Example #1
0
        private static void RollbackStateToolInstall(Session session)
        {
            if (session.CustomActionData["STATE_TOOL_INSTALLED"] == "false")
            {
                Status.ProgressBar.StatusMessage(session, "Rolling back State Tool installation");
                // If we installed the state tool then we want to remove it
                // along with any environment entries.
                // We cannot pass data between non-immediate custom actions
                // so we use the known State Tool installation path from the
                // state deploy custom acion.
                string stateToolInstallDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ActiveState", "bin");

                session.Log(string.Format("Attemping to remove State Tool installation directory: {0}", stateToolInstallDir));
                ActionResult result = Remove.Dir(session, stateToolInstallDir);
                if (!result.Equals(ActionResult.Success))
                {
                    string msg = string.Format("Not successful in removing State Tool installation directory, got action result: {0}", result);
                    session.Log(msg);
                    RollbarReport.Error(msg);
                }

                session.Log(string.Format("Removing environment entries containing: {0}", stateToolInstallDir));
                result = Remove.EnvironmentEntries(session, stateToolInstallDir);
                if (!result.Equals(ActionResult.Success))
                {
                    string msg = string.Format("Not successful in removing State Tool environment entries, got action result: {0}", result);
                    session.Log(msg);
                    RollbarReport.Error(msg);
                }
            }
        }
Example #2
0
        public static ActionResult Uninstall(Session session)
        {
            ActiveState.RollbarHelper.ConfigureRollbarSingleton();

            session.Log("Begin uninstallation");

            string installDir = session.CustomActionData["REMEMBER"];

            ActionResult result = Remove.Dir(session, installDir);

            if (result.Equals(ActionResult.Failure))
            {
                session.Log("Could not remove installation directory");
                ActiveState.RollbarHelper.Report("Could not remove installation directory");
                return(ActionResult.Failure);
            }

            string shortcutDir = session.CustomActionData["REMEMBER_SHORTCUTDIR"];

            result = Remove.Dir(session, shortcutDir);
            if (result.Equals(ActionResult.Failure))
            {
                session.Log("Could not remove shortcuts directory");
                ActiveState.RollbarHelper.Report("Could not remove shortcuts directory");
                return(ActionResult.Failure);
            }

            return(Remove.EnvironmentEntries(session, installDir));
        }
Example #3
0
        public static ActionResult InstallStateTool(Session session, out string stateToolPath)
        {
            ActiveState.RollbarHelper.ConfigureRollbarSingleton();

            stateToolPath = "";
            session.Log("Installing State Tool if necessary");
            if (session.CustomActionData["STATE_TOOL_INSTALLED"] == "true")
            {
                stateToolPath = session.CustomActionData["STATE_TOOL_PATH"];
                session.Log("State Tool is installed, no installation required");
                Status.ProgressBar.Increment(session, 1);
                return(ActionResult.Success);
            }

            string tempDir     = Path.GetTempPath();
            string scriptPath  = Path.Combine(tempDir, "install.ps1");
            string installPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ActiveState", "bin");

            Status.ProgressBar.StatusMessage(session, "Installing State Tool...");

            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            try
            {
                WebClient client = new WebClient();
                client.DownloadFile("https://platform.activestate.com/dl/cli/install.ps1", scriptPath);
            }
            catch (WebException e)
            {
                session.Log(string.Format("Encoutered exception downloading file: {0}", e.ToString()));
                ActiveState.RollbarHelper.Report(string.Format("Encoutered exception downloading file: {0}", e.ToString()));
                return(ActionResult.Failure);
            }

            string installCmd = string.Format("Set-PSDebug -trace 2; Set-ExecutionPolicy Unrestricted -Scope Process; \"{0}\" -n -t \"{1}\"", scriptPath, installPath);

            session.Log(string.Format("Running install command: {0}", installCmd));

            string       output;
            ActionResult result = RunCommand(session, installCmd, Shell.Powershell, out output);

            if (result.Equals(ActionResult.UserExit))
            {
                // Catch cancel and return
                return(result);
            }
            else if (result.Equals(ActionResult.Failure))
            {
                Record record      = new Record();
                var    errorOutput = FormatErrorOutput(output);
                record.FormatString = String.Format("state tool installation failed with error:\n{0}", errorOutput);

                MessageResult msgRes = session.Message(InstallMessage.Error | (InstallMessage)MessageBoxButtons.OK, record);
                return(result);
            }
            Status.ProgressBar.Increment(session, 1);

            stateToolPath = Path.Combine(installPath, "state.exe");
            return(result);
        }
