Exemplo n.º 1
0
        private UndeploymentResult UndeployRemoveInternal(
            DeploymentInformation info,
            UndeploymentOptions undeploymentOptions)
        {
            var reverted = new DeploymentInformationItem[info.Items.Length];

            for (int i = 0; i < info.Items.Length; i++)
            {
                reverted[i] = info.Items[info.Items.Length - 1 - i];
            }

            var revertedStatements = new List <DeploymentInformationItem>();

            if (undeploymentOptions.IsDestroyStatements)
            {
                var referencedTypes = new HashSet <string>();

                Exception firstExceptionEncountered = null;

                foreach (DeploymentInformationItem item in reverted)
                {
                    EPStatement statement = _epService.GetStatement(item.StatementName);
                    if (statement == null)
                    {
                        Log.Debug("Deployment id '" + info.DeploymentId + "' statement name '" + item + "' not found");
                        continue;
                    }
                    referencedTypes.AddAll(_statementEventTypeRef.GetTypesForStatementName(statement.Name));
                    if (statement.IsDisposed)
                    {
                        continue;
                    }
                    try
                    {
                        statement.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Log.Warn("Unexpected exception destroying statement: " + ex.Message, ex);
                        if (firstExceptionEncountered == null)
                        {
                            firstExceptionEncountered = ex;
                        }
                    }
                    revertedStatements.Add(item);
                }
                EPLModuleUtil.UndeployTypes(
                    referencedTypes, _statementEventTypeRef, _eventAdapterService, _filterService);
                revertedStatements.Reverse();

                if (firstExceptionEncountered != null &&
                    _undeployRethrowPolicy ==
                    ConfigurationEngineDefaults.UndeployRethrowPolicy.RETHROW_FIRST)
                {
                    throw firstExceptionEncountered;
                }
            }

            return(new UndeploymentResult(info.DeploymentId, revertedStatements));
        }
