Ejemplo n.º 1
0
        public void StopBuild(Project project)
        {
            var url = NetUtils.ConcatUrls(project.Url, "/lastBuild/stop");

            if (!string.IsNullOrEmpty(project.AuthenticationToken))
            {
                url = NetUtils.ConcatUrlsWithoutTrailingSlash(url, "&token=",
                                                              HttpUtility.UrlEncode(project.AuthenticationToken));
                if (!string.IsNullOrEmpty(project.CauseText))
                {
                    url = NetUtils.ConcatUrlsWithoutTrailingSlash(url, "&cause=",
                                                                  HttpUtility.UrlEncode(project.CauseText));
                }
            }
            logger.Info("Stopping build at " + url);

            var credentials = project.Server.Credentials;
            var str         = UploadString(credentials, url, project.Server.IgnoreUntrustedCertificate);

            if (logger.IsTraceEnabled)
            {
                logger.Trace("Result: " + str);
            }

            logger.Info("Done stopping build");
        }
Ejemplo n.º 2
0
        public void RemoveFromQueue(Server server, long queueId)
        {
            var url = NetUtils.ConcatUrls(server.Url, "/queue/cancelItem?id=" + queueId);

            logger.Info("Removing queue item at " + url);

            var credentials = server.Credentials;

            try
            {
                var str = UploadString(credentials, url, server.IgnoreUntrustedCertificate);

                if (logger.IsTraceEnabled)
                {
                    logger.Trace("Result: " + str);
                }
            }
            catch (WebException webEx)
            {
                //  Workaround for JENKINS-21311
                if (webEx.Status == WebExceptionStatus.ProtocolError &&
                    ((HttpWebResponse)webEx.Response).StatusCode == HttpStatusCode.NotFound)
                {
                    //  consume error 404
                }
                else
                {
                    throw webEx;
                }
            }
            logger.Info("Done removing queue item");
        }