Example #4
0
        public ActionResult Install()
        {
            session.Log("installing perl file associations");
            FileAssociation.EnsureAssociationsSet(associations());

            session.Log("updating PATHEXT");
            var oldPathExt = Environment.GetEnvironmentVariable("PATHEXT", EnvironmentVariableTarget.Machine);
            var exts       = String.Join(";", oldPathExt.Split(';').Concat(PathExtensions).Distinct().ToArray());

            if (exts != oldPathExt)
            {
                Environment.SetEnvironmentVariable("PATHEXT", exts, EnvironmentVariableTarget.Machine);
            }

            session.Log("install cmd-prompt shortcut");
            ActionResult result = CmdPromptShortcut();

            if (result.Equals(ActionResult.Failure))
            {
                session.Log("Could not create Command Prompt shortcut");
                // Do not fail if we cannot create shortcut
                return(ActionResult.Success);
            }

            session.Log("Install Documentation link");
            DocumentationShortcut();

            return(ActionResult.Success);
        }
Example #5
0
        private static void RollbackDeploy(Session session)
        {
            Status.ProgressBar.StatusMessage(session, "Rolling back language installation");
            ActionResult result = Remove.Dir(session, session.CustomActionData["INSTALLDIR"]);

            if (!result.Equals(ActionResult.Success))
            {
                session.Log(string.Format("Not successful in removing deploy directory, got action result: {0}", result));
            }

            result = Remove.EnvironmentEntries(session, session.CustomActionData["INSTALLDIR"]);
            if (!result.Equals(ActionResult.Success))
            {
                session.Log(string.Format("Not successful in removing Deployment environment entries, got action result: {0}", result));
            }
        }