Exemplo n.º 2
0
        private async Task <bool> ProcessDeployment(DeploymentInformation deployment)
        {
            try
            {
                var artifactLocation = Path.Join(deployment.DeploymentLocation, "artifacts");
                var artifactFilePath = Path.Join(artifactLocation, $"{deployment.PackageName}-{deployment.Version}.zip");
                // Update database status to unzipping, Unzip artifacts
                var updateStatusResult = await UpdateDeploymentStatus(deployment.Id, DeploymentStatus.Unzipping);

                if (!updateStatusResult.WasSuccessful) /** Log something... once we have a logger */ } {
                await UnzipArtifacts(artifactFilePath, deployment.DeploymentLocation);

                // Update deployment status to running script, Run the provided setup script
                updateStatusResult = await UpdateDeploymentStatus(deployment.Id, DeploymentStatus.RunningScript);

                if (!updateStatusResult.WasSuccessful)                   /** Log something... once we have a logger */
                {
                }

                await RunScript(artifactFilePath);

                // Dump script logs to the webservice

                // Update the status to failed/succeeded.
                updateStatusResult = await UpdateDeploymentStatus(deployment.Id, DeploymentStatus.Done);

                if (!updateStatusResult.WasSuccessful) /** Log something... once we have a logger */ } {
                return(true);
        }
Exemplo n.º 3
0
 public void AddUpdateDeployment(DeploymentInformation descriptor)
 {
     using (_lock.Acquire())
     {
         _deployments.Put(descriptor.DeploymentId, descriptor);
     }
 }
Exemplo n.º 4
0
        private void AddInternal(Module module, String deploymentId)
        {
            var now  = DateTimeOffsetHelper.Now(_timeZone);
            var desc = new DeploymentInformation(
                deploymentId, module, now, now, new DeploymentInformationItem[0], DeploymentState.UNDEPLOYED);

            _deploymentStateService.AddUpdateDeployment(desc);
        }
Exemplo n.º 5
0
        private void AddInternal(Module module, string deploymentId)
        {
            var desc = new DeploymentInformation(
                deploymentId, module, DateTimeEx.GetInstance(_timeZone), DateTimeEx.GetInstance(_timeZone),
                new DeploymentInformationItem[0], DeploymentState.UNDEPLOYED);

            _deploymentStateService.AddUpdateDeployment(desc);
        }
Exemplo n.º 6
0
        /// <summary>
        /// deployes the given deployment information
        /// </summary>
        /// <param name="deployInfo">object containing all the needed deployment information</param>
        public void Deploy(DeploymentInformation deployInfo)
        {
            Show();

            _deployInfo = deployInfo;

            Text = string.Format("Deploying {0} {1}", _deployInfo.NuSpecPackage.Metadata.Id, _deployInfo.NuSpecPackage.Metadata.Version);

            deployInfo.NuGetServer.LastAttemptedDeploy = DateTime.Now;

            OptionsManager.Instance.SaveSettings();
        }
Exemplo n.º 7
0
        /// <summary>
        /// builds the nuPkg file
        /// </summary>
        /// <returns>true if the nuPkg file was build, false otherwise</returns>
        private void BuildNuGetPackage(DeploymentInformation deployInfo, ref string nuPkgFilePath)
        {
            LoggingManager.Instance.Logger.Debug("creating nupkg file");
            //-----create the .nuPkg file in the folder
            //-----first delete any "current" versions of the .nuPkg file by wildcard ( because if revision == "0" that
            //-----  4:th position ".0" in the file name has probably been omitted by the "NuGet pack" command )
            string nuPkgWildcard = string.Format("{0}.*.nupkg", deployInfo.NuSpecPackage.Metadata.Id);

            try
            {
                foreach (var f in Directory.GetFiles(deployInfo.Build.BuildPath, nuPkgWildcard))
                {
                    File.Delete(f);
                }
            }
            catch (Exception ex)
            {
                LoggingManager.Instance.Logger.Warn($@"Error deleting previous ""{nuPkgWildcard}"" files in ""{deployInfo.Build.BuildPath}""", ex);
            }
            var symbolsParam = (deployInfo.Build.DebugInfo == Resources.DebugInfoPdbOnly || deployInfo.Build.DebugInfo == Resources.DebugInfoFull) ? "-Symbols" : "";
            var commands     = new string[]
            {
                $@"cd /D ""{deployInfo.Build.BuildPath}""",
                $@"""{OptionsManager.Instance.Configuration.GeneralOptions.NuGetOptions.ExePath}"" pack ""{deployInfo.NuSpecFileFullName}"" {symbolsParam}"
            };

            nuPkgFilePath = Execute(commands, out string error, expectedOutputFilePattern: nuPkgWildcard, path: deployInfo.Build.BuildPath);
            if (string.IsNullOrEmpty(nuPkgFilePath))
            {
                throw new BuildNuGetPackageFailedExceptions(string.Format("Could not create nuPkg file: {0}.{1}.nupkg", deployInfo.NuSpecPackage.Metadata.Id, deployInfo.NuSpecPackage.Metadata.Version));
            }

            //-----delete the nuSpec file is possible
            if (!deployInfo.ProjectOptions.NuGetOptions.NuSpecOptions.Metadata.UseAny && !deployInfo.ProjectOptions.NuGetOptions.NuSpecOptions.Files.UseFromSettings)
            {
                try
                {
                    File.Delete(deployInfo.NuSpecFileFullName);
                }
                catch (Exception ex)
                {
                    LoggingManager.Instance.Logger.Warn(ex);
                }
            }
            LoggingManager.Instance.Logger.Debug("creating nupkg file finished");
        }
Exemplo n.º 8
0
 public void Remove(string deploymentId)
 {
     using (_iLock.Acquire())
     {
         DeploymentInformation info = _deploymentStateService.GetDeployment(deploymentId);
         if (info == null)
         {
             throw new DeploymentNotFoundException("Deployment by id '" + deploymentId + "' could not be found");
         }
         if (info.State == DeploymentState.DEPLOYED)
         {
             throw new DeploymentStateException(
                       "Deployment by id '" + deploymentId + "' is in deployed state, please undeploy first");
         }
         _deploymentStateService.Remove(deploymentId);
     }
 }
Exemplo n.º 9
0
 public DeploymentResult Deploy(string deploymentId, DeploymentOptions options)
 {
     using (_iLock.Acquire())
     {
         DeploymentInformation info = _deploymentStateService.GetDeployment(deploymentId);
         if (info == null)
         {
             throw new DeploymentNotFoundException("Deployment by id '" + deploymentId + "' could not be found");
         }
         if (info.State == DeploymentState.DEPLOYED)
         {
             throw new DeploymentStateException(
                       "Module by deployment id '" + deploymentId + "' is already in deployed state");
         }
         GetDeploymentOrder(Collections.SingletonList(info.Module), null);
         return(DeployInternal(info.Module, options, deploymentId, info.AddedDate));
     }
 }
Exemplo n.º 10
0
        private UndeploymentResult UndeployInternal(String deploymentId, UndeploymentOptions undeploymentOptions)
        {
            var info = _deploymentStateService.GetDeployment(deploymentId);

            if (info == null)
            {
                throw new DeploymentNotFoundException("Deployment by id '" + deploymentId + "' could not be found");
            }
            if (info.State == DeploymentState.UNDEPLOYED)
            {
                throw new DeploymentStateException("Deployment by id '" + deploymentId + "' is already in undeployed state");
            }

            var result  = UndeployRemoveInternal(info, undeploymentOptions);
            var updated = new DeploymentInformation(deploymentId, info.Module, info.AddedDate, DateTimeOffsetHelper.Now(_timeZone), new DeploymentInformationItem[0], DeploymentState.UNDEPLOYED);

            _deploymentStateService.AddUpdateDeployment(updated);
            return(result);
        }
Exemplo n.º 11
0
        /// <summary>
        /// builds the nuPkg file
        /// </summary>
        /// <returns>true if the nuPkg file was build, false otherwise</returns>
        private void BuildNuGetPackage(DeploymentInformation deployInfo, ref string nuPkgFilePath)
        {
            LoggingManager.Instance.Logger.Debug("creating nupkg file");

            //-----create the .nuPkg file in the folder
            string result;
            string error;

            nuPkgFilePath = Path.Combine(deployInfo.Build.BuildPath, string.Format("{0}.{1}.nupkg", deployInfo.NuSpecPackage.Metadata.Id, deployInfo.NuSpecPackage.Metadata.Version));
            string commandOne = string.Format(@"cd /D ""{0}"" ", deployInfo.Build.BuildPath);
            string commandTwo = string.Format(@" ""{0}"" pack ""{1}"" ", OptionsManager.Instance.Configuration.GeneralOptions.NuGetOptions.ExePath, deployInfo.NuSpecFileFullName);

            LoggingManager.Instance.Logger.Debug(string.Format("executing command [{0}]  and [{1}]", commandOne, commandTwo));
            CommandUtil.ExecuteCommands(new string[] { commandOne, commandTwo }, new string[] { "/C" }, out result, out error);

            //-----make sure the nuPkg file was build
            if (!string.IsNullOrEmpty(error) || !File.Exists(nuPkgFilePath))
            {
                throw new BuildNuGetPackageFailedExceptions(!string.IsNullOrEmpty(error) ? string.Format("An Error occured while creating the nuPkg file: {0}", error) :
                                                            string.Format("Could not create nuPkg file: {0}", nuPkgFilePath));
            }

            //-----delete the nuSpec file is possible
            if (!deployInfo.ProjectOptions.NuGetOptions.NuSpecOptions.Metadata.UseAny && !deployInfo.ProjectOptions.NuGetOptions.NuSpecOptions.Files.UseFromSettings)
            {
                try
                {
                    File.Delete(deployInfo.NuSpecFileFullName);
                }
                catch (Exception ex)
                {
                    LoggingManager.Instance.Logger.Warn(ex);
                }
            }

            LoggingManager.Instance.Logger.Debug("creating nupkg file finished");
        }
Exemplo n.º 12
0
        /// <summary>
        /// called when the worker is supposed to start
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void DoWork(object sender, DoWorkEventArgs e)
        {
            LoggingManager.Instance.Logger.Debug("saving changed started");

            Project activeProject = (Project)((object[])e.Argument)[0];

            DeploymentInformation transit = (DeploymentInformation)((object[])e.Argument)[1];

            //-----save the nuspec file so all the changes can be applied
            try
            {
                XmlUtil.Serialize(transit.NuSpecFileFullName, transit.NuSpecPackage);

                if (transit.ProjectOptions.NuGetOptions.NuSpecOptions.Metadata.UseAny || transit.ProjectOptions.NuGetOptions.NuSpecOptions.Files.UseFromSettings)
                {
                    activeProject.ProjectItems.AddFromFile(transit.NuSpecFileFullName);
                }
            }
            catch (Exception ex)
            {
                throw new IOException(string.Format("Could not serialize the nuspec file: {0}.", transit.NuSpecFileFullName), ex);
            }

            //-----make sure the project is supported
            ProjectInformation projectInformation = OptionsManager.Instance.SupportedProjectInformation.FirstOrDefault(p => activeProject.FullName.EndsWith(p.Extension));

            if (projectInformation == null)
            {
                throw new ProjectNoSupportedException("project is not supported");
            }

            SaveChangesAssembly(activeProject, transit, projectInformation);

            activeProject.Save();

            LoggingManager.Instance.Logger.Debug("saving changed finished");
        }
Exemplo n.º 13
0
        private UndeploymentResult UndeployRemoveInternal(string deploymentId, UndeploymentOptions options)
        {
            using (_iLock.Acquire())
            {
                DeploymentInformation info = _deploymentStateService.GetDeployment(deploymentId);
                if (info == null)
                {
                    throw new DeploymentNotFoundException("Deployment by id '" + deploymentId + "' could not be found");
                }

                UndeploymentResult result;
                if (info.State == DeploymentState.DEPLOYED)
                {
                    result = UndeployRemoveInternal(info, options);
                }
                else
                {
                    result = new UndeploymentResult(
                        deploymentId, Collections.GetEmptyList <DeploymentInformationItem>());
                }
                _deploymentStateService.Remove(deploymentId);
                return(result);
            }
        }
Exemplo n.º 14
0
        public DeploymentOrder GetDeploymentOrder(ICollection <Module> modules, DeploymentOrderOptions options)
        {
            using (_iLock.Acquire())
            {
                if (options == null)
                {
                    options = new DeploymentOrderOptions();
                }
                string[] deployments = _deploymentStateService.Deployments;

                var proposedModules = new List <Module>();
                proposedModules.AddAll(modules);

                var availableModuleNames = new HashSet <string>();
                foreach (Module proposedModule in proposedModules)
                {
                    if (proposedModule.Name != null)
                    {
                        availableModuleNames.Add(proposedModule.Name);
                    }
                }

                // Collect all uses-dependencies of existing modules
                var usesPerModuleName = new Dictionary <string, ISet <string> >();
                foreach (string deployment in deployments)
                {
                    DeploymentInformation info = _deploymentStateService.GetDeployment(deployment);
                    if (info == null)
                    {
                        continue;
                    }
                    if ((info.Module.Name == null) || (info.Module.Uses == null))
                    {
                        continue;
                    }
                    ISet <string> usesSet = usesPerModuleName.Get(info.Module.Name);
                    if (usesSet == null)
                    {
                        usesSet = new HashSet <string>();
                        usesPerModuleName.Put(info.Module.Name, usesSet);
                    }
                    usesSet.AddAll(info.Module.Uses);
                }

                // Collect uses-dependencies of proposed modules
                foreach (Module proposedModule in proposedModules)
                {
                    // check uses-dependency is available
                    if (options.IsCheckUses)
                    {
                        if (proposedModule.Uses != null)
                        {
                            foreach (string uses in proposedModule.Uses)
                            {
                                if (availableModuleNames.Contains(uses))
                                {
                                    continue;
                                }
                                if (IsDeployed(uses))
                                {
                                    continue;
                                }
                                string message = "Module-dependency not found";
                                if (proposedModule.Name != null)
                                {
                                    message += " as declared by module '" + proposedModule.Name + "'";
                                }
                                message += " for uses-declaration '" + uses + "'";
                                throw new DeploymentOrderException(message);
                            }
                        }
                    }

                    if ((proposedModule.Name == null) || (proposedModule.Uses == null))
                    {
                        continue;
                    }
                    ISet <string> usesSet = usesPerModuleName.Get(proposedModule.Name);
                    if (usesSet == null)
                    {
                        usesSet = new HashSet <string>();
                        usesPerModuleName.Put(proposedModule.Name, usesSet);
                    }
                    usesSet.AddAll(proposedModule.Uses);
                }

                var proposedModuleNames = new Dictionary <string, ISet <int> >().WithNullSupport();
                int count = 0;
                foreach (Module proposedModule in proposedModules)
                {
                    ISet <int> moduleNumbers = proposedModuleNames.Get(proposedModule.Name);
                    if (moduleNumbers == null)
                    {
                        moduleNumbers = new SortedSet <int>();
                        proposedModuleNames.Put(proposedModule.Name, moduleNumbers);
                    }
                    moduleNumbers.Add(count);
                    count++;
                }

                var graph      = new DependencyGraph(proposedModules.Count, false);
                int fromModule = 0;
                foreach (Module proposedModule in proposedModules)
                {
                    if ((proposedModule.Uses == null) || (proposedModule.Uses.IsEmpty()))
                    {
                        fromModule++;
                        continue;
                    }
                    var dependentModuleNumbers = new SortedSet <int>();
                    foreach (string use in proposedModule.Uses)
                    {
                        ISet <int> moduleNumbers = proposedModuleNames.Get(use);
                        if (moduleNumbers == null)
                        {
                            continue;
                        }
                        dependentModuleNumbers.AddAll(moduleNumbers);
                    }
                    dependentModuleNumbers.Remove(fromModule);
                    graph.AddDependency(fromModule, dependentModuleNumbers);
                    fromModule++;
                }

                if (options.IsCheckCircularDependency)
                {
                    var circular = graph.FirstCircularDependency;
                    if (circular != null)
                    {
                        string message   = "";
                        string delimiter = "";
                        foreach (int i in circular)
                        {
                            message  += delimiter;
                            message  += "module '" + proposedModules[i].Name + "'";
                            delimiter = " uses (depends on) ";
                        }
                        throw new DeploymentOrderException(
                                  "Circular dependency detected in module uses-relationships: " + message);
                    }
                }

                var reverseDeployList = new List <Module>();
                var ignoreList        = new HashSet <int>();
                while (ignoreList.Count < proposedModules.Count)
                {
                    // secondary sort according to the order of listing
                    ICollection <int> rootNodes = new SortedSet <int>(
                        new StandardComparer <int>((o1, o2) => - 1 * o1.CompareTo(o2)));

                    rootNodes.AddAll(graph.GetRootNodes(ignoreList));

                    if (rootNodes.IsEmpty())
                    {
                        // circular dependency could cause this
                        for (int i = 0; i < proposedModules.Count; i++)
                        {
                            if (!ignoreList.Contains(i))
                            {
                                rootNodes.Add(i);
                                break;
                            }
                        }
                    }

                    foreach (int root in rootNodes)
                    {
                        ignoreList.Add(root);
                        reverseDeployList.Add(proposedModules[root]);
                    }
                }

                reverseDeployList.Reverse();
                return(new DeploymentOrder(reverseDeployList));
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// build the project using the given msbuild exe
        /// </summary>
        /// <param name="msBuildPath">full path to the msbuild exe to use</param>
        /// <returns>true if the build process was successful, false otherwise</returns>
        private void BuildProject(DeploymentInformation deployInfo)
        {
            LoggingManager.Instance.Logger.Debug("building project");

            //-----start the build process of the project
            string result;
            string error;

            if (!Directory.Exists(deployInfo.Build.BuildPath))
            {
                LoggingManager.Instance.Logger.Debug(string.Format("creating directory {0}", deployInfo.Build.BuildPath));
                Directory.CreateDirectory(deployInfo.Build.BuildPath);
            }

            string buildFileFullname = Path.Combine(deployInfo.Build.BuildPath, deployInfo.OutputFileName);

            StringBuilder command = new StringBuilder(string.Format(@"{0} ""{1}"" ", deployInfo.MsBuildFullName, deployInfo.ProjectFullName));

            command.Append(string.Format(@" /p:Configuration=""{0}"" ", deployInfo.Build.ConfigurationName));

            command.Append(string.Format(@" /p:Platform=""{0}"" ", deployInfo.Build.PlatformName));

            command.Append(string.Format(@" /p:OutputPath=""{0}"" ", deployInfo.Build.BuildPath));

            if (deployInfo.ProjectOptions.MsBuildOptions.Usage.Optimize.Useage != Enumerations.Useage.None && deployInfo.Build.Optimize != null)
            {
                command.Append(string.Format(@" /p:Optimize={0} ", deployInfo.Build.Optimize.ToString()));
            }

            if (deployInfo.ProjectOptions.MsBuildOptions.Usage.DebugConstants.Useage != Enumerations.Useage.None && !string.IsNullOrEmpty(deployInfo.Build.DebugConstants))
            {
                command.Append(string.Format(@" /p:DefineConstants=""{0}"" ", deployInfo.Build.DebugConstants));
            }

            if (deployInfo.ProjectOptions.MsBuildOptions.Usage.DebugInfo.Useage != Enumerations.Useage.None && !string.IsNullOrEmpty(deployInfo.Build.DebugInfo))
            {
                command.Append(string.Format(@" /p:DebugSymbols=true /p:DebugType={0} ", deployInfo.Build.DebugInfo.ToString()));
            }

            if (deployInfo.Build.DocumentationFile != null)
            {
                command.Append(string.Format(@" /p:DocumentationFile=""{0}"" ", deployInfo.Build.DocumentationFile.Source));
            }

            LoggingManager.Instance.Logger.Debug(string.Format("executing command [{0}]", command.ToString()));
            CommandUtil.ExecuteCommand(command.ToString(), new string[] { "/C" }, out result, out error);

            //-----make sure the build process was successfull
            if (!string.IsNullOrEmpty(error) || !File.Exists(buildFileFullname))
            {
                //HACK should be reworked since it is not very save, but currently the only way
                if (string.IsNullOrEmpty(error) && deployInfo.ProjectOptions.Identifier == Enumerations.ProjectIdentifier.CPP)
                {
                    Xml.NuGet.NuSpec.File fileDll = deployInfo.NuSpecPackage.Files.FirstOrDefault(f => f.Source == buildFileFullname);
                    Xml.NuGet.NuSpec.File filePdb = deployInfo.NuSpecPackage.Files.FirstOrDefault(f => f.Source == StringUtil.ReplaceLastOccurrence(buildFileFullname, Resources.ExtensionDLL, Resources.ExtensionPDB));

                    if (fileDll != null)
                    {
                        deployInfo.Build.BuildPath = Path.Combine(Path.GetDirectoryName(deployInfo.ProjectFullName), deployInfo.Build.PlatformName, deployInfo.Build.ConfigurationName);

                        buildFileFullname = Path.Combine(deployInfo.Build.BuildPath, deployInfo.OutputFileName);

                        LoggingManager.Instance.Logger.Warn(string.Format("could not create the orignal file for cpp project, checking if file {0} exists", buildFileFullname));

                        if (File.Exists(buildFileFullname))
                        {
                            fileDll.Source = buildFileFullname;

                            if (filePdb != null)
                            {
                                filePdb.Source = StringUtil.ReplaceLastOccurrence(buildFileFullname, Resources.ExtensionDLL, Resources.ExtensionPDB);
                            }

                            XmlUtil.Serialize(deployInfo.NuSpecFileFullName, deployInfo.NuSpecPackage);

                            return;
                        }
                    }
                }
                throw new ProjectBuildFailedExceptions(!string.IsNullOrEmpty(error) ? string.Format("An Error occured during the build process: {0}", error) :
                                                       string.Format("Could not create file: {0}", buildFileFullname));
            }
            LoggingManager.Instance.Logger.Debug("building project finished");
        }
Exemplo n.º 16
0
        private DeploymentResult DeployInternal(Module module, DeploymentOptions options, String deploymentId, DateTimeOffset addedDate)
        {
            if (options == null)
            {
                options = new DeploymentOptions();
            }

            if (Log.IsDebugEnabled)
            {
                Log.Debug("Deploying module " + module);
            }
            IList <String> imports;

            if (module.Imports != null)
            {
                foreach (var imported in module.Imports)
                {
                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug("Adding import " + imported);
                    }
                    _epService.Configuration.AddImport(imported);
                }
                imports = new List <String>(module.Imports);
            }
            else
            {
                imports = Collections.GetEmptyList <string>();
            }

            if (options.IsCompile)
            {
                var itemExceptions = new List <DeploymentItemException>();
                foreach (var item in module.Items)
                {
                    if (item.IsCommentOnly)
                    {
                        continue;
                    }

                    try {
                        _epService.CompileEPL(item.Expression);
                    }
                    catch (Exception ex) {
                        itemExceptions.Add(new DeploymentItemException(ex.Message, item.Expression, ex, item.LineNumber));
                    }
                }

                if (itemExceptions.IsNotEmpty())
                {
                    throw BuildException("Compilation failed", module, itemExceptions);
                }
            }

            if (options.IsCompileOnly)
            {
                return(null);
            }

            var exceptions           = new List <DeploymentItemException>();
            var statementNames       = new List <DeploymentInformationItem>();
            var statements           = new List <EPStatement>();
            var eventTypesReferenced = new HashSet <String>();

            foreach (var item in module.Items)
            {
                if (item.IsCommentOnly)
                {
                    continue;
                }

                String statementName = null;
                Object userObject    = null;
                if (options.StatementNameResolver != null || options.StatementUserObjectResolver != null)
                {
                    var ctx = new StatementDeploymentContext(item.Expression, module, item, deploymentId);
                    statementName = options.StatementNameResolver != null?options.StatementNameResolver.GetStatementName(ctx) : null;

                    userObject = options.StatementUserObjectResolver != null?options.StatementUserObjectResolver.GetUserObject(ctx) : null;
                }

                try {
                    EPStatement stmt;
                    if (_optionalStatementIdGenerator == null)
                    {
                        if (options.IsolatedServiceProvider == null)
                        {
                            stmt = _epService.CreateEPL(item.Expression, statementName, userObject);
                        }
                        else
                        {
                            var unit = _statementIsolationService.GetIsolationUnit(options.IsolatedServiceProvider, -1);
                            stmt = unit.EPAdministrator.CreateEPL(item.Expression, statementName, userObject);
                        }
                    }
                    else
                    {
                        var statementId = _optionalStatementIdGenerator.Invoke();
                        if (options.IsolatedServiceProvider == null)
                        {
                            stmt = _epService.CreateEPLStatementId(item.Expression, statementName, userObject, statementId);
                        }
                        else
                        {
                            var unit = _statementIsolationService.GetIsolationUnit(options.IsolatedServiceProvider, -1);
                            var spi  = (EPAdministratorIsolatedSPI)unit.EPAdministrator;
                            stmt = spi.CreateEPLStatementId(item.Expression, statementName, userObject, statementId);
                        }
                    }
                    statementNames.Add(new DeploymentInformationItem(stmt.Name, stmt.Text));
                    statements.Add(stmt);

                    ICollection <String> types = _statementEventTypeRef.GetTypesForStatementName(stmt.Name);
                    if (types != null)
                    {
                        eventTypesReferenced.AddAll(types);
                    }
                }
                catch (EPException ex) {
                    exceptions.Add(new DeploymentItemException(ex.Message, item.Expression, ex, item.LineNumber));
                    if (options.IsFailFast)
                    {
                        break;
                    }
                }
            }

            if (exceptions.IsNotEmpty())
            {
                if (options.IsRollbackOnFail)
                {
                    Log.Debug("Rolling back intermediate statements for deployment");
                    foreach (var stmt in statements)
                    {
                        try {
                            stmt.Dispose();
                        }
                        catch (Exception ex) {
                            Log.Debug("Failed to destroy created statement during rollback: " + ex.Message, ex);
                        }
                    }
                    EPLModuleUtil.UndeployTypes(eventTypesReferenced, _statementEventTypeRef, _eventAdapterService, _filterService);
                }
                var text = "Deployment failed";
                if (options.IsValidateOnly)
                {
                    text = "Validation failed";
                }
                throw BuildException(text, module, exceptions);
            }

            if (options.IsValidateOnly)
            {
                Log.Debug("Rolling back created statements for validate-only");
                foreach (var stmt in statements)
                {
                    try {
                        stmt.Dispose();
                    }
                    catch (Exception ex) {
                        Log.Debug("Failed to destroy created statement during rollback: " + ex.Message, ex);
                    }
                }
                EPLModuleUtil.UndeployTypes(eventTypesReferenced, _statementEventTypeRef, _eventAdapterService, _filterService);
                return(null);
            }

            var deploymentInfoArr = statementNames.ToArray();
            var desc = new DeploymentInformation(deploymentId, module, addedDate.TranslateTo(_timeZone), DateTime.Now, deploymentInfoArr, DeploymentState.DEPLOYED);

            _deploymentStateService.AddUpdateDeployment(desc);

            if (Log.IsDebugEnabled)
            {
                Log.Debug("Module " + module + " was successfully deployed.");
            }
            return(new DeploymentResult(desc.DeploymentId, statements.AsReadOnlyList(), imports));
        }
Exemplo n.º 17
0
 public Task RunScript(string scriptPath, DeploymentInformation deployment)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 18
0
        /// <summary>
        /// called when the worker is supposed to start
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void DoWork(object sender, DoWorkEventArgs e)
        {
            LoggingManager.Instance.Logger.Debug("staring deployment process");

            DeploymentInformation deployInfo = (DeploymentInformation)e.Argument;

            int interval = 0;

            if (deployInfo.Step == Step.Deploy)
            {
                interval = 33;
            }
            else if (deployInfo.Step == Step.Package)
            {
                interval = 50;
            }
            else if (deployInfo.Step == Step.Build)
            {
                interval = 100;
            }

            bool isLocked = false;

            using (Mutex mutex = new Mutex(true, deployInfo.ProjectFullName.GetHashCode().ToString()))
            {
                //-----start the deployment process
                try
                {
                    isLocked = mutex.WaitOne();

                    //-----build project
                    if (!_worker.CancellationPending)
                    {
                        _worker.ReportProgress(0 * interval, "Building project...");
                        BuildProject(deployInfo);
                    }
                    //----check if only the build was needed
                    if (deployInfo.Step == Step.Build)
                    {
                        e.Result = string.Format("project successfully build at location {0}", deployInfo.Build.BuildPath);
                        return;
                    }

                    //-----build nuPkgfile from nuSpec file
                    string nuPkgFilePath = null;
                    if (!_worker.CancellationPending)
                    {
                        _worker.ReportProgress(1 * interval, "Creating NuGet package...");
                        BuildNuGetPackage(deployInfo, ref nuPkgFilePath);
                    }
                    //----check if only the packaing was needed
                    if (deployInfo.Step == Step.Package)
                    {
                        e.Result = string.Format("project successfully packaged at location {0}", deployInfo.Build.BuildPath);
                        return;
                    }

                    //-----push nuPkg file
                    if (!_worker.CancellationPending)
                    {
                        _worker.ReportProgress(2 * interval, "Deploying NuGet package to server...");
                        PushNuGetPackage(deployInfo.NuGetServer.Url, ExtensionManager.Instance.Encryptor.Decrypt(deployInfo.NuGetServer.ApiKey), nuPkgFilePath);
                    }
                    e.Result = string.Format("package successfully pushed to server {0}", deployInfo.NuGetServer.Url);
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    e.Cancel = _worker.CancellationPending;

                    if (isLocked)
                    {
                        mutex.ReleaseMutex();
                    }
                }
            }
        }