Ejemplo n.º 3
0
        public AllBuildDetails UpdateProject(Project project)
        {
            var url = NetUtils.ConcatUrls(project.Url, "/api/xml");

            //logger.Info("Updating project from " + url);

            var credentials = project.Server.Credentials;
            var ignoreUntrustedCertificate = project.Server.IgnoreUntrustedCertificate;
            var xmlStr = DownloadString(credentials, url, false, ignoreUntrustedCertificate);

            if (logger.IsTraceEnabled)
            {
                logger.Trace("XML: " + xmlStr);
            }

            var xml = new XmlDocument();

            xml.LoadXml(xmlStr);

            var displayName            = XmlUtils.SelectSingleNodeText(xml, "/*/displayName");
            var inQueue                = XmlUtils.SelectSingleNodeBoolean(xml, "/*/inQueue");
            var inQueueSince           = XmlUtils.SelectSingleNodeText(xml, "/*/queueItem/inQueueSince");
            var queueId                = XmlUtils.SelectSingleNodeText(xml, "/*/queueItem/id");
            var why                    = XmlUtils.SelectSingleNodeText(xml, "/*/queueItem/why");
            var stuck                  = XmlUtils.SelectSingleNodeBoolean(xml, "/*/queueItem/stuck");
            var status                 = xml.SelectSingleNode("/*/color").InnerText;
            var lastBuildUrl           = XmlUtils.SelectSingleNodeText(xml, "/*/lastBuild/url");
            var lastCompletedBuildUrl  = XmlUtils.SelectSingleNodeText(xml, "/*/lastCompletedBuild/url");
            var lastSuccessfulBuildUrl = XmlUtils.SelectSingleNodeText(xml, "/*/lastSuccessfulBuild/url");
            var lastFailedBuildUrl     = XmlUtils.SelectSingleNodeText(xml, "/*/lastFailedBuild/url");

            project.DisplayName   = displayName;
            project.Queue.InQueue = inQueue.HasValue && inQueue.Value;
            if (!string.IsNullOrEmpty(queueId))
            {
                project.Queue.Id = long.Parse(queueId);
            }
            if (!string.IsNullOrEmpty(inQueueSince))
            {
                var ts   = TimeSpan.FromSeconds(long.Parse(inQueueSince) / 1000);
                var date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                date = date.Add(ts);
                project.Queue.InQueueSince = date;
            }
            if (!string.IsNullOrEmpty(why))
            {
                project.Queue.Why = why;
            }

            var res = new AllBuildDetails();

            res.Status              = GetStatus(status, stuck);
            res.LastBuild           = GetBuildDetails(credentials, lastBuildUrl, ignoreUntrustedCertificate);
            res.LastCompletedBuild  = GetBuildDetails(credentials, lastCompletedBuildUrl, ignoreUntrustedCertificate);
            res.LastSuccessfulBuild = GetBuildDetails(credentials, lastSuccessfulBuildUrl, ignoreUntrustedCertificate);
            res.LastFailedBuild     = GetBuildDetails(credentials, lastFailedBuildUrl, ignoreUntrustedCertificate);

            //logger.Info("Done updating project");
            return(res);
        }
        public AllBuildDetails UpdateProject(Project project)
        {
            String url = NetUtils.ConcatUrls(project.Url, "/api/xml");

            logger.Info("Updating project from " + url);

            Credentials credentials = project.Server.Credentials;
            bool        ignoreUntrustedCertificate = project.Server.IgnoreUntrustedCertificate;
            String      xmlStr = DownloadString(credentials, url, false, ignoreUntrustedCertificate);

            if (logger.IsTraceEnabled)
            {
                logger.Trace("XML: " + xmlStr);
            }

            XmlDocument xml = new XmlDocument();

            xml.LoadXml(xmlStr);

            string status = xml.SelectSingleNode("/*/color").InnerText;
            string lastCompletedBuildUrl  = XmlUtils.SelectSingleNodeText(xml, "/*/lastCompletedBuild/url");
            string lastSuccessfulBuildUrl = XmlUtils.SelectSingleNodeText(xml, "/*/lastSuccessfulBuild/url");
            string lastFailedBuildUrl     = XmlUtils.SelectSingleNodeText(xml, "/*/lastFailedBuild/url");
            bool?  stuck = XmlUtils.SelectSingleNodeBoolean(xml, "/*/queueItem/stuck");

            AllBuildDetails res = new AllBuildDetails();

            res.Status              = GetStatus(status, stuck);
            res.LastCompletedBuild  = GetBuildDetails(credentials, lastCompletedBuildUrl, ignoreUntrustedCertificate);
            res.LastSuccessfulBuild = GetBuildDetails(credentials, lastSuccessfulBuildUrl, ignoreUntrustedCertificate);
            res.LastFailedBuild     = GetBuildDetails(credentials, lastFailedBuildUrl, ignoreUntrustedCertificate);

            logger.Info("Done updating project");
            return(res);
        }
        private BuildDetails GetBuildDetails(Credentials credentials, string buildUrl, bool ignoreUntrustedCertificate)
        {
            if (buildUrl == null)
            {
                return(null);
            }

            String url = NetUtils.ConcatUrls(buildUrl, "/api/xml");

            if (logger.IsDebugEnabled)
            {
                logger.Debug("Getting build details from " + url);
            }

            String xmlStr = DownloadString(credentials, url, true, ignoreUntrustedCertificate);

            if (logger.IsTraceEnabled)
            {
                logger.Trace("XML: " + xmlStr);
            }

            XmlDocument xml = new XmlDocument();

            xml.LoadXml(xmlStr);

            string      number    = xml.SelectSingleNode("/*/number").InnerText;
            string      timestamp = xml.SelectSingleNode("/*/timestamp").InnerText;
            XmlNodeList userNodes = xml.SelectNodes("/*/culprit/fullName");

            TimeSpan ts   = TimeSpan.FromSeconds(long.Parse(timestamp) / 1000);
            DateTime date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            date = date.Add(ts);

            ISet <string> users = new HashedSet <string>();

            foreach (XmlNode userNode in userNodes)
            {
                string userName = StringUtils.ExtractUserName(userNode.InnerText);
                users.Add(userName);
            }

            BuildDetails res = new BuildDetails();

            res.Number = int.Parse(number);
            res.Time   = date;
            res.Users  = users;

            ClaimService.FillInBuildDetails(res, xml);

            if (logger.IsDebugEnabled)
            {
                logger.Debug("Done getting build details");
            }

            return(res);
        }