Example #6
0
        private static ActionResult Login(Session session, string stateToolPath)
        {
            string username = session.CustomActionData["AS_USERNAME"];
            string password = session.CustomActionData["AS_PASSWORD"];
            string totp     = session.CustomActionData["AS_TOTP"];

            if (username == "" && password == "" && totp == "")
            {
                session.Log("No login information provided, not executing login");
                return(ActionResult.Success);
            }

            string authCmd;

            if (totp != "")
            {
                session.Log("Attempting to log in with TOTP token");
                authCmd = " auth" + " --totp " + totp;
            }
            else
            {
                session.Log(string.Format("Attempting to login as user: {0}", username));
                authCmd = " auth" + " --username " + username + " --password " + password;
            }

            string output;

            Status.ProgressBar.StatusMessage(session, "Authenticating...");
            ActionResult runResult = ActiveState.Command.Run(session, stateToolPath, authCmd, out output);

            if (runResult.Equals(ActionResult.UserExit))
            {
                // Catch cancel and return
                return(runResult);
            }
            else if (runResult == ActionResult.Failure)
            {
                Record record = new Record();
                session.Log(string.Format("Output: {0}", output));
                var errorOutput = FormatErrorOutput(output);
                record.FormatString = string.Format("Platform login failed with error:\n{0}", errorOutput);

                session.Message(InstallMessage.Error | (InstallMessage)MessageBoxButtons.OK, record);
                return(runResult);
            }
            // The auth command did not fail but the username we expected is not present in the output meaning
            // another user is logged into the State Tool
            else if (!output.Contains(username))
            {
                Record record      = new Record();
                var    errorOutput = string.Format("Could not log in as {0}, currently logged in as another user. To correct this please start a command prompt and execute `{1} auth logout` and try again", username, stateToolPath);
                record.FormatString = string.Format("Failed with error:\n{0}", errorOutput);

                session.Message(InstallMessage.Error | (InstallMessage)MessageBoxButtons.OK, record);
                return(ActionResult.Failure);
            }
            return(ActionResult.Success);
        }
        public static ActionResult InstallShortcuts(Session session)
        {
            session.Log("Begin InstallShortcuts");

            ActiveState.RollbarHelper.ConfigureRollbarSingleton();

            string shortcutData     = session.CustomActionData["SHORTCUTS"];
            string appStartMenuPath = session.CustomActionData["APP_START_MENU_PATH"];

            if (shortcutData.ToLower() == "none")
            {
                session.Log("Recieved none, not building any shortcuts");
                return(ActionResult.Success);
            }

            string[] shortcuts = shortcutData.Split(',');
            foreach (string shortcut in shortcuts)
            {
                var s = shortcut.ToLower();
                switch (s)
                {
                case "perlcritic":
                {
                    ActionResult result = PerlCriticShortcut(session, appStartMenuPath);
                    if (result.Equals(ActionResult.Failure))
                    {
                        session.Log("Could not create Perl Critic shortcut");
                        // Do not fail if we cannot create shortcut
                        return(ActionResult.Success);
                    }
                    break;
                }

                case "cmdprompt":
                {
                    ActionResult result = CmdPromptShortcut(session, appStartMenuPath);
                    if (result.Equals(ActionResult.Failure))
                    {
                        session.Log("Could not create Command Prompt shortcut");
                        // Do not fail if we cannot create shortcut
                        return(ActionResult.Success);
                    }
                    break;
                }

                default:
                    session.Log(string.Format("Received unknown shortcut, not building: {0}", shortcut));
                    break;
                }
            }
            return(ActionResult.Success);
        }
        public void LoginResponseTest()
        {
            AccountController target   = new AccountController(); // TODO: Initialize to an appropriate value
            ActionResult      expected = null;                    // TODO: Initialize to an appropriate value

            expected.Equals(true);

            ActionResult actual;

            actual = target.LoginResponse();
            Assert.AreEqual(expected, actual);
            //Assert.Inconclusive("Verify the correctness of this test method.");
        }
