public string Configure(string cartName, string templateGitUrl, string manifest)
        {
            StringBuilder sb = new StringBuilder();

            this.CartridgeName = cartName;            
            string name = cartName.Split('-')[0];
            string softwareVersion = cartName.Split('-')[1];
            Manifest cartridge = null;
            if (!string.IsNullOrEmpty(manifest))
            {
                Logger.Debug("Loading from manifest... {0}", manifest);
                cartridge = new Manifest(manifest, softwareVersion);
            }
            else
            {
                cartridge = CartridgeRepository.Instance.Select(name, softwareVersion);
            }
           
            CreateCartridgeDirectory(cartridge, softwareVersion);
            this.CreatePrivateEndpoints(cartridge);
            this.CreateDependencyDirectories(cartridge);
            sb.AppendLine(CartridgeAction(cartridge, "setup", softwareVersion, true));
            sb.AppendLine(CartridgeAction(cartridge, "install", softwareVersion));
            sb.AppendLine(PopulateGearRepo(name, templateGitUrl));
            return sb.ToString();
        }
        public string GenerateEndpointCreationNotificationMsg(Manifest cart, Endpoint endpoint, string privateIpValue, string publicPortValue)
        {

            Dictionary<string, object> endpointCreateHash = new Dictionary<string, object>()
            {
                { "cartridge_name", string.Format("{0}-{1}", cart.Name, cart.Version) },
                { "external_address", NodeConfig.Values["PUBLIC_IP"] },
                { "external_port", publicPortValue },
                { "internal_address", privateIpValue },
                { "internal_port", endpoint.PrivatePort },
                { "protocols", endpoint.Protocols },
                { "description", endpoint.Description },
                { "type", new string[0] }
            };

            if (cart.Categories.Contains("web_framework"))
            {
                endpointCreateHash["type"] = new string[] { "web_framework" };
            }
            else if (cart.Categories.Contains("database"))
            {
                endpointCreateHash["type"] = new string[] { "database" };
            }
            else if (cart.Categories.Contains("plugin"))
            {
                endpointCreateHash["type"] = new string[] { "plugin" };
            }
            else
            {
                endpointCreateHash["type"] = new string[] { "other" };
            }

            if (endpoint.Mappings != null)
            {
                endpointCreateHash["mappings"] = endpoint.Mappings.Select(m =>
                {
                    return new Dictionary<string, string>()
                    {
                        { "frontend", m.Frontend },
                        { "backend", m.Backend }
                    };
                }).ToArray();
            }

            return string.Format("NOTIFY_ENDPOINT_CREATE: {0}\n", JsonConvert.SerializeObject(endpointCreateHash));
        }
        public string StartCartridge(string action, Manifest cartridge, dynamic options)
        {
            options = (Dictionary<string, object>)options;
            if (!options.ContainsKey("user_initiated"))
            {
                options.Add("user_initiated", true);
            }

            if (!options.ContainsKey("hot_deploy"))
            {
                options.Add("hot_deploy", false);
            }

            if (!options["user_initiated"] && StopLockExists)
            {
                return string.Format("Not starting cartridge {0} because the application was explicitly stopped by the user", cartridge.Name);
            }

            Manifest primaryCartridge = GetPrimaryCartridge();            

            if (primaryCartridge != null)
            {
                if (primaryCartridge.Name == cartridge.Name)
                {
                    if (options["user_initiated"])
                    {
                        File.Delete(StopLock);
                    }
                    state.Value(State.STARTED);

                //TODO : Unidle the application
                }
            }

            if (options["hot_deploy"])
            {
                return string.Format("Not starting cartridge {0} because hot deploy is enabled", cartridge.Name);
            }

            return DoControl(action, cartridge, options);
        }
        public string StopCartridge(Manifest cartridge, dynamic options)
        {
            Logger.Debug("Stopping cartridge {0} for gear {1}", cartridge.Name, this.container.Uuid);

            if (options == null)
            {
                options = new Dictionary<string, object>();
            }
            options = (Dictionary<string, object>)options;
            if (!options.ContainsKey("user_initiated"))
            {
                options.Add("user_initiated", true);
            }

            if (!options.ContainsKey("hot_deploy"))
            {
                options.Add("hot_deploy", false);
            }

            if (options["hot_deploy"])
            {
                return string.Format("Not stopping cartridge {0} because hot deploy is enabled", cartridge.Name);
            }

            if (!options["user_initiated"] && StopLockExists)
            {
                return string.Format("Not stopping cartridge {0} because the application was explicitly stopped by the user", cartridge.Name);
            }

            Manifest primaryCartridge = GetPrimaryCartridge();
            if (primaryCartridge != null)
            {
                if (cartridge.Name == primaryCartridge.Name)
                {
                    if (options["user_initiated"])
                    {
                        CreateStopLock();
                    }
                    state.Value(State.STOPPED);
                }
            }

            return DoControl("stop", cartridge, options);
        }
 internal List<string> BuildDependencyDirs(Manifest cartridge)
 {
     throw new NotImplementedException();
 }