Ejemplo n.º 6
0
        public void ClaimBuild(Project project, BuildDetails buildDetails, string reason, bool sticky)
        {
            string url     = NetUtils.ConcatUrls(project.Url, buildDetails.Number.ToString(), "/claim/claim");
            var    request = (HttpWebRequest)WebRequest.Create(url);

            request.Method      = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            // we don't want to follow redirections
            request.AllowAutoRedirect = false;

            var credentials = project.Server.Credentials;

            if (credentials != null)
            {
                request.Credentials = new NetworkCredential(credentials.Username, credentials.Password);
            }

            using (Stream postStream = request.GetRequestStream())
            {
                var claim = new ClaimDetailsDto
                {
                    Reason = reason,
                    Sticky = sticky
                };

                var stream     = new MemoryStream();
                var serializer = new DataContractJsonSerializer(typeof(ClaimDetailsDto));
                serializer.WriteObject(stream, claim);
                string json = Encoding.UTF8.GetString(stream.ToArray());

                string postData = "json=" + HttpUtility.UrlEncode(json, Encoding.UTF8);
                using (var writer = new StreamWriter(postStream))
                {
                    writer.Write(postData);
                }
            }

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode != HttpStatusCode.Found && response.StatusCode != HttpStatusCode.OK)
                {
                    throw new Exception("Received response code " + response.StatusCode);
                }
            }

            string buildUrl = NetUtils.ConcatUrls(project.Url, buildDetails.Number.ToString(), "/api/xml");

            JenkinsService.RemoveFromCache(buildUrl);
        }
        public void RunBuild(Project project)
        {
            String url = NetUtils.ConcatUrls(project.Url, "/build?delay=0sec");

            logger.Info("Running build at " + url);

            Credentials credentials = project.Server.Credentials;
            String      str         = DownloadString(credentials, url, false, project.Server.IgnoreUntrustedCertificate);

            if (logger.IsTraceEnabled)
            {
                logger.Trace("Result: " + str);
            }

            logger.Info("Done running build");
        }