Example #9
0
        public static ActionResult InstallStateTool(Session session, out string stateToolPath)
        {
            RollbarHelper.ConfigureRollbarSingleton(session.CustomActionData["COMMIT_ID"]);

            session.Log("Installing State Tool if necessary");
            if (session.CustomActionData["STATE_TOOL_INSTALLED"] == "true")
            {
                stateToolPath = session.CustomActionData["STATE_TOOL_PATH"];
                session.Log("State Tool is installed, no installation required");
                Status.ProgressBar.Increment(session, 1);
                return(ActionResult.Success);
            }

            Status.ProgressBar.StatusMessage(session, "Installing State Tool...");
            Status.ProgressBar.Increment(session, 1);
            stateToolPath = "";

            var    paths     = GetPaths();
            string stateURL  = "https://s3.ca-central-1.amazonaws.com/cli-update/update/state/unstable/";
            string jsonURL   = stateURL + paths.JsonDescription;
            string timeStamp = DateTime.Now.ToFileTime().ToString();
            string tempDir   = Path.Combine(Path.GetTempPath(), timeStamp);

            session.Log(string.Format("Using temp path: {0}", tempDir));
            try
            {
                Directory.CreateDirectory(tempDir);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not create temp directory at: {0}, encountered exception: {1}", tempDir, e.ToString());
                session.Log(msg);
                RollbarReport.Critical(msg);
                return(ActionResult.Failure);
            }

            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            string versionInfoString;

            session.Log(string.Format("Downloading JSON from URL: {0}", jsonURL));
            try
            {
                WebClient client = new WebClient();
                versionInfoString = client.DownloadString(jsonURL);
            }
            catch (WebException e)
            {
                string msg = string.Format("Encountered exception downloading state tool json info file: {0}", e.ToString());
                session.Log(msg);
                RollbarReport.Critical(msg);
                return(ActionResult.Failure);
            }

            VersionInfo info;

            try
            {
                info = JsonConvert.DeserializeObject <VersionInfo>(versionInfoString);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not deserialize version info. Version info string {0}, exception {1}", versionInfoString, e.ToString());
                session.Log(msg);
                RollbarReport.Critical(msg);
                return(ActionResult.Failure);
            }

            string zipPath = Path.Combine(tempDir, paths.ZipFile);
            string zipURL  = stateURL + info.version + "/" + paths.ZipFile;

            session.Log(string.Format("Downloading zip file from URL: {0}", zipURL));
            Status.ProgressBar.StatusMessage(session, "Downloading State Tool...");
            try
            {
                WebClient client = new WebClient();
                client.DownloadFile(zipURL, zipPath);
            }
            catch (WebException e)
            {
                string msg = string.Format("Encoutered exception downloading state tool zip file. URL to zip file: {0}, path to save zip file to: {1}, exception: {2}", zipURL, zipPath, e.ToString());
                session.Log(msg);
                RollbarReport.Critical(msg);
                return(ActionResult.Failure);
            }

            SHA256     sha     = SHA256.Create();
            FileStream fInfo   = File.OpenRead(zipPath);
            string     zipHash = BitConverter.ToString(sha.ComputeHash(fInfo)).Replace("-", string.Empty).ToLower();

            if (zipHash != info.sha256v2)
            {
                string msg = string.Format("SHA256 checksum did not match, expected: {0} actual: {1}", info.sha256v2, zipHash.ToString());
                session.Log(msg);
                RollbarReport.Critical(msg);
                return(ActionResult.Failure);
            }

            Status.ProgressBar.StatusMessage(session, "Extracting State Tool executable...");
            try
            {
                ZipFile.ExtractToDirectory(zipPath, tempDir);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not extract State Tool, encountered exception. Path to zip file: {0}, path to temp directory: {1}, exception {2})", zipPath, tempDir, e);
                session.Log(msg);
                RollbarReport.Critical(msg);
                return(ActionResult.Failure);
            }

            string stateToolInstallDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ActiveState", "bin");

            try
            {
                Directory.CreateDirectory(stateToolInstallDir);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not create State Tool install directory at: {0}, encountered exception: {1}", stateToolInstallDir, e.ToString());
                session.Log(msg);
                RollbarReport.Critical(msg);
                return(ActionResult.Failure);
            }


            stateToolPath = Path.Combine(stateToolInstallDir, "state.exe");
            if (File.Exists(stateToolPath))
            {
                try
                {
                    File.Delete(stateToolPath);
                }
                catch (Exception e)
                {
                    string msg = string.Format("Could not remove existing temporary state tool executable at: {0}, encountered exception: {1}", stateToolPath, e.ToString());
                    session.Log(msg);
                    RollbarReport.Critical(msg);
                    return(ActionResult.Failure);
                }
            }

            try
            {
                File.Move(Path.Combine(tempDir, paths.ExeFile), stateToolPath);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not move State Tool executable to: {0}, encountered exception: {1}", stateToolPath, e);
                session.Log(msg);
                RollbarReport.Critical(msg);
                return(ActionResult.Failure);
            }

            string       configDirCmd = " export" + " config" + " --filter=dir";
            string       output;
            ActionResult runResult = ActiveState.Command.Run(session, stateToolPath, configDirCmd, out output);

            session.Log("Writing install file...");
            // We do not fail the installation if writing the installsource.txt file fails
            if (runResult.Equals(ActionResult.Failure))
            {
                string msg = string.Format("Could not get config directory from State Tool");
                session.Log(msg);
                RollbarReport.Error(msg);
            }
            else
            {
                string contents = "msi-ui";
                if (session.CustomActionData["UI_LEVEL"] == "2")
                {
                    contents = "msi-silent";
                }
                try
                {
                    string installFilePath = Path.Combine(output.Trim(), "installsource.txt");
                    File.WriteAllText(installFilePath, contents);
                }
                catch (Exception e)
                {
                    string msg = string.Format("Could not write install file at path: {0}, encountered exception: {1}", output, e.ToString());
                    session.Log(msg);
                    RollbarReport.Error(msg);
                }
            }

            session.Log("Updating PATH environment variable");
            string oldPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);

            if (oldPath.Contains(stateToolInstallDir))
            {
                session.Log("State tool installation already on PATH");
                return(ActionResult.Success);
            }

            var newPath = string.Format("{0};{1}", stateToolInstallDir, oldPath);

            session.Log(string.Format("updating PATH to {0}", newPath));
            try
            {
                Environment.SetEnvironmentVariable("PATH", newPath, EnvironmentVariableTarget.Machine);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not update PATH. Attempted to set path to: {0}, encountered exception: {1}", newPath, e.ToString());
                session.Log(msg);
                RollbarReport.Critical(msg);
                return(ActionResult.Failure);
            }

            return(ActionResult.Success);
        }