Exemple #6
0
        public static void InstantiateCartridge(Manifest cartridge, string target, bool failureRemove = true)
        {
            Directory.CreateDirectory(target);
            try
            {
                bool downloadable = cartridge.ManifestPath == "url";

                if (downloadable)
                {
                    Uri    uri       = new Uri(cartridge.SourceUrl);
                    string temporary = Path.Combine(target, Path.GetFileName(uri.LocalPath));

                    if (uri.Scheme == "git" || cartridge.SourceUrl.EndsWith(".git"))
                    {
                        // use intermediate temp directory to reset cygwin directories ACLs
                        string tempRepo    = cartridge.Name + ".temp";
                        string tempRepoDir = Path.Combine(new DirectoryInfo(target).Parent.FullName, tempRepo);
                        try
                        {
                            string template = @"{0} clone {1} {2}
set GIT_DIR=./{2}/.git
{0} repack";
                            string file     = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + "cmd.bat");
                            File.WriteAllText(file, string.Format(template, Path.Combine(NodeConfig.Values["SSHD_BASE_DIR"], @"bin\git.exe"), cartridge.SourceUrl, tempRepo));
                            ProcessResult result = ProcessExtensions.RunCommandAndGetOutput("cmd.exe", string.Format("/c {0}", file), new DirectoryInfo(target).Parent.FullName);
                            if (result.ExitCode != 0)
                            {
                                throw new Exception(string.Format("Unable to clone cartridge from {0} stdout: {1} stderr {2}", cartridge.SourceUrl, result.StdOut, result.StdErr));
                            }

                            DirectoryUtil.DirectoryCopy(tempRepoDir, target, true);
                        }
                        finally
                        {
                            if (Directory.Exists(tempRepoDir))
                            {
                                Directory.Delete(tempRepoDir, true);
                            }
                        }
                    }
                    else if (Regex.IsMatch(uri.Scheme, @"^https*") && Regex.IsMatch(cartridge.SourceUrl, @"\.zip"))
                    {
                        try
                        {
                            UriCopy(new Uri(cartridge.SourceUrl), temporary, cartridge.SourceMD5);
                            Extract("zip", temporary, target);
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex.ToString());
                            throw ex;
                        }
                        finally
                        {
                            if (File.Exists(temporary))
                            {
                                File.Delete(temporary);
                            }
                        }
                    }
                    else if (Regex.IsMatch(uri.Scheme, @"^https*") && Regex.IsMatch(cartridge.SourceUrl, @"(\.tar\.gz|\.tgz)$"))
                    {
                        try
                        {
                            UriCopy(new Uri(cartridge.SourceUrl), temporary, cartridge.SourceMD5);
                            Extract("tgz", temporary, target);
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex.ToString());
                            throw ex;
                        }
                        finally
                        {
                            if (File.Exists(temporary))
                            {
                                File.Delete(temporary);
                            }
                        }
                    }
                    else if (Regex.IsMatch(uri.Scheme, @"^https*") && Regex.IsMatch(cartridge.SourceUrl, @"\.tar$"))
                    {
                        try
                        {
                            UriCopy(new Uri(cartridge.SourceUrl), temporary, cartridge.SourceMD5);
                            Extract("tar", temporary, target);
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex.ToString());
                            throw ex;
                        }
                        finally
                        {
                            if (File.Exists(temporary))
                            {
                                File.Delete(temporary);
                            }
                        }
                    }
                    else if (uri.Scheme == "file")
                    {
                        DirectoryUtil.DirectoryCopy(uri.LocalPath, target, true);
                    }
                    else
                    {
                        throw new ArgumentException(string.Format("CLIENT_ERROR: Unsupported URL({0}) for downloading a private cartridge", cartridge.SourceUrl));
                    }
                }
                else
                {
                    // TODO exclude usr folder and use link
                    DirectoryUtil.DirectoryCopy(cartridge.RepositoryPath, target, true);
                }

                ValidateCartridgeHome(cartridge, target);

                if (downloadable)
                {
                    string manifestOnDisk = Path.Combine(target, "metadata", "manifest.yml");
                    using (StreamWriter sw = new StreamWriter(manifestOnDisk))
                    {
                        Serializer ser = new Serializer(SerializationOptions.None);
                        ser.Serialize(sw, cartridge.ManifestSpec);
                    }
                }
            }
            catch (Exception e)
            {
                if (failureRemove)
                {
                    if (Directory.Exists(target))
                    {
                        Directory.Delete(target);
                    }
                }
                throw e;
            }
        }
        public void CreatePrivateEndpoints(Manifest cartridge)
        {
            if (cartridge == null)
            {
                throw new ArgumentNullException("cartridge");
            }

            if (cartridge.Endpoints == null || cartridge.Endpoints.Count == 0)
            {
                return;
            }

            foreach (Endpoint endpoint in cartridge.Endpoints)
            {
                string privateIp = "0.0.0.0";
                container.AddEnvVar(endpoint.PrivateIpName, privateIp);

                string port = container.ReadEnvVar("PRISON_PORT");

                if (string.IsNullOrWhiteSpace(port))
                {
                    Logger.Error("No prison port available for gear {0}", this.container.Uuid);
                    throw new Exception(string.Format("No prison port available for gear {0}", this.container.Uuid));
                }

                container.AddEnvVar(endpoint.PrivatePortName, port);

                //if (!string.IsNullOrWhiteSpace(endpoint.WebsocketPortName) && !string.IsNullOrWhiteSpace(endpoint.WebsocketPort))
                //{
                //    string websocketPort = endpoint.WebsocketPort == "0" ? Network.GrabEphemeralPort().ToString() : endpoint.WebsocketPort;
                //    container.AddEnvVar(endpoint.WebsocketPortName, websocketPort);
                //}
            }
        }
        public string CartridgeAction(Manifest cartridge, string action, string softwareVersion, bool renderErbs = false)
        {
            string cartridgeHome = Path.Combine(this.container.ContainerDir, cartridge.Dir);
            bool ps = false;
            if (File.Exists(Path.Combine(cartridgeHome, "bin", action + ".exe")))
            {
                action = Path.Combine(cartridgeHome, "bin", action + ".exe");
            }
            else
            {
                action = Path.Combine(cartridgeHome, "bin", action + ".ps1");
                ps = true;
            }
            if (!File.Exists(action))
            {
                return string.Empty;
            }

            Dictionary<string, string> gearEnv = Environ.ForGear(this.container.ContainerDir);
            string cartridgeEnvHome = Path.Combine(cartridgeHome, "env");
            Dictionary<string, string> cartridgeEnv = Environ.Load(cartridgeEnvHome);
            cartridgeEnv.Remove("PATH");
            foreach (var kvp in gearEnv)
            {
                cartridgeEnv[kvp.Key] = kvp.Value;
            }
            if (renderErbs)
            {
                // TODO: render erb
            }

            // TODO: vladi: implement hourglass
            string cmd = null;
            if (ps)
            {
                cmd = string.Format("{0} -ExecutionPolicy Bypass -InputFormat None -noninteractive -file {1} --version {2}", ProcessExtensions.Get64BitPowershell(), action, softwareVersion);
            }
            else
            {
                cmd = string.Format("{0} --version {1}", action, softwareVersion);
            }
            string output = this.container.RunProcessInContainerContext(cartridgeHome, cmd, 0).StdOut;

            // TODO: vladi: add logging
            return output;
        }
        public static void InstantiateCartridge(Manifest cartridge, string target, bool failureRemove = true)
        {
            Directory.CreateDirectory(target);
            try
            {
                bool downloadable = cartridge.ManifestPath == "url";

                if (downloadable)
                {
                    Uri uri = new Uri(cartridge.SourceUrl);
                    string temporary = Path.Combine(target, Path.GetFileName(uri.LocalPath));

                    if (uri.Scheme == "git" || cartridge.SourceUrl.EndsWith(".git"))
                    {
                        // use intermediate temp directory to reset cygwin directories ACLs
                        string tempRepo = cartridge.Name + ".temp";
                        string tempRepoDir = Path.Combine(new DirectoryInfo(target).Parent.FullName, tempRepo);
                        try
                        {
                            string template = @"{0} clone {1} {2}
set GIT_DIR=./{2}/.git
{0} repack";
                            string file = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + "cmd.bat");
                            File.WriteAllText(file, string.Format(template, Path.Combine(NodeConfig.Values["SSHD_BASE_DIR"], @"bin\git.exe"), cartridge.SourceUrl, tempRepo));
                            ProcessResult result = ProcessExtensions.RunCommandAndGetOutput("cmd.exe", string.Format("/c {0}", file), new DirectoryInfo(target).Parent.FullName);
                            if (result.ExitCode != 0)
                            {
                                throw new Exception(string.Format("Unable to clone cartridge from {0} stdout: {1} stderr {2}", cartridge.SourceUrl, result.StdOut, result.StdErr));
                            }

                            DirectoryUtil.DirectoryCopy(tempRepoDir, target, true);
                        }
                        finally
                        {
                            if (Directory.Exists(tempRepoDir))
                            {
                                Directory.Delete(tempRepoDir, true);
                            }
                        }                        
                    }
                    else if (Regex.IsMatch(uri.Scheme, @"^https*") && Regex.IsMatch(cartridge.SourceUrl, @"\.zip"))
                    {
                        try
                        {
                            UriCopy(new Uri(cartridge.SourceUrl), temporary, cartridge.SourceMD5);
                            Extract("zip", temporary, target);
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex.ToString());
                            throw ex;
                        }
                        finally
                        {
                            if (File.Exists(temporary))
                            {
                                File.Delete(temporary);
                            }
                        }
                    }
                    else if (Regex.IsMatch(uri.Scheme, @"^https*") && Regex.IsMatch(cartridge.SourceUrl, @"(\.tar\.gz|\.tgz)$"))
                    {
                        try
                        {
                            UriCopy(new Uri(cartridge.SourceUrl), temporary, cartridge.SourceMD5);
                            Extract("tgz", temporary, target);
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex.ToString());
                            throw ex;
                        }
                        finally
                        {
                            if (File.Exists(temporary))
                            {
                                File.Delete(temporary);
                            }
                        }
                    }
                    else if (Regex.IsMatch(uri.Scheme, @"^https*") && Regex.IsMatch(cartridge.SourceUrl, @"\.tar$"))
                    {
                        try
                        {
                            UriCopy(new Uri(cartridge.SourceUrl), temporary, cartridge.SourceMD5);
                            Extract("tar", temporary, target);
                        }
                        catch(Exception ex)
                        {
                            Logger.Error(ex.ToString());
                            throw ex;
                        }
                        finally
                        {
                            if (File.Exists(temporary))
                            {
                                File.Delete(temporary);
                            }
                        }
                    }
                    else if (uri.Scheme == "file")
                    {
                        DirectoryUtil.DirectoryCopy(uri.LocalPath, target, true);
                    }
                    else
                    {
                        throw new ArgumentException(string.Format("CLIENT_ERROR: Unsupported URL({0}) for downloading a private cartridge", cartridge.SourceUrl));
                    }
                }
                else
                {
                    // TODO exclude usr folder and use link
                    DirectoryUtil.DirectoryCopy(cartridge.RepositoryPath, target, true);
                }

                ValidateCartridgeHome(cartridge, target);

                if (downloadable)
                {
                    string manifestOnDisk = Path.Combine(target, "metadata", "manifest.yml");
                    using (StreamWriter sw = new StreamWriter(manifestOnDisk))
                    {
                        Serializer ser = new Serializer(SerializationOptions.None);
                        ser.Serialize(sw, cartridge.ManifestSpec);
                    }
                }
            }
            catch(Exception e)
            {
                if (failureRemove)
                {
                    if (Directory.Exists(target))
                    {
                        Directory.Delete(target);
                    }
                }
                throw e;
            }
        }
 public static void  OverlayCartridge(Manifest cartridge, string target)
 {
     InstantiateCartridge(cartridge, target, false);
 }
        public Manifest Insert(Manifest cartridge)
        {
            string name = cartridge.Name;
            string cartridgeVersion = cartridge.CartridgeVersion;

            foreach(string version in Manifest.SortVersions(cartridge.Versions))
            {
                Manifest projectedCartridge = cartridge.ProjectVersionOverrides(version, path);
                Index[name] = new Dictionary<string, Dictionary<string, Manifest>>();
                Index[name][version] = new Dictionary<string, Manifest>();
                Index[name][version][cartridgeVersion] = projectedCartridge;
                Index[name][version]["_"] = projectedCartridge;
            }

            return cartridge;
        }
        public bool InstalledInBasePath(string cartridgeName, string version, string cartridgeVersion)
        {
            string cartridgePath = Path.Combine(CartridgeBasePath, cartridgeName);
            if(!Directory.Exists(cartridgePath))
            {
                return false;
            }

            string manifestPath = Path.Combine(cartridgePath, "metadata", "manifest.yml");
            if(!File.Exists(manifestPath))
            {
                return false;
            }

            bool error = false;

            Manifest manifest = null;
            try
            {
                manifest = new Manifest(manifestPath, null, "file");
            }
            catch
            {
                error = true;
            }

            return (!error && manifest.Versions.Contains(version) && manifest.CartridgeVersion == cartridgeVersion);
        }
        public RubyHash UpdateRemoteProxyStatus(RubyHash args)
        {
            RubyHash result      = new RubyHash();
            string   currentGear = args["current_gear"];

            GearRegistry.Entry proxyGear  = args["proxy_gear"];
            object             targetGear = args["target_gear"];
            Manifest           cartridge  = args["cartridge"];
            string             action     = args["action"];
            bool   persist = args["persist"] != null && args["persist"] == true;
            object gearEnv = args["gear_env"];

            if (currentGear == proxyGear.Uuid)
            {
                // self, no need to ssh
                return(this.UpdateLocalProxyStatus(new RubyHash()
                {
                    { "cartridge", cartridge },
                    { "action", action },
                    { "target_gear", targetGear },
                    { "persist", persist }
                }));
            }

            string direction     = action == "enable" ? "in" : "out";
            string persistOption = persist ? "--persist" : "";

            string url = string.Format("{0}@{1}", proxyGear.Uuid, proxyGear.ProxyHostname);

            string ooSSH      = @"/cygpath/c/openshift/oo-bin/oo-ssh";
            string bashBinary = Path.Combine(NodeConfig.Values["SSHD_BASE_DIR"], "bin\bash.exe");

            string sshCommand = string.Format("{0} {1} gear rotate-{2} --gear {3} {4} --cart {5}-{6} --as-json",
                                              ooSSH, url, direction, targetGear, persistOption, cartridge.Name, cartridge.Version);

            string bashArgs = string.Format("--norc --login -c '{0}'", sshCommand);

            string command = string.Format("{0} {1}", bashBinary, bashArgs);

            try
            {
                ProcessResult processResult = this.RunProcessInContainerContext(this.ContainerDir, command, 0);

                if (string.IsNullOrEmpty(processResult.StdOut))
                {
                    throw new Exception("No result JSON was received from the remote proxy update call");
                }

                result = JsonConvert.DeserializeObject <RubyHash>(processResult.StdOut);

                if (!result.ContainsKey("status"))
                {
                    throw new Exception(string.Format("Invalid result JSON received from remote proxy update call: {0}", processResult.StdOut));
                }
            }
            catch (Exception ex)
            {
                result = new RubyHash()
                {
                    { "status", RESULT_FAILURE },
                    { "proxy_gear_uuid", proxyGear.Uuid },
                    { "messages", new List <string>() },
                    { "errors", new List <string> {
                          string.Format("An exception occured updating the proxy status: {0}\n{1}", ex.Message, ex.StackTrace)
                      } }
                };
            }

            return(result);
        }
 internal List <string> BuildDependencyDirs(Manifest cartridge)
 {
     throw new NotImplementedException();
 }
 public string DoControl(string action, Manifest cartridge, dynamic options = null)
 {
     if (options == null)
     {
         options = new Dictionary<string, string>();
     }
     options["cartridgeDir"] = cartridge.Dir;
     return DoControlWithDirectory(action, options);
 }
        public Manifest GetCartridgeFromDirectory(string cartDir)
        {
            if(string.IsNullOrEmpty(cartDir))
            {
                throw new ArgumentNullException("Directory name is required");
            }

            if (!this.cartridges.ContainsKey(cartDir))
            {
                string cartPath = Path.Combine(container.ContainerDir, cartDir);
                string manifestPath = Path.Combine(cartPath, "metadata", "manifest.yml");
                string identPath = Directory.GetFiles(Path.Combine(cartPath, "env"), "OPENSHIFT_*_IDENT").FirstOrDefault();

                if(!File.Exists(manifestPath))
                {
                    throw new Exception(string.Format("Cartridge manifest not found: {0} missing", manifestPath));
                }

                if(identPath == null)
                {
                    throw new Exception(string.Format("Cartridge Ident not found in {0}", cartPath));
                }

                string version = Manifest.ParseIdent(File.ReadAllText(identPath))[2];
                Manifest cartridge = new Manifest(manifestPath, version, "file", this.container.ContainerDir);
                this.cartridges[cartDir] = cartridge;
            }
            return this.cartridges[cartDir];
        }
 private static void ValidateCartridgeHome(Manifest cartridge, string path)
 {
     List<string> errors = new List<string>();
     if(!Directory.Exists(Path.Combine(path, "metadata")))
     {
         errors.Add(Path.Combine(path, "metadata") + "is not a directory");
     }
     if (!Directory.Exists(Path.Combine(path, "bin")))
     {
         errors.Add(Path.Combine(path, "bin") + "is not a directory");
     }
     if (!File.Exists(Path.Combine(path, "metadata", "manifest.yml")))
     {
         errors.Add(Path.Combine(path, "metadata", "manifest.yml") + "is not a file");
     }
     if(errors.Count != 0)
     {
         throw new MalformedCartridgeException(string.Format("CLIENT_ERROR: Malformed cartridge ({0}, {1}, {2})", cartridge.Name, cartridge.Version, cartridge.CartridgeVersion), errors.ToArray());
     }
 }
        private void CreateCartridgeDirectory(Manifest cartridge, string softwareVersion)
        {
            string target = Path.Combine(this.container.ContainerDir, cartridge.Dir);
            CartridgeRepository.InstantiateCartridge(cartridge, target);

            string ident = Manifest.BuildIdent(cartridge.CartridgeVendor, cartridge.Name, softwareVersion, cartridge.CartridgeVersion);
            Dictionary<string, string> envs = new Dictionary<string, string>();
            envs[string.Format("{0}_DIR", cartridge.ShortName)] = target + Path.DirectorySeparatorChar;
            envs[string.Format("{0}_IDENT", cartridge.ShortName)] = ident;
            WriteEnvironmentVariables(Path.Combine(target, "env"), envs);
            envs = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(this.container.Namespace))
            {
                envs["namespace"] = this.container.Namespace;
            }

            Dictionary<string, string> currentGearEnv = Environ.ForGear(this.container.ContainerDir);
            if (!currentGearEnv.ContainsKey("OPENSHIFT_PRIMARY_CARTRIDGE_DIR"))
            {
                envs["PRIMARY_CARTRIDGE_DIR"] = target + Path.DirectorySeparatorChar;
            }
            if (envs.Count > 0)
            {
                WriteEnvironmentVariables(Path.Combine(this.container.ContainerDir, ".env"), envs);
            }

            var prison = Prison.Prison.LoadPrisonNoAttach(Guid.Parse(this.container.Uuid.PadLeft(32, '0')));
            Logger.Debug("Setting permisions to dir {0}, prison user {1}", target, prison.User.Username);
            
            LinuxFiles.TakeOwnership(target, prison.User.Username);

            Logger.Info("Created cartridge directory {0}/{1}", container.Uuid, cartridge.Dir);
        }
        public string Build(RubyHash options)
        {
            this.State.Value(Runtime.State.BUILDING);
            string             deploymentDateTime = options["deployment_datetime"] != null ? options["deployment_datetime"] : LatestDeploymentDateTime();
            DeploymentMetadata deploymentMetadata = DeploymentMetadataFor(deploymentDateTime);

            if (!options.ContainsKey("deployment_datetime"))
            {
                // this will execute if coming from a CI builder, since it doesn't
                // specify :deployment_datetime in the options hash
                ApplicationRepository applicationRepository = options["git_repo"];
                string gitRef  = options["ref"];
                string gitSha1 = applicationRepository.GetSha1(gitRef);
                deploymentMetadata.GitSha          = gitSha1;
                deploymentMetadata.GitRef          = gitRef;
                deploymentMetadata.HotDeploy       = options["hot_deploy"];
                deploymentMetadata.ForceCleanBuild = options["force_clean_build"];
                deploymentMetadata.Save();
            }

            StringBuilder buffer = new StringBuilder();

            if (deploymentMetadata.ForceCleanBuild)
            {
                buffer.AppendLine("Force clean build enabled - cleaning dependencies");

                CleanRuntimeDirs(new RubyHash()
                {
                    { "dependencies", true }, { "build_dependencies", true }
                });

                this.Cartridge.EachCartridge(delegate(Manifest cartridge) {
                    this.Cartridge.CreateDependencyDirectories(cartridge);
                });
            }

            buffer.AppendLine(string.Format("Building git ref {0}, commit {1}", deploymentMetadata.GitRef, deploymentMetadata.GitSha));

            Dictionary <string, string> env = Environ.ForGear(this.ContainerDir);
            int deploymentsToKeep           = DeploymentsToKeep(env);

            try
            {
                Manifest primaryCartridge = this.Cartridge.GetPrimaryCartridge();
                buffer.AppendLine(this.Cartridge.DoControl("update-configuration", primaryCartridge, new RubyHash()
                {
                    { "pre_action_hooks_enabled", false }, { "post_action_hooks_enabled", false }
                }));
                buffer.AppendLine(this.Cartridge.DoControl("pre-build", primaryCartridge, new RubyHash()
                {
                    { "pre_action_hooks_enabled", false }, { "post_action_hooks_enabled", false }
                }));
                buffer.AppendLine(this.Cartridge.DoControl("build", primaryCartridge, new RubyHash()
                {
                    { "pre_action_hooks_enabled", false }, { "post_action_hooks_enabled", false }
                }));
            }
            catch (Exception ex)
            {
                buffer.AppendLine("Encountered a failure during build: " + ex.ToString());
                if (deploymentsToKeep > 1)
                {
                    buffer.AppendLine("Restarting application");
                    buffer.AppendLine(StartGear(new RubyHash()
                    {
                        { "user_initiated", true }, { "hot_deploy", deploymentMetadata.HotDeploy }
                    }));
                }
                throw ex;
            }

            return(buffer.ToString());
        }
 private void DeleteCartridgeDirectory(Manifest cartridge)
 {
     Directory.Delete(Path.Combine(this.container.ContainerDir, cartridge.Dir), true);
 }
        private RubyHash ActivateLocalGear(dynamic options)
        {
            string deploymentId = options["deployment_id"];

            Logger.Debug("Activating local gear with deployment id {0}", deploymentId);

            RubyHash result = new RubyHash();

            result["status"]        = RESULT_FAILURE;
            result["gear_uuid"]     = this.Uuid;
            result["deployment_id"] = deploymentId;
            result["messages"]      = new List <string>();
            result["errors"]        = new List <string>();

            if (!DeploymentExists(deploymentId))
            {
                Logger.Warning("No deployment with id {0} found on gear", deploymentId);
                result["errors"].Add(string.Format("No deployment with id {0} found on gear", deploymentId));
                return(result);
            }

            try
            {
                string deploymentDateTime = GetDeploymentDateTimeForDeploymentId(deploymentId);
                string deploymentDir      = Path.Combine(this.ContainerDir, "app-deployments", deploymentDateTime);

                Dictionary <string, string> gearEnv = Environ.ForGear(this.ContainerDir);

                string output = string.Empty;

                Logger.Debug("Current deployment state for deployment {0} is {1}", deploymentId, this.State.Value());

                if (Runtime.State.STARTED.EqualsString(State.Value()))
                {
                    options["exclude_web_proxy"] = true;
                    output = StopGear(options);
                    result["messages"].Add(output);
                }

                SyncDeploymentRepoDirToRuntime(deploymentDateTime);
                SyncDeploymentDependenciesDirToRuntime(deploymentDateTime);
                SyncDeploymentBuildDependenciesDirToRuntime(deploymentDateTime);

                UpdateCurrentDeploymentDateTimeSymlink(deploymentDateTime);

                FixHomeDir();

                Manifest primaryCartridge = this.Cartridge.GetPrimaryCartridge();

                this.Cartridge.DoControl("update-configuration", primaryCartridge);

                result["messages"].Add("Starting application " + ApplicationName);

                Dictionary <string, object> opts = new Dictionary <string, object>();
                opts["secondary_only"] = true;
                opts["user_initiated"] = true;
                opts["hot_deploy"]     = options["hot_deploy"];

                output = StartGear(opts);
                result["messages"].Add(output);

                this.State.Value(Runtime.State.DEPLOYING);

                opts = new Dictionary <string, object>();
                opts["pre_action_hooks_enabled"] = false;
                opts["prefix_action_hooks"]      = false;
                output = this.Cartridge.DoControl("deploy", primaryCartridge, opts);
                result["messages"].Add(output);

                opts = new Dictionary <string, object>();
                opts["primary_only"]   = true;
                opts["user_initiated"] = true;
                opts["hot_deploy"]     = options["hot_deploy"];
                output = StartGear(opts);
                result["messages"].Add(output);

                opts = new Dictionary <string, object>();
                opts["pre_action_hooks_enabled"] = false;
                opts["prefix_action_hooks"]      = false;
                output = this.Cartridge.DoControl("post-deploy", primaryCartridge, opts);
                result["messages"].Add(output);

                if (options.ContainsKey("post_install"))
                {
                    string primaryCartEnvDir = Path.Combine(this.ContainerDir, primaryCartridge.Dir, "env");
                    Dictionary <string, string> primaryCartEnv = Environ.Load(primaryCartEnvDir);
                    string ident = (from kvp in primaryCartEnv
                                    where Regex.Match(kvp.Key, "^OPENSHIFT_.*_IDENT").Success
                                    select kvp.Value).FirstOrDefault();
                    string version = Manifest.ParseIdent(ident)[2];
                    this.Cartridge.PostInstall(primaryCartridge, version);
                }

                DeploymentMetadata deploymentMetadata = DeploymentMetadataFor(deploymentDateTime);
                deploymentMetadata.RecordActivation();
                deploymentMetadata.Save();

                if (options.ContainsKey("report_deployments") && gearEnv["OPENSHIFT_APP_DNS"] == gearEnv["OPENSHIFT_GEAR_DNS"])
                {
                    ReportDeployments(gearEnv);
                }

                result["status"] = RESULT_SUCCESS;
            }
            catch (Exception e)
            {
                result["status"] = RESULT_FAILURE;
                result["errors"].Add(string.Format("Error activating gear: {0}", e.ToString()));
            }

            return(result);
        }
        internal void CreateDependencyDirectories(Manifest cartridge)
        {
            // TODO
            // need managed_files.yml from here on
            return;

            foreach (string dependenciesDirName in new string[] { "build-dependencies", "dependencies" })
            {
                List<string> dirs = null;
                if(dependenciesDirName == "build-dependencies")
                {
                    dirs = this.container.BuildDependencyDirs(cartridge);
                }

            }
        }
Exemple #23
0
 public static void  OverlayCartridge(Manifest cartridge, string target)
 {
     InstantiateCartridge(cartridge, target, false);
 }