Ejemplo n.º 8
0
        public List <Project> GetProjects(XmlNodeList jobElements, Server server)
        {
            var projects = new List <Project>();

            foreach (XmlNode jobElement in jobElements)
            {
                var projectName  = jobElement.SelectSingleNode("name").InnerText;
                var projectUrl   = jobElement.SelectSingleNode("url").InnerText;
                var projectColor = jobElement.SelectSingleNode("color");
                // If the job is a folder we need to recursively get the jobs within.
                if (jobElement.SelectSingleNode("color") == null)
                {
                    var url    = NetUtils.ConcatUrls(projectUrl, "/api/xml?tree=jobs[name,url,color]");
                    var xmlStr = DownloadString(server.Credentials, url, false, server.IgnoreUntrustedCertificate);
                    var xml    = new XmlDocument();
                    xml.LoadXml(xmlStr);
                    var nodes = xml.SelectNodes("/folder/job");
                    if (nodes.Count == 0)
                    {
                        nodes = xml.SelectNodes("/workflowMultiBranchProject/job");
                    }
                    projects.AddRange(GetProjects(nodes, server));
                }
                else
                {
                    var project = new Project();
                    project.Server = server;
                    project.Name   = projectName;
                    project.Url    = projectUrl;

                    if (logger.IsDebugEnabled)
                    {
                        logger.Debug("Found project " + projectName + " (" + projectUrl + ")");
                    }

                    // Ensure only unique entries in the returned list.
                    if (!projects.Contains(project))
                    {
                        projects.Add(project);
                    }
                }
            }
            return(projects);
        }
        public IList <Project> LoadProjects(Server server)
        {
            String url = NetUtils.ConcatUrls(server.Url, "/api/xml");

            logger.Info("Loading projects from " + url);

            String xmlStr = DownloadString(server.Credentials, url, false, server.IgnoreUntrustedCertificate);

            if (logger.IsTraceEnabled)
            {
                logger.Trace("XML: " + xmlStr);
            }

            XmlDocument xml = new XmlDocument();

            xml.LoadXml(xmlStr);

            XmlNodeList jobElements = xml.SelectNodes("/hudson/job");
            var         projects    = new List <Project>();

            foreach (XmlNode jobElement in jobElements)
            {
                string projectName = jobElement.SelectSingleNode("name").InnerText;
                string projectUrl  = jobElement.SelectSingleNode("url").InnerText;

                Project project = new Project();
                project.Server = server;
                project.Name   = projectName;
                project.Url    = projectUrl;

                if (logger.IsDebugEnabled)
                {
                    logger.Debug("Found project " + projectName + " (" + projectUrl + ")");
                }

                projects.Add(project);
            }

            logger.Info("Done loading projects");

            return(projects);
        }
Ejemplo n.º 10
0
        public IList <Project> LoadProjects(Server server)
        {
            var url = NetUtils.ConcatUrls(server.Url, "/api/xml?tree=jobs[name,url,color]");

            logger.Info("Loading projects from " + url);

            var xmlStr = DownloadString(server.Credentials, url, false, server.IgnoreUntrustedCertificate);

            if (logger.IsTraceEnabled)
            {
                logger.Trace("XML: " + xmlStr);
            }

            var xml = new XmlDocument();

            xml.LoadXml(xmlStr);

            var jobElements = xml.SelectNodes("/hudson/job");
            var projects    = GetProjects(jobElements, server);

            logger.Info("Done loading projects");

            return(projects);
        }
Ejemplo n.º 11
0
        public void RunBuild(Project project)
        {
            String url = NetUtils.ConcatUrls(project.Url, "/build?delay=0sec");

            if (!string.IsNullOrEmpty(project.AuthenticationToken))
            {
                url = NetUtils.ConcatUrlsWithoutTrailingSlash(url, "&token=", HttpUtility.UrlEncodeUnicode(project.AuthenticationToken));
                if (!string.IsNullOrEmpty(project.CauseText))
                {
                    url = NetUtils.ConcatUrlsWithoutTrailingSlash(url, "&cause=", HttpUtility.UrlEncodeUnicode(project.CauseText));
                }
            }
            logger.Info("Running build at " + url);

            Credentials credentials = project.Server.Credentials;
            String      str         = UploadString(credentials, url, project.Server.IgnoreUntrustedCertificate);

            if (logger.IsTraceEnabled)
            {
                logger.Trace("Result: " + str);
            }

            logger.Info("Done running build");
        }