Example #10
0
        public static ActionResult StateDeploy(Session session)
        {
            ActiveState.RollbarHelper.ConfigureRollbarSingleton(session.CustomActionData["COMMIT_ID"]);

            if (!Environment.Is64BitOperatingSystem)
            {
                Record record = new Record();
                record.FormatString = "This installer cannot be run on a 32-bit operating system";

                RollbarReport.Critical(record.FormatString);
                session.Message(InstallMessage.Error | (InstallMessage)MessageBoxButtons.OK, record);
                return(ActionResult.Failure);
            }

            string       stateToolPath;
            ActionResult res = InstallStateTool(session, out stateToolPath);

            if (res != ActionResult.Success)
            {
                return(res);
            }
            session.Log("Starting state deploy with state tool at " + stateToolPath);

            res = Login(session, stateToolPath);
            if (res.Equals(ActionResult.Failure))
            {
                return(res);
            }

            Status.ProgressBar.StatusMessage(session, string.Format("Deploying project {0}...", session.CustomActionData["PROJECT_OWNER_AND_NAME"]));
            Status.ProgressBar.StatusMessage(session, string.Format("Preparing deployment of {0}...", session.CustomActionData["PROJECT_OWNER_AND_NAME"]));

            var sequence = new ReadOnlyCollection <InstallSequenceElement>(
                new[]
            {
                new InstallSequenceElement("install", string.Format("Installing {0}", session.CustomActionData["PROJECT_OWNER_AND_NAME"])),
                new InstallSequenceElement("configure", "Updating system environment"),
                new InstallSequenceElement("symlink", "Creating shortcut directory"),
            });

            try
            {
                foreach (var seq in sequence)
                {
                    string deployCmd = BuildDeployCmd(session, seq.SubCommand);
                    session.Log(string.Format("Executing deploy command: {0}", deployCmd));

                    Status.ProgressBar.Increment(session, 1);
                    Status.ProgressBar.StatusMessage(session, seq.Description);

                    string output;
                    var    runResult = ActiveState.Command.Run(session, stateToolPath, deployCmd, out output);
                    if (runResult.Equals(ActionResult.UserExit))
                    {
                        // Catch cancel and return
                        return(runResult);
                    }
                    else if (runResult == ActionResult.Failure)
                    {
                        Record record      = new Record();
                        var    errorOutput = FormatErrorOutput(output);
                        record.FormatString = String.Format("{0} failed with error:\n{1}", seq.Description, errorOutput);

                        MessageResult msgRes = session.Message(InstallMessage.Error | (InstallMessage)MessageBoxButtons.OK, record);
                        return(runResult);
                    }
                }
            }
            catch (Exception objException)
            {
                string msg = string.Format("Caught exception: {0}", objException);
                session.Log(msg);
                RollbarReport.Critical(msg);
                return(ActionResult.Failure);
            }

            Status.ProgressBar.Increment(session, 1);
            return(ActionResult.Success);
        }
