Save the last replication error to a project's JSON

Whenever a replication error is detected through Gerrit stream events
it is saved under the plugin’s data directory with the full JSON
of the failed replication event on the associated ref.
Multiple errors on different refs will be stored onto different
JSON files on different refs directories.

When replication resumes and a new successful replication event
for that ref will be received, the JSON gets removed.

This simple JSON file can be used for reporting problems directly
to the project owner via e-mail or crontab or a dedicated GUI.

Change-Id: Ie9eeea82de669134bdfe71e409a8c90f2d3d89d3
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GuiceModule.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GuiceModule.java
index 2b37e5e..6eed4ea 100644
--- a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GuiceModule.java
+++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/GuiceModule.java
@@ -14,13 +14,14 @@
 
 package com.googlesource.gerrit.plugins.github;
 
+import com.google.gerrit.common.EventListener;
 import com.google.gerrit.extensions.registration.DynamicSet;
 import com.google.gerrit.extensions.webui.TopMenu;
 import com.google.gerrit.server.account.GroupBackend;
 import com.google.inject.AbstractModule;
+import com.google.inject.Scopes;
 import com.google.inject.TypeLiteral;
 import com.google.inject.assistedinject.FactoryModuleBuilder;
-
 import com.googlesource.gerrit.plugins.github.group.GitHubGroupBackend;
 import com.googlesource.gerrit.plugins.github.group.GitHubGroupMembership;
 import com.googlesource.gerrit.plugins.github.group.GitHubGroupsCache;
@@ -28,6 +29,9 @@
 import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin;
 import com.googlesource.gerrit.plugins.github.oauth.IdentifiedUserGitHubLoginProvider;
 import com.googlesource.gerrit.plugins.github.oauth.UserScopedProvider;
+import com.googlesource.gerrit.plugins.github.replication.ReplicationErrorListener;
+import com.googlesource.gerrit.plugins.github.replication.ReplicationStatusFlatFile;
+import com.googlesource.gerrit.plugins.github.replication.ReplicationStatusStore;
 
 public class GuiceModule extends AbstractModule {
   @Override
@@ -39,10 +43,15 @@
 
     DynamicSet.bind(binder(), TopMenu.class).to(GitHubTopMenu.class);
     DynamicSet.bind(binder(), GroupBackend.class).to(GitHubGroupBackend.class);
+    DynamicSet.bind(binder(), EventListener.class).to(ReplicationErrorListener.class);
+
 
     install(new FactoryModuleBuilder()
         .build(GitHubOrganisationGroup.Factory.class));
     install(new FactoryModuleBuilder()
         .build(GitHubGroupMembership.Factory.class));
+
+    bind(ReplicationStatusStore.class).to(ReplicationStatusFlatFile.class)
+        .in(Scopes.SINGLETON);
   }
 }
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationErrorListener.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationErrorListener.java
new file mode 100644
index 0000000..3eea388
--- /dev/null
+++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationErrorListener.java
@@ -0,0 +1,69 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.googlesource.gerrit.plugins.github.replication;
+
+import java.io.IOException;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.gerrit.common.EventListener;
+import com.google.gerrit.reviewdb.client.Project.NameKey;
+import com.google.gerrit.server.OutputFormat;
+import com.google.gerrit.server.events.Event;
+import com.google.gerrit.server.events.RefEvent;
+import com.google.gson.Gson;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+
+@Singleton
+public class ReplicationErrorListener implements EventListener {
+  private static final String REF_REPLICATED_EVENT = "ref-replicated";
+  private static Logger log = LoggerFactory
+      .getLogger(ReplicationErrorListener.class);
+
+  private final ReplicationStatusStore statusStore;
+  private final Gson gson;
+
+  @Inject
+  public ReplicationErrorListener(ReplicationStatusStore statusStore) {
+    this.statusStore = statusStore;
+    this.gson = OutputFormat.JSON_COMPACT.newGson();
+  }
+
+  @Override
+  public void onEvent(Event event) {
+    if (RefEvent.class.isAssignableFrom(event.getClass())
+        && event.getType().equals(REF_REPLICATED_EVENT)) {
+      RefEvent refEvent = (RefEvent) event;
+      NameKey projectNameKey = refEvent.getProjectNameKey();
+      JsonObject eventJson = (JsonObject) gson.toJsonTree(event);
+      String projectKey =
+          projectNameKey.get() + "/" + eventJson.get("ref").getAsString();
+
+      try {
+        if (eventJson.get("status").getAsString().equals("succeeded")) {
+          statusStore.remove(projectKey);
+        } else {
+          statusStore.set(projectKey, eventJson);
+        }
+      } catch (IOException e) {
+        log.error("Unable to update replication status for event " + eventJson
+            + " on project " + projectKey, e);
+      }
+    }
+  }
+}
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusFlatFile.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusFlatFile.java
new file mode 100644
index 0000000..ebba163
--- /dev/null
+++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusFlatFile.java
@@ -0,0 +1,58 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.googlesource.gerrit.plugins.github.replication;
+
+import static java.nio.file.StandardOpenOption.CREATE;
+import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
+import static java.nio.file.StandardOpenOption.WRITE;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import com.google.gerrit.extensions.annotations.PluginData;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+
+public class ReplicationStatusFlatFile implements ReplicationStatusStore {
+  private final Path pluginData;
+
+  @Inject
+  public ReplicationStatusFlatFile(@PluginData Path pluginData) {
+    this.pluginData = pluginData;
+  }
+
+  @Override
+  public void set(String key, JsonObject event) throws IOException {
+    Path replicationStatusPath = getReplicationStatusPath(key);
+    Files.write(replicationStatusPath, event.toString().getBytes(),
+        TRUNCATE_EXISTING, CREATE, WRITE);
+  }
+
+  @Override
+  public void remove(String key) throws IOException {
+      Path replicationStatusPath = getReplicationStatusPath(key);
+      if (Files.exists(replicationStatusPath)) {
+        Files.delete(replicationStatusPath);
+      }
+  }
+
+  private Path getReplicationStatusPath(String key) throws IOException {
+    String sanitizedKey = key.replace(".", "_").replace(" ","_");
+    Path projectPath = pluginData.resolve(sanitizedKey + ".replication-error.json");
+    Files.createDirectories(projectPath.getParent());
+    return projectPath;
+  }
+}
diff --git a/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusStore.java b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusStore.java
new file mode 100644
index 0000000..2eb8c24
--- /dev/null
+++ b/github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/replication/ReplicationStatusStore.java
@@ -0,0 +1,26 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.googlesource.gerrit.plugins.github.replication;
+
+import java.io.IOException;
+
+import com.google.gson.JsonObject;
+
+public interface ReplicationStatusStore {
+
+  public void set(String key, JsonObject event) throws IOException;
+
+  public void remove(String key) throws IOException;
+}