-
Notifications
You must be signed in to change notification settings - Fork 749
Introduce JCasC configuration history tracking via listener extension point #2820
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
Closed
somiljain2006
wants to merge
4
commits into
jenkinsci:master
from
somiljain2006:Configuration-history-implementation
Closed
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
27 changes: 27 additions & 0 deletions
27
plugin/src/main/java/io/jenkins/plugins/casc/CasCReloadListener.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| package io.jenkins.plugins.casc; | ||
|
|
||
| import hudson.ExtensionList; | ||
| import hudson.ExtensionPoint; | ||
| import java.util.logging.Level; | ||
| import java.util.logging.Logger; | ||
|
|
||
| public interface CasCReloadListener extends ExtensionPoint { | ||
|
|
||
| void onConfigurationReloaded(); | ||
|
|
||
| static void fire() { | ||
| Logger logger = Logger.getLogger(CasCReloadListener.class.getName()); | ||
|
|
||
| for (CasCReloadListener listener : ExtensionList.lookup(CasCReloadListener.class)) { | ||
| try { | ||
| listener.onConfigurationReloaded(); | ||
| } catch (Exception e) { | ||
| logger.log( | ||
| Level.WARNING, | ||
| "Listener " + listener.getClass().getName() | ||
| + " threw an exception during CasC reload notification", | ||
| e); | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
126 changes: 126 additions & 0 deletions
126
plugin/src/main/java/io/jenkins/plugins/casc/history/CasCHistoryAction.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| package io.jenkins.plugins.casc.history; | ||
|
|
||
| import hudson.Extension; | ||
| import hudson.model.ManagementLink; | ||
| import java.io.File; | ||
| import java.io.IOException; | ||
| import java.nio.file.Files; | ||
| import java.time.LocalDateTime; | ||
| import java.time.format.DateTimeFormatter; | ||
| import java.util.ArrayList; | ||
| import java.util.Arrays; | ||
| import java.util.Comparator; | ||
| import java.util.List; | ||
| import java.util.logging.Level; | ||
| import java.util.logging.Logger; | ||
| import javax.xml.parsers.DocumentBuilder; | ||
| import javax.xml.parsers.DocumentBuilderFactory; | ||
| import jenkins.model.Jenkins; | ||
| import org.kohsuke.stapler.StaplerRequest2; | ||
| import org.kohsuke.stapler.StaplerResponse2; | ||
| import org.springframework.lang.NonNull; | ||
| import org.w3c.dom.Document; | ||
|
|
||
| @Extension | ||
| public class CasCHistoryAction extends ManagementLink { | ||
|
|
||
| private static final Logger LOGGER = Logger.getLogger(CasCHistoryAction.class.getName()); | ||
|
|
||
| @Override | ||
| public String getIconFileName() { | ||
| return "symbol-time"; | ||
| } | ||
|
|
||
| @Override | ||
| public String getDisplayName() { | ||
| return "CasC History"; | ||
| } | ||
|
|
||
| @Override | ||
| public String getUrlName() { | ||
| return "casc-history"; | ||
| } | ||
|
|
||
| @Override | ||
| public String getDescription() { | ||
| return "Browse CasC history and snapshots."; | ||
| } | ||
|
|
||
| public List<HistoryEntry> getHistoryEntries() { | ||
| List<HistoryEntry> entries = new ArrayList<>(); | ||
| File baseDir = new File(Jenkins.get().getRootDir(), "casc-history"); | ||
|
|
||
| if (baseDir.exists() && baseDir.isDirectory()) { | ||
| File[] historyFolders = baseDir.listFiles(File::isDirectory); | ||
| if (historyFolders != null) { | ||
| Arrays.sort(historyFolders, Comparator.comparing(File::getName).reversed()); | ||
|
|
||
| for (File folder : historyFolders) { | ||
| entries.add(new HistoryEntry(folder.getName(), parseUserFromXml(folder))); | ||
| } | ||
| } | ||
| } | ||
| return entries; | ||
| } | ||
|
|
||
| private String parseUserFromXml(File folder) { | ||
| File xmlFile = new File(folder, "history.xml"); | ||
| if (xmlFile.exists()) { | ||
| try { | ||
| DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); | ||
| factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); | ||
| DocumentBuilder builder = factory.newDocumentBuilder(); | ||
| Document doc = builder.parse(xmlFile); | ||
|
|
||
| return doc.getElementsByTagName("user").item(0).getTextContent(); | ||
| } catch (Exception e) { | ||
| LOGGER.log(Level.WARNING, "Failed to read history.xml in " + folder.getName(), e); | ||
| } | ||
| } | ||
| return "Unknown User"; | ||
| } | ||
|
|
||
| public record HistoryEntry(String timestamp, String user) { | ||
|
|
||
| @SuppressWarnings("unused") | ||
| public String getFormattedTimestamp() { | ||
| LocalDateTime dt = LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss")); | ||
|
|
||
| return dt.format(DateTimeFormatter.ofPattern("dd MMM yyyy, HH:mm:ss")); | ||
| } | ||
| } | ||
|
|
||
| @SuppressWarnings("unused") | ||
| public void doView(StaplerRequest2 req, StaplerResponse2 res) throws IOException { | ||
Check warningCode scanning / Jenkins Security Scan Stapler: Missing POST/RequirePOST annotation Warning
Potential CSRF vulnerability: If CasCHistoryAction#doView connects to user-specified URLs, modifies state, or is expensive to run, it should be annotated with @POST or @RequirePOST
|
||
| Jenkins.get().checkPermission(Jenkins.ADMINISTER); | ||
|
|
||
| String timestamp = req.getParameter("timestamp"); | ||
| if (timestamp == null || timestamp.isEmpty()) { | ||
| res.sendError(400, "Missing timestamp parameter"); | ||
| return; | ||
| } | ||
|
|
||
| if (!timestamp.matches("^[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}-[0-9]{2}-[0-9]{2}(_[0-9]+)?$")) { | ||
| res.sendError(400, "Invalid timestamp format"); | ||
| return; | ||
| } | ||
|
|
||
| File baseDir = new File(Jenkins.get().getRootDir(), "casc-history"); | ||
| File historyDir = new File(baseDir, timestamp); | ||
| File yamlFile = new File(historyDir, "jenkins.yaml"); | ||
|
|
||
| if (!yamlFile.exists()) { | ||
| res.sendError(404, "History record not found"); | ||
| return; | ||
| } | ||
|
|
||
| res.setContentType("text/plain;charset=UTF-8"); | ||
| Files.copy(yamlFile.toPath(), res.getOutputStream()); | ||
| } | ||
|
|
||
| @Override | ||
| @NonNull | ||
| public Category getCategory() { | ||
| return Category.CONFIGURATION; | ||
| } | ||
| } | ||
9 changes: 9 additions & 0 deletions
9
plugin/src/main/java/io/jenkins/plugins/casc/history/CasCHistoryBackend.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| package io.jenkins.plugins.casc.history; | ||
|
|
||
| import hudson.ExtensionPoint; | ||
| import java.io.IOException; | ||
|
|
||
| public abstract class CasCHistoryBackend implements ExtensionPoint { | ||
|
|
||
| public abstract void save(String yamlContent, String triggeredBy) throws IOException; | ||
| } |
42 changes: 42 additions & 0 deletions
42
plugin/src/main/java/io/jenkins/plugins/casc/history/CasCHistoryRecorder.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| package io.jenkins.plugins.casc.history; | ||
|
|
||
| import hudson.Extension; | ||
| import hudson.ExtensionList; | ||
| import io.jenkins.plugins.casc.CasCReloadListener; | ||
| import io.jenkins.plugins.casc.ConfigurationAsCode; | ||
| import java.io.ByteArrayOutputStream; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.logging.Level; | ||
| import java.util.logging.Logger; | ||
| import jenkins.model.Jenkins; | ||
| import jenkins.util.Timer; | ||
| import org.springframework.security.core.Authentication; | ||
|
|
||
| @Extension | ||
| @SuppressWarnings("unused") | ||
| public class CasCHistoryRecorder implements CasCReloadListener { | ||
|
|
||
| private static final Logger LOGGER = Logger.getLogger(CasCHistoryRecorder.class.getName()); | ||
|
|
||
| @Override | ||
| public void onConfigurationReloaded() { | ||
| LOGGER.fine("CasC reload detected. Queuing async capture of current YAML state..."); | ||
|
|
||
| final Authentication auth = Jenkins.getAuthentication2(); | ||
| final String triggeredBy = auth.getName(); | ||
|
|
||
| Timer.get().submit(() -> { | ||
| try { | ||
| ByteArrayOutputStream out = new ByteArrayOutputStream(); | ||
| ConfigurationAsCode.get().export(out); | ||
| String currentYaml = out.toString(StandardCharsets.UTF_8); | ||
|
|
||
| CasCHistoryBackend backend = ExtensionList.lookupFirst(CasCHistoryBackend.class); | ||
| backend.save(currentYaml, triggeredBy); | ||
|
|
||
| } catch (Exception e) { | ||
| LOGGER.log(Level.WARNING, "Failed to capture CasC history asynchronously", e); | ||
| } | ||
| }); | ||
| } | ||
| } |
93 changes: 93 additions & 0 deletions
93
plugin/src/main/java/io/jenkins/plugins/casc/history/LocalFileHistoryBackend.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| package io.jenkins.plugins.casc.history; | ||
|
|
||
| import static org.apache.commons.lang.StringEscapeUtils.escapeXml; | ||
|
|
||
| import hudson.Extension; | ||
| import hudson.Util; | ||
| import java.io.File; | ||
| import java.io.IOException; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
| import java.text.SimpleDateFormat; | ||
| import java.util.Arrays; | ||
| import java.util.Comparator; | ||
| import java.util.Date; | ||
| import java.util.logging.Level; | ||
| import java.util.logging.Logger; | ||
| import jenkins.model.Jenkins; | ||
|
|
||
| @Extension | ||
| public class LocalFileHistoryBackend extends CasCHistoryBackend { | ||
| private static final Logger LOGGER = Logger.getLogger(LocalFileHistoryBackend.class.getName()); | ||
| private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd_HH-mm-ss"; | ||
| private static final int MAX_HISTORY_ENTRIES = 50; | ||
| private final Object writeLock = new Object(); | ||
|
|
||
| @Override | ||
| public void save(String yamlContent, String triggeredBy) throws IOException { | ||
| File jenkinsHome = Jenkins.get().getRootDir(); | ||
| File baseHistoryDir = new File(jenkinsHome, "casc-history"); | ||
|
|
||
| synchronized (writeLock) { | ||
| if (!baseHistoryDir.mkdirs() && !baseHistoryDir.exists()) { | ||
| throw new IOException("Failed to create base history directory: " + baseHistoryDir.getAbsolutePath()); | ||
| } | ||
|
|
||
| String timestamp = getCurrentTimestamp(); | ||
| File specificHistoryDir = new File(baseHistoryDir, timestamp); | ||
|
|
||
| int counter = 1; | ||
| while (specificHistoryDir.exists()) { | ||
| specificHistoryDir = new File(baseHistoryDir, timestamp + "_" + counter); | ||
| counter++; | ||
| } | ||
|
|
||
| if (!specificHistoryDir.mkdirs()) { | ||
| throw new IOException( | ||
| "Failed to create specific history directory: " + specificHistoryDir.getAbsolutePath()); | ||
| } | ||
|
|
||
| Path yamlFile = new File(specificHistoryDir, "jenkins.yaml").toPath(); | ||
| Files.writeString(yamlFile, yamlContent); | ||
|
|
||
| String xmlMetadata = String.format( | ||
| "<?xml version='1.1' encoding='UTF-8'?>%n" + "<history>%n" | ||
| + " <user>%s</user>%n" | ||
| + " <timestamp>%s</timestamp>%n" | ||
| + "</history>", | ||
| escapeXml(triggeredBy), timestamp); | ||
| Path metadataFile = new File(specificHistoryDir, "history.xml").toPath(); | ||
| Files.writeString(metadataFile, xmlMetadata); | ||
|
|
||
| LOGGER.info("CasC history successfully saved at: " + specificHistoryDir.getAbsolutePath()); | ||
|
|
||
| cleanupOldHistory(baseHistoryDir); | ||
| } | ||
| } | ||
|
|
||
| private void cleanupOldHistory(File baseHistoryDir) { | ||
| File[] historyFolders = baseHistoryDir.listFiles(File::isDirectory); | ||
|
|
||
| if (historyFolders != null && historyFolders.length > MAX_HISTORY_ENTRIES) { | ||
| Arrays.sort(historyFolders, Comparator.comparing(File::getName)); | ||
| int directoriesToDelete = historyFolders.length - MAX_HISTORY_ENTRIES; | ||
|
|
||
| for (int i = 0; i < directoriesToDelete; i++) { | ||
| File folderToDelete = historyFolders[i]; | ||
| LOGGER.fine("Deleting old CasC history entry: " + folderToDelete.getName()); | ||
| try { | ||
| Util.deleteRecursive(folderToDelete); | ||
| } catch (IOException e) { | ||
| LOGGER.log( | ||
| Level.WARNING, | ||
| "Failed to delete old CasC history folder: " + folderToDelete.getAbsolutePath(), | ||
| e); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| String getCurrentTimestamp() { | ||
| return new SimpleDateFormat(TIMESTAMP_FORMAT).format(new Date()); | ||
| } | ||
| } |
39 changes: 39 additions & 0 deletions
39
plugin/src/main/resources/io/jenkins/plugins/casc/history/CasCHistoryAction/index.jelly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| <?jelly escape-by-default='true'?> | ||
| <j:jelly xmlns:j="jelly:core" xmlns:l="/lib/layout"> | ||
| <l:layout title="CasC Configuration History" permission="${app.ADMINISTER}"> | ||
|
|
||
| <l:main-panel> | ||
| <h1>CasC Configuration History</h1> | ||
| <p> Browse the history of CasC changes and view the resulting configuration snapshots</p> | ||
|
|
||
| <table class="jenkins-table sortable"> | ||
| <thead> | ||
| <tr> | ||
| <th class="jenkins-table__cell--tight">Timestamp</th> | ||
| <th>User</th> | ||
| <th>Actions</th> | ||
| </tr> | ||
| </thead> | ||
| <tbody> | ||
| <j:forEach var="entry" items="${it.historyEntries}"> | ||
| <tr> | ||
| <td>${entry.formattedTimestamp}</td> | ||
| <td>${entry.user()}</td> | ||
| <td> | ||
| <a href="view?timestamp=${entry.timestamp()}" | ||
| class="jenkins-button jenkins-button--tertiary"> | ||
| View YAML | ||
| </a> | ||
| </td> | ||
| </tr> | ||
| </j:forEach> | ||
| </tbody> | ||
| </table> | ||
|
|
||
| <j:if test="${empty(it.historyEntries)}"> | ||
| <p class="jenkins-!-margin-top-3">No history found. Try reloading your configuration first!</p> | ||
| </j:if> | ||
|
|
||
| </l:main-panel> | ||
| </l:layout> | ||
| </j:jelly> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.