Example #11
0
        private static ActionResult _installStateTool(Session session, out string stateToolPath)
        {
            Error.ResetErrorDetails(session);

            var paths = GetPaths();
            string stateURL = "https://state-tool.s3.amazonaws.com/update/state/release/";
            string jsonURL = stateURL + paths.JsonDescription;
            string timeStamp = DateTime.Now.ToFileTime().ToString();
            string tempDir = Path.Combine(Path.GetTempPath(), timeStamp);
            string stateToolInstallDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ActiveState", "bin");
            stateToolPath = Path.Combine(stateToolInstallDir, "state.exe");

            if (File.Exists(stateToolPath))
            {
                session.Log("Using existing State Tool executable at install path");
                Status.ProgressBar.Increment(session, 200);
                return ActionResult.Success;
            }

            session.Log(string.Format("Using temp path: {0}", tempDir));
            try
            {
                Directory.CreateDirectory(tempDir);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not create temp directory at: {0}, encountered exception: {1}", tempDir, e.ToString());
                session.Log(msg);
                RollbarReport.Critical(msg, session);
                return ActionResult.Failure;
            }

            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            string versionInfoString = "unset";
            session.Log(string.Format("Downloading JSON from URL: {0}", jsonURL));
            try
            {
                RetryHelper.RetryOnException(session, 3, TimeSpan.FromSeconds(2), () =>
                {
                    var client = new WebClient();
                    versionInfoString = client.DownloadString(jsonURL);
                });
            }
            catch (WebException e)
            {
                string msg = string.Format("Encountered exception downloading state tool json info file: {0}", e.ToString());
                session.Log(msg);
                new NetworkError().SetDetails(session, e.Message);
                return ActionResult.Failure;
            }

            VersionInfo info;
            try
            {
                info = JsonConvert.DeserializeObject<VersionInfo>(versionInfoString);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not deserialize version info. Version info string {0}, exception {1}", versionInfoString, e.ToString());
                session.Log(msg);
                RollbarReport.Critical(msg, session);
                return ActionResult.Failure;
            }

            string zipPath = Path.Combine(tempDir, paths.ZipFile);
            string zipURL = stateURL + info.version + "/" + paths.ZipFile;
            session.Log(string.Format("Downloading zip file from URL: {0}", zipURL));
            Status.ProgressBar.StatusMessage(session, "Downloading State Tool...");

            var tokenSource = new CancellationTokenSource();
            var token = tokenSource.Token;

            Task incrementTask = Task.Run(() =>
            {
                incrementProgressBar(session, 50, token);
            });

            Task<ActionResult> downloadTask = Task.Run(() =>
            {
                try
                {
                    RetryHelper.RetryOnException(session, 3, TimeSpan.FromSeconds(2), () =>
                    {
                        var client = new WebClient();
                        client.DownloadFile(zipURL, zipPath);
                    });
                }
                catch (WebException e)
                {
                    string msg = string.Format("Encountered exception downloading state tool zip file. URL to zip file: {0}, path to save zip file to: {1}, exception: {2}", zipURL, zipPath, e.ToString());
                    session.Log(msg);
                    new NetworkError().SetDetails(session, e.Message);
                    return ActionResult.Failure;
                }

                return ActionResult.Success;
            });

            ActionResult result = downloadTask.Result;
            tokenSource.Cancel();
            incrementTask.Wait();
            if (result.Equals(ActionResult.Failure))
            {
                return result;
            }


            SHA256 sha = SHA256.Create();
            FileStream fInfo = File.OpenRead(zipPath);
            string zipHash = BitConverter.ToString(sha.ComputeHash(fInfo)).Replace("-", string.Empty).ToLower();
            if (zipHash != info.sha256v2)
            {
                string msg = string.Format("SHA256 checksum did not match, expected: {0} actual: {1}", info.sha256v2, zipHash.ToString());
                session.Log(msg);
                RollbarReport.Critical(msg, session);
                return ActionResult.Failure;
            }

            Status.ProgressBar.StatusMessage(session, "Extracting State Tool executable...");
            Status.ProgressBar.Increment(session, 50);
            try
            {
                ZipFile.ExtractToDirectory(zipPath, tempDir);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not extract State Tool, encountered exception. Path to zip file: {0}, path to temp directory: {1}, exception {2})", zipPath, tempDir, e);
                session.Log(msg);
                RollbarReport.Critical(msg, session);
                return ActionResult.Failure;
            }

            try
            {
                Directory.CreateDirectory(stateToolInstallDir);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not create State Tool install directory at: {0}, encountered exception: {1}", stateToolInstallDir, e.ToString());
                session.Log(msg);
                RollbarReport.Critical(msg, session);
                return ActionResult.Failure;
            }

            try
            {
                File.Move(Path.Combine(tempDir, paths.ExeFile), stateToolPath);
            }
            catch (Exception e)
            {
                string msg = string.Format("Could not move State Tool executable to: {0}, encountered exception: {1}", stateToolPath, e);
                session.Log(msg);
                RollbarReport.Critical(msg, session);
                return ActionResult.Failure;
            }


            string configDirCmd = " export" + " config" + " --filter=dir";
            string output;
            ActionResult runResult = ActiveState.Command.Run(session, stateToolPath, configDirCmd, out output);
            session.Log("Writing install file...");
            // We do not fail the installation if writing the installsource.txt file fails
            if (runResult.Equals(ActionResult.Failure))
            {
                string msg = string.Format("Could not get config directory from State Tool");
                session.Log(msg);
                RollbarReport.Error(msg, session);
            }
            else
            {
                string contents = "msi-ui";
                if (session.CustomActionData["UI_LEVEL"] == "2")
                {
                    contents = "msi-silent";
                }
                try
                {
                    string installFilePath = Path.Combine(output.Trim(), "installsource.txt");
                    File.WriteAllText(installFilePath, contents, Encoding.ASCII);
                }
                catch (Exception e)
                {
                    string msg = string.Format("Could not write install file at path: {0}, encountered exception: {1}", output, e.ToString());
                    session.Log(msg);
                    RollbarReport.Error(msg, session);
                }
            }

            session.Log("Updating PATH environment variable");
            Status.ProgressBar.Increment(session, 50);
            string oldPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
            if (oldPath.Contains(stateToolInstallDir))
            {
                session.Log("State tool installation already on PATH");
            }
            else
            {
                var newPath = string.Format("{0};{1}", stateToolInstallDir, oldPath);
                session.Log(string.Format("updating PATH to {0}", newPath));
                try
                {
                    Environment.SetEnvironmentVariable("PATH", newPath, EnvironmentVariableTarget.Machine);
                }
                catch (Exception e)
                {
                    string msg = string.Format("Could not update PATH. Encountered exception: {0}", e.Message);
                    session.Log(msg);
                    new SecurityError().SetDetails(session, msg);
                    return ActionResult.Failure;
                }
            }

            session.Log("Running prepare step...");
            string prepareCmd = " _prepare";
            string prepareOutput;
            ActionResult prepareRunResult = ActiveState.Command.Run(session, stateToolPath, prepareCmd, out prepareOutput);
            if (prepareRunResult.Equals(ActionResult.Failure))
            {
                string msg = string.Format("Preparing environment caused error: {0}", prepareOutput);
                session.Log(msg);
                RollbarReport.Critical(msg, session);

                Record record = new Record();
                var errorOutput = Command.FormatErrorOutput(prepareOutput);
                record.FormatString = msg;

                session.Message(InstallMessage.Error | (InstallMessage)MessageBoxButtons.OK, record);
                return ActionResult.Failure;
            }
            else
            {
                session.Log(string.Format("Prepare Output: {0}", prepareOutput));
            }

            Status.ProgressBar.Increment(session, 50);
            return ActionResult.Success;
        }