Ejemplo n.º 12
0
        private BuildDetails GetBuildDetails(Credentials credentials, string buildUrl, bool ignoreUntrustedCertificate)
        {
            if (buildUrl == null)
            {
                return(null);
            }

            var url = NetUtils.ConcatUrls(buildUrl, "/api/xml", JenkinsService.buildDetailsFilter);

            if (logger.IsDebugEnabled)
            {
                logger.Debug("Getting build details from " + url);
            }

            var xmlStr = DownloadString(credentials, url, true, ignoreUntrustedCertificate);

            if (logger.IsTraceEnabled)
            {
                logger.Trace("XML: " + xmlStr);
            }

            var xml = new XmlDocument();

            xml.LoadXml(xmlStr);

            var number            = xml.SelectSingleNode("/*/number").InnerText;
            var fullDisplayName   = xml.SelectSingleNode("/*/fullDisplayName").InnerText;
            var timestamp         = xml.SelectSingleNode("/*/timestamp").InnerText;
            var estimatedDuration = xml.SelectSingleNode("/*/estimatedDuration").InnerText;
            var duration          = xml.SelectSingleNode("/*/duration").InnerText;
            var xmlResult         = xml.SelectSingleNode("/*/result");
            var result            = xmlResult == null ? string.Empty : xmlResult.InnerText;
            var userNodes         = xml.SelectNodes("/*/culprit/fullName");

            var ts   = TimeSpan.FromSeconds(long.Parse(timestamp) / 1000);
            var date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            date = date.Add(ts);
            var estimatedts = TimeSpan.FromSeconds(long.Parse(estimatedDuration) / 1000);
            var durationts  = TimeSpan.FromSeconds(long.Parse(estimatedDuration) / 1000);

            Spring.Collections.Generic.ISet <string> users = new HashedSet <string>();
            foreach (XmlNode userNode in userNodes)
            {
                var userName = StringUtils.ExtractUserName(userNode.InnerText);
                users.Add(userName);
            }

            var res = new BuildDetails();

            BuildCauses.FillInBuildCauses(res, xml);
            res.Number            = int.Parse(number);
            res.DisplayName       = fullDisplayName;
            res.Time              = date;
            res.EstimatedDuration = estimatedts;
            res.Duration          = durationts;
            res.Result            = BuildStatus.StringToBuildStatus(result);
            res.Users             = users;

            ClaimService.FillInBuildDetails(res, xml);

            if (logger.IsDebugEnabled)
            {
                logger.Debug("Done getting build details");
            }

            return(res);
        }
Ejemplo n.º 13
0
        public void ClaimBuild(Project project, BuildDetails buildDetails, string reason, bool sticky)
        {
            var url     = NetUtils.ConcatUrls(project.Url, buildDetails.Number.ToString(), "/claim/claim");
            var request = (HttpWebRequest)WebRequest.Create(url);

            request.Method      = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            // we don't want to follow redirections
            request.AllowAutoRedirect = false;

            // currently supporting assigning to self
            var assignee = string.Empty;

            var credentials = project.Server.Credentials;

            if (credentials != null)
            {
                // claim plugin requests uses the username from the session cookie but not from request credentials
                request.Credentials = new NetworkCredential(credentials.Username, credentials.Password);
                assignee            = credentials.Username;
            }

            try
            {
                using (var postStream = request.GetRequestStream())
                {
                    var claim = new ClaimDetailsDto
                    {
                        Assignee = assignee,
                        Reason   = reason,
                        Sticky   = sticky
                    };

                    var stream     = new MemoryStream();
                    var serializer = new DataContractJsonSerializer(typeof(ClaimDetailsDto));
                    serializer.WriteObject(stream, claim);
                    var json = Encoding.UTF8.GetString(stream.ToArray());

                    var postData = "json=" + HttpUtility.UrlEncode(json, Encoding.UTF8);
                    using (var writer = new StreamWriter(postStream))
                    {
                        writer.Write(postData);
                    }
                }

                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.StatusCode != HttpStatusCode.Found && response.StatusCode != HttpStatusCode.OK)
                    {
                        throw new Exception("Received response code " + response.StatusCode);
                    }
                }
            }
            catch (WebException webEx)
            {
                MessageBox.Show(webEx.Message, "Claim failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                LoggingHelper.LogError(logger, webEx);
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(logger, ex);
            }
            var buildUrl = NetUtils.ConcatUrls(project.Url, buildDetails.Number.ToString(), "/api/xml");

            JenkinsService.RemoveFromCache(buildUrl);
        }