public IActionResult GetJobParameters(string jenkinsUrl, string name) { JenkinsConfig config = new JenkinsConfig() { JenkinsUrl = jenkinsUrl }; JenkinsClient client = new JenkinsClient(config); CancellationToken token = new CancellationToken(); var job = client.GetJob(name, token).Result; try { List <JenkinsJobParameter> parameters = new List <JenkinsJobParameter>(); var par = job.Actions.Where(a => a["parameterDefinitions"] != null).FirstOrDefault(); foreach (var item in par["parameterDefinitions"].Children()) { var p = Newtonsoft.Json.JsonConvert.DeserializeObject <JsonJobParameter>(item.ToString()); parameters.Add(new JenkinsJobParameter() { Name = p.Name, DataType = p.Type, DefaultValue = p.DefaultParameterValue.Value }); } return(Json(parameters)); } catch { } return(Json(false)); }
protected BaseClient(JenkinsClient jenkinsClient) { _jenkinsClient = jenkinsClient; Client = jenkinsClient.Client; BaseUri = jenkinsClient.BaseUri; _username = jenkinsClient.Username; }
public static JenkinsJobRunner Create(TextWriter writer, JenkinsClient client = null, bool quiet = false) #endif { client = client ?? DefaultClient.Create(); var jobRunner = new JenkinsJobRunner(client) { MonitorConsoleOutput = !quiet, }; if (!quiet) { jobRunner.StatusChanged += () => { writer.WriteLine($"[{DateTime.Now}] Status: '{jobRunner.Status}'"); }; #if NETCORE // Write method not available! jobRunner.ConsoleOutputChanged += writer.WriteLine; #else jobRunner.ConsoleOutputChanged += writer.Write; #endif } return(jobRunner); }
public IActionResult GetJobs(string jenkinsUrl) { // "http://jenkins-dbforge.datasoft.local:8080/job/Oracle4.0/" JenkinsConfig config = new JenkinsConfig() { JenkinsUrl = jenkinsUrl }; JenkinsClient client = new JenkinsClient(config); CancellationToken token = new CancellationToken(); var master = client.GetMaster(token).Result; var result = new List <JenkinsJob>(); foreach (var job in master.Jobs) { result.Add(new JenkinsJob() { Name = job.Name, Color = job.Color, Url = job.Url.ToString() }); } Console.WriteLine($"{DateTime.Now.TimeOfDay.ToString()}: get-jobs for {jenkinsUrl} = {result.Count}"); return(Json(result)); }
private void JenkinsWindowLoaded(object sender, System.Windows.RoutedEventArgs e) { jenkinsClient = new JenkinsClient { BaseUrl = $"http://{Host}:{Port}/", UserName = User, ApiToken = ApiKey, }; var jenkins = jenkinsClient.Get(); List <Job> jobList = new List <Job>(); foreach (var job in jenkins.Jobs) { jobList.Add(new Job { Name = job.Name }); } foreach (var job in jenkins.Jobs) { fields = new List <JobProperty>(); JenkinsJobBase jenkinsJob = jenkinsClient.Jobs.Get <JenkinsJobBase>(job.Name) as JenkinsJobBase; foreach (var action in jenkinsJob.Actions) { FindAllNodes(action.Node); } jobData[job.Name] = fields; } Jobs = new ObservableCollection <Job>(jobList); JobCombo.SelectedItem = Jobs[0]; }
public JenkinsTests(ITestOutputHelper testOutputHelper) { LogSettings.RegisterDefaultLogger <XUnitLogger>(LogLevels.Verbose, testOutputHelper); var testUriString = Environment.GetEnvironmentVariable("jenkins_test_uri") ?? "https://jenkins.qa.ubuntu.com/"; if (string.IsNullOrEmpty(testUriString)) { throw new ArgumentNullException("jenkins_test_uri"); } var testUri = new Uri(testUriString); _jenkinsApi = JenkinsClient.Create(testUri); var username = Environment.GetEnvironmentVariable("jenkins_test_username"); var apiKey = Environment.GetEnvironmentVariable("jenkins_test_apikey"); if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(apiKey)) { _hasCredentials = true; _jenkinsApi.SetBasicAuthentication(username, apiKey); } else { _hasCredentials = false; } _jenkinsApi.Settings.IgnoreSslCertificateErrors = true; }
public IActionResult BuildJob(string jenkinsUrl, string name, string parameters) { JenkinsConfig config = new JenkinsConfig() { JenkinsUrl = jenkinsUrl }; JenkinsClient client = new JenkinsClient(config); CancellationToken token = new CancellationToken(); var result = Newtonsoft.Json.JsonConvert.DeserializeObject <Parameter[]>(parameters); Dictionary <string, string> param = new Dictionary <string, string>(result.Length); foreach (var item in result) { param.Add(item.Key, item.Value); } try { client.BuildProjectWithParameters(name, param, token).Wait(); } catch (Exception e) { return(Json(false)); } return(Json(true)); }
public override async Task <IEnumerable <string> > EnumerateValuesAsync(ValueEnumerationContext context) { var credentials = ResourceCredentials.Create <JenkinsCredentials>(this.CredentialName); var client = new JenkinsClient(credentials); return(await client.GetBuildNumbersAsync(this.JobName).ConfigureAwait(false)); }
public ServerViewModel(JenkinsClient client, Server server) { m_server = server; m_jobs = new ObservableCollection<JobViewModel>(); m_client = client; Initialize(); }
public ServerViewModel(JenkinsClient client, Server server) { m_server = server; m_jobs = new ObservableCollection <JobViewModel>(); m_client = client; Initialize(); }
public JenkinsClient GetClient(Uri serverUri) { var client = new JenkinsClient(serverUri); client.CredentialsProvider = new CredStoreProvider(serverUri); return client; }
public BuildTablePopulator(CloudTableClient tableClient, JenkinsClient client, TextWriter textWriter) : this( buildResultDateTable : tableClient.GetTableReference(AzureConstants.TableNames.BuildResultDate), buildResultExactTable : tableClient.GetTableReference(AzureConstants.TableNames.BuildResultExact), buildFailureDateTable : tableClient.GetTableReference(AzureConstants.TableNames.BuildFailureDate), buildFailureExactTable : tableClient.GetTableReference(AzureConstants.TableNames.BuildFailureExact), viewNameDateTable : tableClient.GetTableReference(AzureConstants.TableNames.ViewNameDate), client : client, textWriter : textWriter) { }
public MainWindow() { InitializeComponent(); var jenkinsAddress = new Uri(ConfigurationManager.AppSettings["JenkinsAddress"]); var username = ConfigurationManager.AppSettings["Username"]; var apiToken = ConfigurationManager.AppSettings["ApiToken"]; _client = new JenkinsClient(jenkinsAddress, username, apiToken); }
public BuildTablePopulator(CloudTableClient tableClient, CounterUtilFactory factory, JenkinsClient client, TextWriter textWriter) : this( buildResultDateTable: tableClient.GetTableReference(TableNames.BuildResultDate), buildResultExactTable: tableClient.GetTableReference(TableNames.BuildResultExact), buildFailureDateTable: tableClient.GetTableReference(TableNames.BuildFailureDate), buildFailureExactTable: tableClient.GetTableReference(TableNames.BuildFailureExact), viewNameDateTable: tableClient.GetTableReference(TableNames.ViewNameDate), buildCounterUtil: factory.Create<BuildCounterEntity>(tableClient.GetTableReference(TableNames.CounterBuilds)), client: client, textWriter: textWriter) { }
static int Main(string[] args) { int retVal = 0; Parser.Default.ParseArguments <Options>(args) .WithNotParsed(errors => { foreach (var error in errors) { Console.WriteLine(error.ToString()); } retVal = 1; }) .WithParsed(options => { try { using (var jenkinsClient = new JenkinsClient(JenkinsOptions.Current())) { if (options.Parameters.Count() == 0) { jenkinsClient.SubmitJobAsync(options.JobName) .Wait(); } else { IEnumerable <(string, string)> parameters = options.Parameters.Select(p => { string[] parts = p.Split('='); if (parts.Length != 2) { throw new Exception("parameter name-value pair must be separated by an equals sign"); } return(parts[0], parts[1]); }); jenkinsClient.SubmitParameterizedJob(options.JobName, parameters) .Wait(); } } } catch (Exception e) { do { Console.WriteLine(e.Message); e = e.InnerException; }while (e != null); retVal = 1; } }); return(retVal); }
private bool AddServer(string serverUri, bool authRequired = false, bool promptCreds = true) { if (m_servers.Any(x => x.DomainUrl == serverUri)) { return(false); } UserCredentials userCreds = null; if (authRequired) { userCreds = PromptForCredentials(serverUri, promptCreds); if (userCreds == null) { MessageBox.Show("Please check your username and password", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return(false); } } ServerViewModel serverViewModel; try { JenkinsClient client = new JenkinsClient(new Uri(serverUri, UriKind.Absolute), userCreds); Server server = client.GetJson <Server>(new Uri(serverUri)); server.RequiresAuthentication = authRequired; serverViewModel = new ServerViewModel(client, server); } catch (Exception ex) { MessageBox.Show(ex.Message ?? ex.InnerException?.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); return(false); } SavedJenkinsServers savedServer = m_settings.Servers.FirstOrDefault(x => x.DomainUrl == serverViewModel.DomainUrl); foreach (JobViewModel job in serverViewModel.Jobs) { if (savedServer != null) { job.IsSubscribed = savedServer.Jobs.Any(x => x.Name == job.Name); } job.StatusChanged += JobOnStatusChanged; } m_servers.Add(serverViewModel); SaveSettings(); return(true); }
protected override object EvaluateScalar(IVariableFunctionContext context) { var name = Inedo.Extensibility.Credentials.CredentialName.TryParse(this.CredentialName); if (name == null) { throw new ExecutionFailureException(true, $"The specified credential name \"{this.CredentialName}\" is invalid."); } // need to resolve credential type name if it's not specified with the scope resolution operator if (name.TypeName == null) { var types = (from c in SDK.GetCredentials() where string.Equals(c.Name, name.Name, StringComparison.OrdinalIgnoreCase) select c.LegacyResourceCredentialTypeName).ToHashSet(StringComparer.OrdinalIgnoreCase); if (types.Count == 0) { throw new ExecutionFailureException(true, $"There are no credentials named \"{name.Name}\" found in the system."); } if (types.Count > 1) { throw new ExecutionFailureException(true, $"There are multiple credential types with the name \"{name.Name}\" found in the system. Use the scope resolution operator (i.e. ::) to specify a type, for example: UsernamePassword::{name.Name}"); } name = new CredentialName(types.First(), name.Name); } var credential = ResourceCredentials.TryCreate(name.TypeName, name.Name, environmentId: context.EnvironmentId, applicationId: context.ProjectId, inheritFromParent: true); if (credential == null) { throw new ExecutionFailureException($"Could not find a {name.TypeName} Resource Credentials named \"{name.Name}\"; this error may occur if you renamed a credential, or the application or environment in context does not match any existing credentials. To resolve, edit this item, property, or operation's configuration, ensure a valid credential for the application/environment in context is selected, and then save."); } if (!(credential is JenkinsLegacyCredentials)) { throw new ExecutionFailureException($"Resource Credential \"{name.Name}\" is not a Jenkins Credential."); } var jenkins = (JenkinsLegacyCredentials)credential; UriBuilder uri = new UriBuilder(jenkins.ServerUrl) { Path = JenkinsClient.GetPath(this.JobName, this.BranchName, this.BuildNumber) }; return(uri.ToString()); }
public BuildTablePopulatorTests() { var account = Util.GetStorageAccount(); var tableClient = account.CreateCloudTableClient(); _restClient = new MockRestClient(); var client = new JenkinsClient(new Uri("http://test.com"), _restClient.Client); _buildFailureExactTable = tableClient.GetTableReference(AzureConstants.TableNames.BuildFailureExact); _buildResultExactTable = tableClient.GetTableReference(AzureConstants.TableNames.BuildResultExact); _populator = new BuildTablePopulator( tableClient, client: client, factory: new CounterUtilFactory(), textWriter: new StringWriter()); }
public BuildTablePopulator(CloudTable buildResultDateTable, CloudTable buildResultExactTable, CloudTable buildFailureDateTable, CloudTable buildFailureExactTable, CloudTable viewNameDateTable, JenkinsClient client, TextWriter textWriter) { Debug.Assert(buildResultDateTable.Name == AzureConstants.TableNames.BuildResultDate); Debug.Assert(buildResultExactTable.Name == AzureConstants.TableNames.BuildResultExact); Debug.Assert(buildFailureDateTable.Name == AzureConstants.TableNames.BuildFailureDate); Debug.Assert(buildFailureExactTable.Name == AzureConstants.TableNames.BuildFailureExact); Debug.Assert(viewNameDateTable.Name == AzureConstants.TableNames.ViewNameDate); _buildResultDateTable = buildResultDateTable; _buildResultExactTable = buildResultExactTable; _buildFailureDateTable = buildFailureDateTable; _buildFailureExactTable = buildFailureExactTable; _viewNameDateTable = viewNameDateTable; _client = client; _textWriter = textWriter; }
private static async Task SetupDeleteJobAsync(JenkinsClient client) { var jenkins = await client.GetAsync(); if (jenkins.Jobs.Any(x => string.Equals(x.Name, "Delete Job", System.StringComparison.OrdinalIgnoreCase))) { return; } var createJob = await client.Jobs.GetConfigurationAsync("Test Job"); var deleteJob = new JenkinsProject(createJob.Node); await client.Jobs.CreateAsync("Delete Job", deleteJob); }
public BuildTablePopulatorTests() { var account = Util.GetStorageAccount(); var tableClient = account.CreateCloudTableClient(); _restClient = new MockRestClient(); var client = new JenkinsClient(SharedConstants.DotnetJenkinsUri, _restClient.Client); _buildFailureExactTable = tableClient.GetTableReference(AzureConstants.TableNames.BuildFailureExact); _buildResultExactTable = tableClient.GetTableReference(AzureConstants.TableNames.BuildResultExact); _populator = new BuildTablePopulator( tableClient, client: client, textWriter: new StringWriter()); }
public async Task JenkinsClientWouldCallApi() { var handler = new MockHttpMessageHandler() .Set("{ \"DisplayName\": \"A\", \"Result\":\"B\" }", "application/json"); var httpClient = new HttpClient(handler); var factory = Substitute.For <IHttpClientFactory>(); var client = new JenkinsClient(factory); factory.CreateClient("JenkinsClient").Returns(httpClient); var result = await client.QueryAsync("abc", "https://test.jenkins.com", "def", "jh"); Assert.AreEqual("A", result.DisplayName); Assert.AreEqual("https://test.jenkins.com/job/abc/lastBuild/api/json?tree=building,description,displayName,result,url,changeSet[items[comment]]", handler.Responses[0].Url); }
private JenkinsClient CreateClient(IOperationExecutionContext context) { var(c, r) = this.GetCredentialsAndResource(context); var up = c as Extensions.Credentials.UsernamePasswordCredentials; var api = c as Extensions.Credentials.TokenCredentials; var client = new JenkinsClient( up?.UserName, up?.Password ?? api?.Token, r?.ServerUrl, csrfProtectionEnabled: false, this, context.CancellationToken ); return(client); }
public BuildTablePopulator(CloudTable buildResultDateTable, CloudTable buildResultExactTable, CloudTable buildFailureDateTable, CloudTable buildFailureExactTable, CloudTable viewNameDateTable, CounterUtil<BuildCounterEntity> buildCounterUtil, JenkinsClient client, TextWriter textWriter) { Debug.Assert(buildResultDateTable.Name == TableNames.BuildResultDate); Debug.Assert(buildResultExactTable.Name == TableNames.BuildResultExact); Debug.Assert(buildFailureDateTable.Name == TableNames.BuildFailureDate); Debug.Assert(buildFailureExactTable.Name == TableNames.BuildFailureExact); Debug.Assert(viewNameDateTable.Name == TableNames.ViewNameDate); Debug.Assert(buildCounterUtil.Table.Name == TableNames.CounterBuilds); _buildResultDateTable = buildResultDateTable; _buildResultExactTable = buildResultExactTable; _buildFailureDateTable = buildFailureDateTable; _buildFailureExactTable = buildFailureExactTable; _viewNameDateTable = viewNameDateTable; _buildCounterUtil = buildCounterUtil; _client = client; _textWriter = textWriter; }
public BuildTablePopulator(CloudTable buildResultDateTable, CloudTable buildResultExactTable, CloudTable buildFailureDateTable, CloudTable buildFailureExactTable, CloudTable viewNameDateTable, CounterUtil <BuildCounterEntity> buildCounterUtil, JenkinsClient client, TextWriter textWriter) { Debug.Assert(buildResultDateTable.Name == TableNames.BuildResultDate); Debug.Assert(buildResultExactTable.Name == TableNames.BuildResultExact); Debug.Assert(buildFailureDateTable.Name == TableNames.BuildFailureDate); Debug.Assert(buildFailureExactTable.Name == TableNames.BuildFailureExact); Debug.Assert(viewNameDateTable.Name == TableNames.ViewNameDate); Debug.Assert(buildCounterUtil.Table.Name == TableNames.CounterBuilds); _buildResultDateTable = buildResultDateTable; _buildResultExactTable = buildResultExactTable; _buildFailureDateTable = buildFailureDateTable; _buildFailureExactTable = buildFailureExactTable; _viewNameDateTable = viewNameDateTable; _buildCounterUtil = buildCounterUtil; _client = client; _textWriter = textWriter; }
public IActionResult GetMaster(string jenkinsUrl) { JenkinsConfig config = new JenkinsConfig() { JenkinsUrl = jenkinsUrl }; JenkinsClient client = new JenkinsClient(config); CancellationToken token = new CancellationToken(); var master = client.GetMaster(token).Result; JenkinsMaster result = new JenkinsMaster() { Name = master.Name }; return(Json(result)); }
public static JenkinsJobRunner Create(TextWriter writer, JenkinsClient client = null) { client = client ?? DefaultClient.Create(); var jobRunner = new JenkinsJobRunner(client) { MonitorConsoleOutput = true, }; jobRunner.StatusChanged += () => { writer.WriteLine($"[{DateTime.Now}] Status: '{jobRunner.Status}'"); }; jobRunner.ConsoleOutputChanged += newText => { writer.Write(newText); }; return(jobRunner); }
public IActionResult GetJob(string jenkinsUrl, string name) { JenkinsConfig config = new JenkinsConfig() { JenkinsUrl = jenkinsUrl }; JenkinsClient client = new JenkinsClient(config); CancellationToken token = new CancellationToken(); var job = client.GetJob(name, token).Result; int?health = job.HealthReport.FirstOrDefault()?.Score; // var lastBuild = client.GetBuild(name, job.LastBuild.Number.ToString(), token).Result; string lastBuildResult = "UNKNOWN"; if (job.LastBuild != null && job.LastSuccessfulBuild != null) { lastBuildResult = job.LastBuild.Number == job.LastSuccessfulBuild.Number ? "SUCCESS" : "FAILED"; } // string lastBuildResult = (DateTime.Now.Millisecond % 2 == 0) ? "SUCCESS" : "FAILED"; var result = new JenkinsJob() { Name = job.Name, Color = job.Color, Building = job.Color.Contains("anime"), Url = job.Url.ToString(), Buildable = job.Buildable, Health = health.GetValueOrDefault(-1), LastBuild = new JenkinsBuild() { Url = job.LastBuild.Url.ToString(), Number = job.LastBuild.Number, Result = lastBuildResult }, }; return(Json(result)); }
public async Task JenkinsJob_TriggerAsync_Should_Fail_When_CrumbIsInvalid() { var logger = Substitute.For <ILogger>(); var dialogService = Substitute.For <IDialogService>(); var jenkinsClient = new JenkinsClient(logger); dialogService.Show(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <MessageBoxButton>(), Arg.Any <MessageBoxImage>()) .Returns(MessageBoxResult.Yes); var jenkinsJob = new JenkinsJob_v1 { Name = "Jenkins Core", IgnoreSslErrors = true, CSRF = true, URL = @"https://ci.jenkins-ci.org/job/Core/job/jenkins/job/master/", }; var trigger = new TriggerJenkinsJob(dialogService, logger, jenkinsClient); await trigger.HandleAsync(jenkinsJob); }
public void JenkinsJobs_Monitor() { var jenkinsJobPlugin = new JenkinsJob_v1 { Name = "Jenkins Core", IgnoreSslErrors = true, URL = @"https://builds.apache.org/job/logging-log4net/job/master/", }; var logger = Substitute.For <ILogger>(); var jenkinsClient = new JenkinsClient(logger); var jenkins = new JenkinsJobMonitor(jenkinsClient); jenkins.Handle(jenkinsJobPlugin); Assert.AreNotEqual(State.None, jenkinsJobPlugin.State, "Plugin state is None."); Assert.AreNotEqual(State.Unknown, jenkinsJobPlugin.State, "Plugin state is Unknown."); Assert.AreNotEqual(State.Error, jenkinsJobPlugin.State, "Plugin state is Error."); }
private static void ExecuteJenkinsJob() { var jobName = Env.GetString("JOB"); var client = new JenkinsClient(Env.GetString("JENKINS_HOST")) { UserName = Env.GetString("JENKINS_USER"), ApiToken = Env.GetString("JENKINS_API_KEY") }; client.UpdateSecurityCrumb(); if (Env.GetBool("WAIT_FOR_COMPLETION")) { var jenkinsJobRunner = new JenkinsJobRunner(client) { BuildTimeout = Env.GetInt("BUILD_TIMEOUT", 600) }; Log.Information("Starting build"); var buildBase = jenkinsJobRunner.Run(jobName); if (Env.GetBool("TERMINATE_ON_FAILURE") && buildBase.Result != "SUCCESS") { Log.Error("Build status was " + buildBase.Result); Environment.Exit(1); } if (Env.GetBool("DOWNLOAD_ARTIFACT")) { if (buildBase.Id != null) { DownloadArtifact(client, jobName, buildBase.Id.Value, Env.GetString("ARTIFACT_NAME")); } } } else { client.Jobs.Build(jobName); } Log.Information("Completed"); }
private bool AddServer(string serverUri) { if (m_servers.Any(x => x.DomainUrl == serverUri)) { return(false); } ServerViewModel serverViewModel; try { JenkinsClient client = new JenkinsClient(new Uri(serverUri, UriKind.Absolute)); Server server = client.GetJson <Server>(new Uri(serverUri)); serverViewModel = new ServerViewModel(client, server); } catch (Exception) { return(false); } SavedJenkinsServers savedServer = m_settings.Servers.FirstOrDefault(x => x.DomainUrl == serverViewModel.DomainUrl); foreach (JobViewModel job in serverViewModel.Jobs) { if (savedServer != null) { job.IsSubscribed = savedServer.Jobs.Any(x => x.Name == job.Name); } job.StatusChanged += JobOnStatusChanged; } m_servers.Add(serverViewModel); return(true); }
public JobsClient(JenkinsClient jenkinsClient) : base(jenkinsClient) { }
protected JenkinsClientTests() { _client = new JenkinsClient(new Uri("http://invalid.com"), _restClient.Client); }
private bool AddServer(string serverUri) { if (m_servers.Any(x => x.DomainUrl == serverUri)) return false; ServerViewModel serverViewModel; try { JenkinsClient client = new JenkinsClient(new Uri(serverUri, UriKind.Absolute)); Server server = client.GetJson<Server>(new Uri(serverUri)); serverViewModel = new ServerViewModel(client, server); } catch (Exception) { return false; } SavedJenkinsServers savedServer = m_settings.Servers.FirstOrDefault(x => x.DomainUrl == serverViewModel.DomainUrl); foreach (JobViewModel job in serverViewModel.Jobs) { if (savedServer != null) job.IsSubscribed = savedServer.Jobs.Any(x => x.Name == job.Name); job.StatusChanged += JobOnStatusChanged; } m_servers.Add(serverViewModel); return true; }
public JobViewModel(string name, Uri path, JenkinsClient client) { m_name = name; m_path = path; m_client = client; }
public RoslynClient() { _client = new JenkinsClient(); }
private async void SearchBuilds(object obj) { this.client = this.clientFactory.GetClient(this.viewModel.SelectedInstance.Url); List<BuildModel> builds; if (this.viewModel.SelectedJob is AllJobsModel) { builds = await SearchBuildsInAllJobs(); } else { builds = await SearchBuildsInJob(this.viewModel.SelectedJob); } if (this.viewModel.SelectedStatus.Status != null) { builds = builds.Where(x => x.Status == this.viewModel.SelectedStatus.Status).ToList(); } this.viewModel.Builds = builds; }