Example #12
0
        private static ActionResult run(Session session)
        {
            var uiLevel = session.CustomActionData["UI_LEVEL"];

            if (uiLevel == "2" /* no ui */ || uiLevel == "3" /* basic ui */)
            {
                // we have to send the start event, because it has not triggered before
                reportStartEvent(session, uiLevel);
            }

            if (!Environment.Is64BitOperatingSystem)
            {
                Record record = new Record();
                record.FormatString = "This installer cannot be run on a 32-bit operating system";

                RollbarReport.Critical(record.FormatString, session);
                session.Message(InstallMessage.Error | (InstallMessage)MessageBoxButtons.OK, record);
                return ActionResult.Failure;
            }

            string stateToolPath;
            ActionResult res = InstallStateTool(session, out stateToolPath);
            if (res != ActionResult.Success)
            {
                return res;
            }
            session.Log("Starting state deploy with state tool at " + stateToolPath);

            res = Login(session, stateToolPath);
            if (res.Equals(ActionResult.Failure))
            {
                return res;
            }

            Status.ProgressBar.StatusMessage(session, string.Format("Deploying project {0}...", session.CustomActionData["PROJECT_OWNER_AND_NAME"]));
            Status.ProgressBar.StatusMessage(session, string.Format("Preparing deployment of {0}...", session.CustomActionData["PROJECT_OWNER_AND_NAME"]));

            var sequence = new ReadOnlyCollection<InstallSequenceElement>(
                new[]
                {
                    new InstallSequenceElement("install", string.Format("Installing {0}", session.CustomActionData["PROJECT_OWNER_AND_NAME"])),
                    new InstallSequenceElement("configure", "Updating system environment"),
                    new InstallSequenceElement("symlink", "Creating shortcut directory"),
                });

            try
            {
                foreach (var seq in sequence)
                {
                    string deployCmd = BuildDeployCmd(session, seq.SubCommand);
                    session.Log(string.Format("Executing deploy command: {0}", deployCmd));

                    Status.ProgressBar.StatusMessage(session, seq.Description);
                    string output;
                    var runResult = ActiveState.Command.RunWithProgress(session, stateToolPath, deployCmd, 200, out output);
                    if (runResult.Equals(ActionResult.UserExit))
                    {
                        // Catch cancel and return
                        return runResult;
                    }
                    else if (runResult == ActionResult.Failure)
                    {
                        Record record = new Record();
                        var errorOutput = Command.FormatErrorOutput(output);
                        record.FormatString = String.Format("{0} failed with error:\n{1}", seq.Description, errorOutput);

                        MessageResult msgRes = session.Message(InstallMessage.Error | (InstallMessage)MessageBoxButtons.OK, record);
                        TrackerSingleton.Instance.TrackEventSynchronously(session, "stage", "artifacts", "failure");

                        return runResult;
                    }
                }
                TrackerSingleton.Instance.TrackEventSynchronously(session, "stage", "artifacts", "success");
            }
            catch (Exception objException)
            {
                string msg = string.Format("Caught exception: {0}", objException);
                session.Log(msg);
                RollbarReport.Critical(msg, session);
                return ActionResult.Failure;
            }

            Status.ProgressBar.Increment(session, 100);
            return ActionResult.Success;

        }