Skip to content

The Unified and Autonomous Development Platform

Use update hook instead of pre-receive hook so that failed branch update does not prevent other branches to be updated.

robin shine8594cc1f9d1c
diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/CoreServletConfigurator.java b/gitop.core/src/main/java/com/pmease/gitop/core/CoreServletConfigurator.java
index c5809c0068..79f5044a07 100644
--- a/gitop.core/src/main/java/com/pmease/gitop/core/CoreServletConfigurator.java
+++ b/gitop.core/src/main/java/com/pmease/gitop/core/CoreServletConfigurator.java
@@ -12,21 +12,21 @@ import org.eclipse.jetty.servlet.ServletHolder;
import com.pmease.commons.hibernate.HibernateFilter;
import com.pmease.commons.jetty.ServletConfigurator;
-import com.pmease.gitop.core.hookcallback.PostReceiveServlet;
-import com.pmease.gitop.core.hookcallback.PreReceiveServlet;
+import com.pmease.gitop.core.hookcallback.GitPostReceiveCallback;
+import com.pmease.gitop.core.hookcallback.GitUpdateCallback;
@Singleton
public class CoreServletConfigurator implements ServletConfigurator {
private final HibernateFilter hibernateFilter;
- private final PreReceiveServlet preReceiveServlet;
+ private final GitUpdateCallback preReceiveServlet;
- private final PostReceiveServlet postReceiveServlet;
+ private final GitPostReceiveCallback postReceiveServlet;
@Inject
public CoreServletConfigurator(HibernateFilter hibernateFilter,
- PreReceiveServlet preReceiveServlet, PostReceiveServlet postReceiveServlet) {
+ GitUpdateCallback preReceiveServlet, GitPostReceiveCallback postReceiveServlet) {
this.hibernateFilter = hibernateFilter;
this.preReceiveServlet = preReceiveServlet;
this.postReceiveServlet = postReceiveServlet;
@@ -38,10 +38,10 @@ public class CoreServletConfigurator implements ServletConfigurator {
context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
ServletHolder servletHolder = new ServletHolder(preReceiveServlet);
- context.addServlet(servletHolder, PreReceiveServlet.PATH + "/*");
+ context.addServlet(servletHolder, GitUpdateCallback.PATH + "/*");
servletHolder = new ServletHolder(postReceiveServlet);
- context.addServlet(servletHolder, PostReceiveServlet.PATH + "/*");
+ context.addServlet(servletHolder, GitPostReceiveCallback.PATH + "/*");
}
}
diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/CallbackServlet.java b/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/CallbackServlet.java
deleted file mode 100644
index 50bf840008..0000000000
--- a/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/CallbackServlet.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package com.pmease.gitop.core.hookcallback;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.util.List;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.shiro.SecurityUtils;
-
-import com.google.common.base.Preconditions;
-import com.pmease.commons.util.StringUtils;
-import com.pmease.gitop.core.manager.ProjectManager;
-import com.pmease.gitop.model.Project;
-import com.pmease.gitop.model.User;
-
-@SuppressWarnings("serial")
-public abstract class CallbackServlet extends HttpServlet {
-
- private final ProjectManager projectManager;
-
- public CallbackServlet(ProjectManager projectManager) {
- this.projectManager = projectManager;
- }
-
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String clientIp = request.getHeader("X-Forwarded-For");
- if (clientIp == null) clientIp = request.getRemoteAddr();
-
- if (!InetAddress.getByName(clientIp).isLoopbackAddress()) {
- response.sendError(HttpServletResponse.SC_FORBIDDEN,
- "Git hook callbacks can only be accessed from localhost.");
- return;
- }
-
- List<String> fields = StringUtils.splitAndTrim(request.getPathInfo(), "/");
- Preconditions.checkState(fields.size() == 2);
-
- Project project = projectManager.load(Long.valueOf(fields.get(0)));
-
- SecurityUtils.getSubject().runAs(User.asPrincipal(Long.valueOf(fields.get(1))));
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- IOUtils.copy(request.getInputStream(), baos);
-
- callback(project, new String(baos.toByteArray()), new Output(response.getOutputStream()));
- }
-
- protected abstract void callback(Project project, String callbackData, Output output);
-
-}
diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/GitPostReceiveCallback.java b/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/GitPostReceiveCallback.java
new file mode 100644
index 0000000000..f7194f9c73
--- /dev/null
+++ b/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/GitPostReceiveCallback.java
@@ -0,0 +1,123 @@
+package com.pmease.gitop.core.hookcallback;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.util.List;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.shiro.SecurityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.eventbus.EventBus;
+import com.pmease.commons.git.Commit;
+import com.pmease.commons.util.StringUtils;
+import com.pmease.gitop.core.event.BranchRefUpdateEvent;
+import com.pmease.gitop.core.manager.BranchManager;
+import com.pmease.gitop.core.manager.ProjectManager;
+import com.pmease.gitop.model.Branch;
+import com.pmease.gitop.model.Project;
+import com.pmease.gitop.model.User;
+
+@SuppressWarnings("serial")
+@Singleton
+public class GitPostReceiveCallback extends HttpServlet {
+
+ public static final String PATH = "/git-postreceive-callback";
+
+ private static final Logger logger = LoggerFactory.getLogger(GitPostReceiveCallback.class);
+
+ private final ProjectManager projectManager;
+
+ private final BranchManager branchManager;
+
+ private final EventBus eventBus;
+
+ @Inject
+ public GitPostReceiveCallback(ProjectManager projectManager, BranchManager branchManager, EventBus eventBus) {
+ this.projectManager = projectManager;
+ this.branchManager = branchManager;
+ this.eventBus = eventBus;
+ }
+
+ @Override
+ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ String clientIp = request.getHeader("X-Forwarded-For");
+ if (clientIp == null) clientIp = request.getRemoteAddr();
+
+ if (!InetAddress.getByName(clientIp).isLoopbackAddress()) {
+ response.sendError(HttpServletResponse.SC_FORBIDDEN,
+ "Git hook callbacks can only be accessed from localhost.");
+ return;
+ }
+
+ List<String> fields = StringUtils.splitAndTrim(request.getPathInfo(), "/");
+ Preconditions.checkState(fields.size() == 2);
+
+ Project project = projectManager.load(Long.valueOf(fields.get(0)));
+
+ SecurityUtils.getSubject().runAs(User.asPrincipal(Long.valueOf(fields.get(1))));
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ IOUtils.copy(request.getInputStream(), baos);
+
+ /*
+ * If multiple refs are updated, the hook stdin will put each ref update info into
+ * a separate line, however the line breaks is omitted when forward the hook stdin
+ * to curl via "@-", below logic is used to parse these info correctly even
+ * without line breaks.
+ */
+ String callbackData = new String(baos.toByteArray());
+ callbackData = StringUtils.reverse(StringUtils.remove(callbackData, '\n'));
+ fields = StringUtils.splitAndTrim(callbackData, " ");
+
+ int pos = 0;
+ while (true) {
+ String refName = StringUtils.reverse(fields.get(pos));
+ pos++;
+ String newCommitHash = StringUtils.reverse(fields.get(pos));
+ pos++;
+ String field = fields.get(pos);
+ String oldCommitHash = StringUtils.reverse(field.substring(0, 40));
+ onRefUpdated(project, refName, oldCommitHash, newCommitHash);
+
+ field = field.substring(40);
+ if (field.length() == 0)
+ break;
+ else
+ fields.set(pos, field);
+ }
+
+ }
+
+ private void onRefUpdated(Project project, String refName, String oldCommitHash, String newCommitHash) {
+ String branchName = Branch.getName(refName);
+ if (branchName != null) {
+ if (oldCommitHash.equals(Commit.ZERO_HASH)) {
+ Branch branch = new Branch();
+ branch.setProject(project);
+ branch.setName(branchName);
+ branchManager.save(branch);
+ } else if (newCommitHash.equals(Commit.ZERO_HASH)) {
+ Branch branch = branchManager.findBy(project, branchName);
+ Preconditions.checkNotNull(branch);
+ branchManager.delete(branch);
+ } else {
+ logger.info("Executing post-receive hook against branch {}...", branchName);
+
+ Branch branch = branchManager.findBy(project, branchName);
+ Preconditions.checkNotNull(branch);
+ eventBus.post(new BranchRefUpdateEvent(branch));
+ }
+ }
+ }
+}
diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/PreReceiveServlet.java b/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/GitUpdateCallback.java
similarity index 60%
rename from gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/PreReceiveServlet.java
rename to gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/GitUpdateCallback.java
index f20e378353..327e419cd5 100644
--- a/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/PreReceiveServlet.java
+++ b/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/GitUpdateCallback.java
@@ -1,11 +1,19 @@
package com.pmease.gitop.core.hookcallback;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -28,20 +36,21 @@ import com.pmease.gitop.model.permission.ObjectPermission;
@SuppressWarnings("serial")
@Singleton
-public class PreReceiveServlet extends CallbackServlet {
+public class GitUpdateCallback extends HttpServlet {
- private static final Logger logger = LoggerFactory.getLogger(PreReceiveServlet.class);
+ private static final Logger logger = LoggerFactory.getLogger(GitUpdateCallback.class);
- public static final String PATH = "/git-pre-receive";
+ public static final String PATH = "/git-update-callback";
+ private final ProjectManager projectManager;
+
private final BranchManager branchManager;
private final UserManager userManager;
@Inject
- public PreReceiveServlet(ProjectManager projectManager,
- BranchManager branchManager, UserManager userManager) {
- super(projectManager);
+ public GitUpdateCallback(ProjectManager projectManager, BranchManager branchManager, UserManager userManager) {
+ this.projectManager = projectManager;
this.branchManager = branchManager;
this.userManager = userManager;
}
@@ -59,17 +68,39 @@ public class PreReceiveServlet extends CallbackServlet {
}
@Override
- protected void callback(Project project, String callbackData, Output output) {
- List<String> splitted = StringUtils.splitAndTrim(callbackData, " ");
- String refName = splitted.get(2);
+ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ String clientIp = request.getHeader("X-Forwarded-For");
+ if (clientIp == null) clientIp = request.getRemoteAddr();
+
+ if (!InetAddress.getByName(clientIp).isLoopbackAddress()) {
+ response.sendError(HttpServletResponse.SC_FORBIDDEN,
+ "Git hook callbacks can only be accessed from localhost.");
+ return;
+ }
+
+ List<String> fields = StringUtils.splitAndTrim(request.getPathInfo(), "/");
+ Preconditions.checkState(fields.size() == 2);
+
+ Project project = projectManager.load(Long.valueOf(fields.get(0)));
+
+ SecurityUtils.getSubject().runAs(User.asPrincipal(Long.valueOf(fields.get(1))));
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ IOUtils.copy(request.getInputStream(), baos);
+
+ Output output = new Output(response.getOutputStream());
+
+ fields = StringUtils.splitAndTrim(new String(baos.toByteArray()), " ");
+ String refName = fields.get(0);
+ String oldCommitHash = fields.get(1);
+ String newCommitHash = fields.get(2);
+
if (refName.startsWith(Project.REFS_GITOP)) {
if (!SecurityUtils.getSubject().isPermitted(ObjectPermission.ofProjectAdmin(project)))
error(output, "Only project administrators can update gitop refs.");
} else {
String branchName = Branch.getName(refName);
if (branchName != null) {
- String oldCommitHash = splitted.get(0);
-
if (!oldCommitHash.equals(Commit.ZERO_HASH)) {
Branch branch = branchManager.findBy(project, branchName);
Preconditions.checkNotNull(branch);
@@ -79,8 +110,6 @@ public class PreReceiveServlet extends CallbackServlet {
User user = userManager.getCurrent();
Preconditions.checkNotNull(user);
- String newCommitHash = splitted.get(1);
-
GateKeeper gateKeeper = project.getCompositeGateKeeper();
CheckResult checkResult = gateKeeper.checkCommit(user, branch, newCommitHash);
@@ -95,23 +124,23 @@ public class PreReceiveServlet extends CallbackServlet {
}
error(output, messages.toArray(new String[messages.size()]));
} else {
- for (PullRequest request: branch.getIngoingRequests()) {
- if (request.isOpen()) {
+ for (PullRequest each: branch.getIngoingRequests()) {
+ if (each.isOpen()) {
error(output, "There are unclosed pull requests targeting this branch.",
"Please close them before continue.");
return;
}
}
- for (PullRequest request: branch.getOutgoingRequests()) {
- if (request.isOpen()) {
+ for (PullRequest each: branch.getOutgoingRequests()) {
+ if (each.isOpen()) {
error(output, "There are unclosed pull requests originating from this branch.",
"Please close them before continue.");
- return;
+ break;
}
}
}
}
}
}
- }
+ }
}
diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/PostReceiveServlet.java b/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/PostReceiveServlet.java
deleted file mode 100644
index 3b32a76c41..0000000000
--- a/gitop.core/src/main/java/com/pmease/gitop/core/hookcallback/PostReceiveServlet.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package com.pmease.gitop.core.hookcallback;
-
-import java.util.List;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-import com.google.common.eventbus.EventBus;
-import com.pmease.commons.git.Commit;
-import com.pmease.commons.util.StringUtils;
-import com.pmease.gitop.core.event.BranchRefUpdateEvent;
-import com.pmease.gitop.core.manager.BranchManager;
-import com.pmease.gitop.core.manager.ProjectManager;
-import com.pmease.gitop.model.Branch;
-import com.pmease.gitop.model.Project;
-
-@SuppressWarnings("serial")
-@Singleton
-public class PostReceiveServlet extends CallbackServlet {
-
- public static final String PATH = "/git-post-receive";
-
- private static final Logger logger = LoggerFactory.getLogger(PostReceiveServlet.class);
-
- private final BranchManager branchManager;
-
- private final EventBus eventBus;
-
- @Inject
- public PostReceiveServlet(ProjectManager projectManager, BranchManager branchManager, EventBus eventBus) {
- super(projectManager);
-
- this.branchManager = branchManager;
- this.eventBus = eventBus;
- }
-
- @Override
- protected void callback(Project project, String callbackData, Output output) {
- List<String> splitted = StringUtils.splitAndTrim(callbackData, " ");
-
- String branchName = Branch.getName(splitted.get(2));
- if (branchName != null) {
- String oldCommitHash = splitted.get(0);
- String newCommitHash = splitted.get(1);
-
- if (oldCommitHash.equals(Commit.ZERO_HASH)) {
- Branch branch = new Branch();
- branch.setProject(project);
- branch.setName(branchName);
- branchManager.save(branch);
- } else if (newCommitHash.equals(Commit.ZERO_HASH)) {
- Branch branch = branchManager.findBy(project, branchName);
- Preconditions.checkNotNull(branch);
- branchManager.delete(branch);
- } else {
- logger.info("Executing post-receive hook against branch {}...", branchName);
-
- Branch branch = branchManager.findBy(project, branchName);
- Preconditions.checkNotNull(branch);
- eventBus.post(new BranchRefUpdateEvent(branch));
- }
- }
- }
-}
diff --git a/gitop.core/src/main/java/com/pmease/gitop/core/manager/impl/DefaultProjectManager.java b/gitop.core/src/main/java/com/pmease/gitop/core/manager/impl/DefaultProjectManager.java
index 8b806e4b13..f4e8611144 100644
--- a/gitop.core/src/main/java/com/pmease/gitop/core/manager/impl/DefaultProjectManager.java
+++ b/gitop.core/src/main/java/com/pmease/gitop/core/manager/impl/DefaultProjectManager.java
@@ -21,8 +21,8 @@ import com.pmease.commons.hibernate.dao.AbstractGenericDao;
import com.pmease.commons.hibernate.dao.GeneralDao;
import com.pmease.commons.util.FileUtils;
import com.pmease.commons.util.StringUtils;
-import com.pmease.gitop.core.hookcallback.PostReceiveServlet;
-import com.pmease.gitop.core.hookcallback.PreReceiveServlet;
+import com.pmease.gitop.core.hookcallback.GitPostReceiveCallback;
+import com.pmease.gitop.core.hookcallback.GitUpdateCallback;
import com.pmease.gitop.core.manager.BranchManager;
import com.pmease.gitop.core.manager.ProjectManager;
import com.pmease.gitop.core.setting.ServerConfig;
@@ -42,7 +42,9 @@ public class DefaultProjectManager extends AbstractGenericDao<Project> implement
private final ServerConfig serverConfig;
- private final String hookTemplate;
+ private final String gitUpdateHookTemplate;
+
+ private final String gitPostReceiveHookTemplate;
@Inject
public DefaultProjectManager(GeneralDao generalDao, StorageManager storageManager,
@@ -53,9 +55,16 @@ public class DefaultProjectManager extends AbstractGenericDao<Project> implement
this.branchManager = branchManager;
this.serverConfig = serverConfig;
- try (InputStream is = getClass().getClassLoader().getResourceAsStream("git-hook-template")) {
+ try (InputStream is = getClass().getClassLoader().getResourceAsStream("git-update-hook-template")) {
+ Preconditions.checkNotNull(is);
+ gitUpdateHookTemplate = StringUtils.join(IOUtils.readLines(is), "\n");
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ try (InputStream is = getClass().getClassLoader().getResourceAsStream("git-postreceive-hook-template")) {
Preconditions.checkNotNull(is);
- hookTemplate = StringUtils.join(IOUtils.readLines(is), "\n");
+ gitPostReceiveHookTemplate = StringUtils.join(IOUtils.readLines(is), "\n");
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -85,15 +94,15 @@ public class DefaultProjectManager extends AbstractGenericDao<Project> implement
else
urlRoot = "https://localhost:" + serverConfig.getSslConfig().getPort();
- File preReceiveHook = new File(hooksDir, "pre-receive");
- FileUtils.writeFile(preReceiveHook,
- String.format(hookTemplate, urlRoot + PreReceiveServlet.PATH + "/" + project.getId()));
- preReceiveHook.setExecutable(true);
+ File gitUpdateHook = new File(hooksDir, "update");
+ FileUtils.writeFile(gitUpdateHook,
+ String.format(gitUpdateHookTemplate, urlRoot + GitUpdateCallback.PATH + "/" + project.getId()));
+ gitUpdateHook.setExecutable(true);
- File postReceiveHook = new File(hooksDir, "post-receive");
- FileUtils.writeFile(postReceiveHook,
- String.format(hookTemplate, urlRoot + PostReceiveServlet.PATH + "/" + project.getId()));
- postReceiveHook.setExecutable(true);
+ File gitPostReceiveHook = new File(hooksDir, "post-receive");
+ FileUtils.writeFile(gitPostReceiveHook,
+ String.format(gitPostReceiveHookTemplate, urlRoot + GitPostReceiveCallback.PATH + "/" + project.getId()));
+ gitPostReceiveHook.setExecutable(true);
}
branchManager.syncWithGit(project);
diff --git a/gitop.core/src/main/resources/git-hook-template b/gitop.core/src/main/resources/git-postreceive-hook-template
similarity index 100%
rename from gitop.core/src/main/resources/git-hook-template
rename to gitop.core/src/main/resources/git-postreceive-hook-template
diff --git a/gitop.core/src/main/resources/git-update-hook-template b/gitop.core/src/main/resources/git-update-hook-template
new file mode 100644
index 0000000000..61f3ed54b5
--- /dev/null
+++ b/gitop.core/src/main/resources/git-update-hook-template
@@ -0,0 +1,23 @@
+#!/bin/sh
+IFS=$'\r\n';
+lines=($(
+curl -s -S -f -X POST -d @- %s/${GITOP_USER_ID} 2>&1 <<EOF
+$1 $2 $3
+EOF
+))
+
+returnCode=0;
+
+for i in ${lines[@]}
+do
+ if [ "$i" = "ERROR" ]; then
+ returnCode=1
+ else
+ if [[ $i == curl:* ]]; then
+ returnCode=1
+ fi;
+ echo "$i"
+ fi;
+done
+
+exit $returnCode
\ No newline at end of file