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 all 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;
}
}
53 changes: 42 additions & 11 deletions src/main/java/io/codemc/bot/commands/CmdApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,13 @@

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CmdApplication extends BotCommand{


public static final Pattern PROJECT_URL_PATTERN = Pattern.compile("^https://ci\\.codemc\\.io/job/([a-zA-Z0-9-]+)/job/([a-zA-Z0-9-_.]+)/?$");

public CmdApplication(CodeMCBot bot){
super(bot);

Expand All @@ -64,7 +67,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 @@ -121,7 +124,8 @@ public static void handle(CodeMCBot bot, InteractionHook hook, Guild guild, long
.send();
return;
}


String finalRepoLink = repoLink;
channel.sendMessage(getMessage(bot, userId, userLink, repoLink, str, accepted)).queue(m -> {
ThreadChannel thread = message.getStartedThread();
if(thread != null && !thread.isArchived()){
Expand All @@ -141,6 +145,33 @@ public static void handle(CodeMCBot bot, InteractionHook hook, Guild guild, long
.send();
return;
}

Matcher matcher = PROJECT_URL_PATTERN.matcher(str);
if (!matcher.matches()) {
CommandUtil.EmbedReply.fromHook(hook)
.withError("The provided Project URL did not match the pattern `https://ci.codemc.io/job/<user>/job/<project>`!")
.send();
return;
}

String username = matcher.group(1);
String project = matcher.group(2);

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, finalRepoLink, 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 @@ -195,9 +226,7 @@ private static MessageCreateData getMessage(CodeMCBot bot, String userId, String
}

private static class Accept extends BotCommand{

private final Pattern projectUrlPattern = Pattern.compile("^https://ci\\.codemc\\.io/job/[a-zA-Z0-9-]+/job/[a-zA-Z0-9-_.]+/?$");


public Accept(CodeMCBot bot){
super(bot);

Expand All @@ -208,7 +237,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,22 +255,23 @@ 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(
"Message ID or Project URL were not present!"
).send();
return;
}
if(!projectUrlPattern.matcher(projectUrl).matches()){

if(!PROJECT_URL_PATTERN.matcher(projectUrl).matches()){
CommandUtil.EmbedReply.fromHook(hook).withError(
"The provided Project URL did not match the pattern `https://ci.codemc.io/job/<user>/job/<project>`!"
).send();
return;
}

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

Expand Down Expand Up @@ -281,7 +312,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);
}
}
}
115 changes: 115 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,115 @@
/*
* 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.nio.file.Files;
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;
}
}

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

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

private 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, String repoLink, boolean isFreestyle){
String template = isFreestyle ? jenkinsFreestyleJob() : jenkinsMavenJob();
if (template == null) return false;

template = template.replace("{PROJECT_URL}", repoLink);

// 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"
}
}
58 changes: 58 additions & 0 deletions src/main/resources/template-job-freestyle.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?xml version='1.1' encoding='UTF-8'?>
<project>
<actions/>
<description/>
<keepDependencies>false</keepDependencies>
<properties>
<com.coravy.hudson.plugins.github.GithubProjectProperty plugin="[email protected]">
<projectUrl>{PROJECT_URL}</projectUrl>
<displayName/>
</com.coravy.hudson.plugins.github.GithubProjectProperty>
<com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty plugin="[email protected]">
<gitLabConnection/>
<jobCredentialId/>
<useAlternativeCredential>false</useAlternativeCredential>
</com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty>
</properties>
<scm class="hudson.plugins.git.GitSCM" plugin="[email protected]">
<configVersion>2</configVersion>
<userRemoteConfigs>
<hudson.plugins.git.UserRemoteConfig>
<url>{PROJECT_URL}</url>
</hudson.plugins.git.UserRemoteConfig>
</userRemoteConfigs>
<branches>
<hudson.plugins.git.BranchSpec>
<name>*/master</name>
</hudson.plugins.git.BranchSpec>
</branches>
<doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
<submoduleCfg class="empty-list"/>
<extensions/>
</scm>
<canRoam>true</canRoam>
<disabled>false</disabled>
<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
<jdk>(System)</jdk>
<triggers>
<hudson.triggers.SCMTrigger>
<spec>H/15 * * * *</spec>
<ignorePostCommitHooks>false</ignorePostCommitHooks>
</hudson.triggers.SCMTrigger>
</triggers>
<concurrentBuild>false</concurrentBuild>
<builders/>
<publishers>
<hudson.tasks.ArtifactArchiver>
<artifacts>**/build/libs/*.jar</artifacts>
<allowEmptyArchive>false</allowEmptyArchive>
<onlyIfSuccessful>false</onlyIfSuccessful>
<fingerprint>false</fingerprint>
<defaultExcludes>true</defaultExcludes>
<caseSensitive>true</caseSensitive>
<followSymlinks>false</followSymlinks>
</hudson.tasks.ArtifactArchiver>
</publishers>
<buildWrappers/>
</project>
Loading