Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Jenkins Automation to Accept Command #4

Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,6 @@ hs_err_pid*
/.idea/misc.xml
/.idea/uiDesigner.xml
/.idea/vcs.xml

# local gradle stuff
.gradle/
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ dependencies {
implementation group: 'pw.chew', name: 'jda-chewtils-commons', version: '2.0-SNAPSHOT'
implementation group: 'pw.chew', name: 'jda-chewtils-command', version: '2.0-SNAPSHOT'
implementation group: 'org.spongepowered', name: 'configurate-gson', version: '4.1.2'
implementation group: 'io.github.cdancy', name: 'jenkins-rest', version: '1.0.2'
}

artifacts {
Expand Down
19 changes: 18 additions & 1 deletion src/main/java/io/codemc/bot/CodeMCBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import com.jagrosh.jdautilities.command.CommandClientBuilder;
import io.codemc.bot.commands.*;
import io.codemc.bot.config.ConfigHandler;
import io.codemc.bot.jenkins.JenkinsAPI;
import io.codemc.bot.listeners.ModalListener;
import io.codemc.bot.menu.ApplicationMenu;
import net.dv8tion.jda.api.JDABuilder;
Expand All @@ -37,6 +38,7 @@ public class CodeMCBot{

private final Logger logger = LoggerFactory.getLogger(CodeMCBot.class);
private final ConfigHandler configHandler = new ConfigHandler();
private final JenkinsAPI jenkins = new JenkinsAPI(this);

public static void main(String[] args){
try{
Expand Down Expand Up @@ -90,6 +92,13 @@ private void start() throws LoginException{

clientBuilder.setCoOwnerIds(coOwnerIds);
}

logger.info("Pinging Jenkins...");
if(!jenkins.ping()){
logger.warn("Unable to ping Jenkins! Please check your configuration.");
System.exit(1);
return;
}

logger.info("Adding commands...");
clientBuilder.addSlashCommands(
Expand All @@ -105,7 +114,7 @@ private void start() throws LoginException{
new ApplicationMenu.Accept(this),
new ApplicationMenu.Deny(this)
);

logger.info("Starting bot...");
JDABuilder.createDefault(token)
.enableIntents(
Expand All @@ -124,8 +133,16 @@ private void start() throws LoginException{
)
.build();
}

public Logger getLogger(){
return logger;
}

public ConfigHandler getConfigHandler(){
return configHandler;
}

public JenkinsAPI getJenkins(){
return jenkins;
}
}
30 changes: 26 additions & 4 deletions src/main/java/io/codemc/bot/commands/CmdApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public void withModalReply(SlashCommandEvent event){}
@Override
public void withHookReply(InteractionHook hook, SlashCommandEvent event, Guild guild, Member member){}

public static void handle(CodeMCBot bot, InteractionHook hook, Guild guild, long messageId, String str, boolean accepted){
public static void handle(CodeMCBot bot, InteractionHook hook, Guild guild, long messageId, String str, boolean accepted, boolean freestyle){
TextChannel requestChannel = guild.getTextChannelById(bot.getConfigHandler().getLong("channel", "request_access"));
if(requestChannel == null){
CommandUtil.EmbedReply.fromHook(hook).withError("Unable to retrieve `request-access` channel.").send();
Expand Down Expand Up @@ -141,6 +141,26 @@ public static void handle(CodeMCBot bot, InteractionHook hook, Guild guild, long
.send();
return;
}

String[] split = str.split("/");
String username = split[4];
String project = split[6];
gmitch215 marked this conversation as resolved.
Show resolved Hide resolved

boolean userSuccess = bot.getJenkins().createJenkinsUser(username);
if (!userSuccess) {
CommandUtil.EmbedReply.fromHook(hook)
.withError("Failed to create Jenkins user for " + username + "! Manual creation required.")
.send();
return;
}

boolean jobSuccess = bot.getJenkins().createJenkinsJob(username, project, freestyle);
if (!jobSuccess) {
CommandUtil.EmbedReply.fromHook(hook)
.withError("Failed to create Jenkins job for " + username + "! Manual creation required.")
.send();
return;
}

Role authorRole = guild.getRoleById(bot.getConfigHandler().getLong("author_role"));
if(authorRole == null){
Expand Down Expand Up @@ -208,7 +228,8 @@ public Accept(CodeMCBot bot){

this.options = Arrays.asList(
new OptionData(OptionType.STRING, "id", "The message id of the application.").setRequired(true),
new OptionData(OptionType.STRING, "project-url", "The URL of the newly made Project.").setRequired(true)
new OptionData(OptionType.STRING, "project-url", "The URL of the newly made Project. Their username should reflect their GitHub username, not their Discord username.").setRequired(true),
new OptionData(OptionType.BOOLEAN, "freestyle", "False if built with Maven. If built with something other than Maven (such as Gradle), set to true.").setRequired(true)
);
}

Expand All @@ -225,6 +246,7 @@ public void withHookReply(InteractionHook hook, SlashCommandEvent event, Guild g
}
});
String projectUrl = event.getOption("project-url", null, OptionMapping::getAsString);
boolean freestyle = event.getOption("freestyle", false, OptionMapping::getAsBoolean);

if(messageId == -1L || projectUrl == null){
CommandUtil.EmbedReply.fromHook(hook).withError(
Expand All @@ -240,7 +262,7 @@ public void withHookReply(InteractionHook hook, SlashCommandEvent event, Guild g
return;
}

handle(bot, hook, guild, messageId, projectUrl, true);
handle(bot, hook, guild, messageId, projectUrl, true, freestyle);
}
}

Expand Down Expand Up @@ -281,7 +303,7 @@ public void withHookReply(InteractionHook hook, SlashCommandEvent event, Guild g
return;
}

handle(bot, hook, guild, messageId, reason, false);
handle(bot, hook, guild, messageId, reason, false, false);
}
}
}
112 changes: 112 additions & 0 deletions src/main/java/io/codemc/bot/jenkins/JenkinsAPI.java
gmitch215 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
* Copyright 2024 CodeMC.io
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

package io.codemc.bot.jenkins;

import com.cdancy.jenkins.rest.JenkinsClient;
import com.cdancy.jenkins.rest.domain.common.RequestStatus;
import com.cdancy.jenkins.rest.domain.system.SystemInfo;
import io.codemc.bot.CodeMCBot;
import io.codemc.bot.config.ConfigHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

public class JenkinsAPI {

private final CodeMCBot bot;
private final JenkinsClient client;

public JenkinsAPI(CodeMCBot bot){
this.bot = bot;

ConfigHandler config = bot.getConfigHandler();
String url = config.getString("jenkins", "url");
String username = config.getString("jenkins", "username");
String token = config.getString("jenkins", "token");
this.client = JenkinsClient.builder()
.endPoint(url)
.credentials(username + ":" + token)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated question, but should we have a dedicated account for this? I feel like it would be a bit too risky to have one of our accounts used here (Assuming a user-account is used and there isn't a bot-system in Jenkins).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with making a separate bot account. It'll help identify what the bot is doing and could also improve security by only providing necessary permissions (e.g. only create accounts and no delete).

.build();
}

public boolean ping(){
SystemInfo info = client.api().systemApi().systemInfo();
return info != null;
}

// Templates

private String template(String path){
try(InputStream stream = CodeMCBot.class.getResourceAsStream(path)) {
if (stream == null) return null;
try (InputStreamReader isr = new InputStreamReader(stream)) {
BufferedReader reader = new BufferedReader(isr);
return reader.lines().collect(Collectors.joining(System.lineSeparator()));
} catch (IOException e) {
bot.getLogger().error("Error reading {}", path, e);
return null;
}
} catch (IOException e) {
bot.getLogger().error("Error finding {}", path, e);
return null;
}
}

public String jenkinsUserTemplate(){
return template("/template-user-config.xml");
}

public String jenkinsMavenJob(){
return template("/template-job-maven.xml");
}

public String jenkinsFreestyleJob(){
return template("/template-job-freestyle.xml");
}

// Functions

private String createJenkinsConfig(String username){
String template = jenkinsUserTemplate();
if (template == null) return null;

return template.replace("{USERNAME}", username);
}

public boolean createJenkinsUser(String username){
String config = createJenkinsConfig(username);
if (config == null) return false;

RequestStatus status = client.api().jobsApi().create("/", username, config);
return status.value();
}

public boolean createJenkinsJob(String username, String jobName, boolean isFreestyle){
String template = isFreestyle ? jenkinsFreestyleJob() : jenkinsMavenJob();
if (template == null) return false;

// Jenkins will automatically add job to the URL
RequestStatus status = client.api().jobsApi().create(username, jobName, template);
return status.value();
}

}
5 changes: 5 additions & 0 deletions src/main/resources/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,10 @@
"messages": {
"accepted": [],
"denied": []
},
"jenkins": {
"url": "URL",
"username": "USERNAME",
"token": "API TOKEN"
}
}
5 changes: 5 additions & 0 deletions src/main/resources/config.json.sample
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,10 @@
"",
"You may re-apply unless mentioned otherwise in the Reason."
]
},
"jenkins": {
"url": "https://ci.codemc.io",
"username": "admin",
"token": "admin_api_token"
}
}
23 changes: 23 additions & 0 deletions src/main/resources/template-job-freestyle.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version='1.1' encoding='UTF-8'?>
<project>
<actions/>
<description/>
<keepDependencies>false</keepDependencies>
<properties>
<com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty plugin="[email protected]">
<gitLabConnection/>
<jobCredentialId/>
<useAlternativeCredential>false</useAlternativeCredential>
</com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty>
</properties>
<scm class="hudson.scm.NullSCM"/>
<canRoam>true</canRoam>
<disabled>false</disabled>
<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
<triggers/>
<concurrentBuild>false</concurrentBuild>
<builders/>
<publishers/>
<buildWrappers/>
</project>
33 changes: 33 additions & 0 deletions src/main/resources/template-job-maven.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?xml version='1.1' encoding='UTF-8'?>
<maven2-moduleset plugin="[email protected]">
<keepDependencies>false</keepDependencies>
<properties/>
<scm class="hudson.scm.NullSCM"/>
<canRoam>true</canRoam>
<disabled>false</disabled>
<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
<triggers/>
<concurrentBuild>false</concurrentBuild>
<aggregatorStyleBuild>true</aggregatorStyleBuild>
<incrementalBuild>false</incrementalBuild>
<ignoreUpstremChanges>false</ignoreUpstremChanges>
<ignoreUnsuccessfulUpstreams>false</ignoreUnsuccessfulUpstreams>
<archivingDisabled>false</archivingDisabled>
<siteArchivingDisabled>false</siteArchivingDisabled>
<fingerprintingDisabled>false</fingerprintingDisabled>
<resolveDependencies>false</resolveDependencies>
<processPlugins>false</processPlugins>
<mavenValidationLevel>-1</mavenValidationLevel>
<runHeadless>false</runHeadless>
<disableTriggerDownstreamProjects>false</disableTriggerDownstreamProjects>
<settings class="jenkins.mvn.DefaultSettingsProvider"/>
<globalSettings class="org.jenkinsci.plugins.configfiles.maven.job.MvnGlobalSettingsProvider" plugin="[email protected]_a_80ecb_9a_4d0">
<settingsConfigId>e5b005b5-be4d-4709-8657-1981662bcbe3</settingsConfigId>
</globalSettings>
<reporters/>
<publishers/>
<buildWrappers/>
<prebuilders/>
<postbuilders/>
</maven2-moduleset>
Loading