summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorShawn O. Pearce <sop@google.com>2012-05-10 19:04:38 -0700
committerShawn O. Pearce <sop@google.com>2012-05-18 10:39:09 -0700
commitbf62ea82c47253fa748043f16e335e17d1b9686d (patch)
treecab5134372225f3d3ca072041e89188cc7ddb72d
Initial replication plugin, split from Gerrit Code Review
This plugin provides server driven replication within the Gerrit process using the JGit and JSch client libraries to push reference updates to remote destinations using the Git protocol. Taken from gerrit 5de34d9713108fb46e74c12b96db2e3e6be3c672. Change-Id: Id09595d4371e999d175268314d2e320f89839ef6
-rw-r--r--.gitignore5
-rw-r--r--.settings/org.eclipse.core.resources.prefs5
-rw-r--r--.settings/org.eclipse.core.runtime.prefs3
-rw-r--r--.settings/org.eclipse.jdt.core.prefs264
-rw-r--r--.settings/org.eclipse.jdt.ui.prefs61
-rw-r--r--LICENSE201
-rw-r--r--pom.xml92
-rw-r--r--src/main/java/com/googlesource/gerrit/plugins/replication/Destination.java364
-rw-r--r--src/main/java/com/googlesource/gerrit/plugins/replication/OnStartStop.java61
-rw-r--r--src/main/java/com/googlesource/gerrit/plugins/replication/PushAll.java75
-rw-r--r--src/main/java/com/googlesource/gerrit/plugins/replication/PushOne.java430
-rw-r--r--src/main/java/com/googlesource/gerrit/plugins/replication/RemoteSiteUser.java58
-rw-r--r--src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationModule.java46
-rw-r--r--src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java393
-rw-r--r--src/main/java/com/googlesource/gerrit/plugins/replication/SecureCredentialsFactory.java59
-rw-r--r--src/main/java/com/googlesource/gerrit/plugins/replication/SecureCredentialsProvider.java81
-rw-r--r--src/main/java/com/googlesource/gerrit/plugins/replication/SshModule.java24
-rw-r--r--src/main/java/com/googlesource/gerrit/plugins/replication/StartCommand.java72
-rw-r--r--src/main/resources/Documentation/cmd-start.md106
-rw-r--r--src/main/resources/Documentation/config.md268
-rw-r--r--src/test/java/com/googlesource/gerrit/plugins/replication/PushReplicationTest.java44
21 files changed, 2712 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..194bedc
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+/target
+/.classpath
+/.project
+/.settings/org.maven.ide.eclipse.prefs
+/.settings/org.eclipse.m2e.core.prefs \ No newline at end of file
diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs
new file mode 100644
index 0000000..f15f85d
--- /dev/null
+++ b/.settings/org.eclipse.core.resources.prefs
@@ -0,0 +1,5 @@
+#Tue May 15 09:19:33 PDT 2012
+eclipse.preferences.version=1
+encoding//src/main/java=UTF-8
+encoding//src/test/java=UTF-8
+encoding//src/test/resources=UTF-8
diff --git a/.settings/org.eclipse.core.runtime.prefs b/.settings/org.eclipse.core.runtime.prefs
new file mode 100644
index 0000000..8667cfd
--- /dev/null
+++ b/.settings/org.eclipse.core.runtime.prefs
@@ -0,0 +1,3 @@
+#Tue Sep 02 16:59:24 PDT 2008
+eclipse.preferences.version=1
+line.separator=\n
diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..2f45466
--- /dev/null
+++ b/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,264 @@
+#Fri Jul 16 23:39:13 PDT 2010
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
+org.eclipse.jdt.core.compiler.source=1.6
+org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_assignment=16
+org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_compact_if=16
+org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_enum_constants=16
+org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16
+org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16
+org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16
+org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16
+org.eclipse.jdt.core.formatter.blank_lines_after_imports=1
+org.eclipse.jdt.core.formatter.blank_lines_after_package=1
+org.eclipse.jdt.core.formatter.blank_lines_before_field=0
+org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0
+org.eclipse.jdt.core.formatter.blank_lines_before_imports=0
+org.eclipse.jdt.core.formatter.blank_lines_before_member_type=0
+org.eclipse.jdt.core.formatter.blank_lines_before_method=1
+org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1
+org.eclipse.jdt.core.formatter.blank_lines_before_package=0
+org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1
+org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=2
+org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line
+org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false
+org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false
+org.eclipse.jdt.core.formatter.comment.format_block_comments=true
+org.eclipse.jdt.core.formatter.comment.format_header=true
+org.eclipse.jdt.core.formatter.comment.format_html=true
+org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true
+org.eclipse.jdt.core.formatter.comment.format_line_comments=true
+org.eclipse.jdt.core.formatter.comment.format_source_code=true
+org.eclipse.jdt.core.formatter.comment.indent_parameter_description=false
+org.eclipse.jdt.core.formatter.comment.indent_root_tags=true
+org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert
+org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert
+org.eclipse.jdt.core.formatter.comment.line_length=80
+org.eclipse.jdt.core.formatter.compact_else_if=true
+org.eclipse.jdt.core.formatter.continuation_indentation=2
+org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2
+org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true
+org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true
+org.eclipse.jdt.core.formatter.indent_empty_lines=false
+org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true
+org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true
+org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true
+org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true
+org.eclipse.jdt.core.formatter.indentation.size=4
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert
+org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert
+org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert
+org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert
+org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert
+org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.join_lines_in_comments=true
+org.eclipse.jdt.core.formatter.join_wrapped_lines=true
+org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false
+org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false
+org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=true
+org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false
+org.eclipse.jdt.core.formatter.lineSplit=80
+org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false
+org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false
+org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
+org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=3
+org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false
+org.eclipse.jdt.core.formatter.tabulation.char=space
+org.eclipse.jdt.core.formatter.tabulation.size=2
+org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false
+org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true
diff --git a/.settings/org.eclipse.jdt.ui.prefs b/.settings/org.eclipse.jdt.ui.prefs
new file mode 100644
index 0000000..d4218a5
--- /dev/null
+++ b/.settings/org.eclipse.jdt.ui.prefs
@@ -0,0 +1,61 @@
+#Wed Jul 29 11:31:38 PDT 2009
+eclipse.preferences.version=1
+editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
+formatter_profile=_Google Format
+formatter_settings_version=11
+org.eclipse.jdt.ui.ignorelowercasenames=true
+org.eclipse.jdt.ui.importorder=com.google;com;junit;net;org;java;javax;
+org.eclipse.jdt.ui.ondemandthreshold=99
+org.eclipse.jdt.ui.staticondemandthreshold=99
+org.eclipse.jdt.ui.text.custom_code_templates=<?xml version\="1.0" encoding\="UTF-8" standalone\="no"?><templates/>
+sp_cleanup.add_default_serial_version_id=true
+sp_cleanup.add_generated_serial_version_id=false
+sp_cleanup.add_missing_annotations=false
+sp_cleanup.add_missing_deprecated_annotations=true
+sp_cleanup.add_missing_methods=false
+sp_cleanup.add_missing_nls_tags=false
+sp_cleanup.add_missing_override_annotations=true
+sp_cleanup.add_serial_version_id=false
+sp_cleanup.always_use_blocks=true
+sp_cleanup.always_use_parentheses_in_expressions=false
+sp_cleanup.always_use_this_for_non_static_field_access=false
+sp_cleanup.always_use_this_for_non_static_method_access=false
+sp_cleanup.convert_to_enhanced_for_loop=false
+sp_cleanup.correct_indentation=false
+sp_cleanup.format_source_code=false
+sp_cleanup.format_source_code_changes_only=false
+sp_cleanup.make_local_variable_final=true
+sp_cleanup.make_parameters_final=true
+sp_cleanup.make_private_fields_final=true
+sp_cleanup.make_type_abstract_if_missing_method=false
+sp_cleanup.make_variable_declarations_final=false
+sp_cleanup.never_use_blocks=false
+sp_cleanup.never_use_parentheses_in_expressions=true
+sp_cleanup.on_save_use_additional_actions=true
+sp_cleanup.organize_imports=false
+sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
+sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
+sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
+sp_cleanup.qualify_static_member_accesses_with_declaring_class=false
+sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
+sp_cleanup.remove_private_constructors=true
+sp_cleanup.remove_trailing_whitespaces=true
+sp_cleanup.remove_trailing_whitespaces_all=true
+sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
+sp_cleanup.remove_unnecessary_casts=false
+sp_cleanup.remove_unnecessary_nls_tags=false
+sp_cleanup.remove_unused_imports=false
+sp_cleanup.remove_unused_local_variables=false
+sp_cleanup.remove_unused_private_fields=true
+sp_cleanup.remove_unused_private_members=false
+sp_cleanup.remove_unused_private_methods=true
+sp_cleanup.remove_unused_private_types=true
+sp_cleanup.sort_members=false
+sp_cleanup.sort_members_all=false
+sp_cleanup.use_blocks=false
+sp_cleanup.use_blocks_only_for_return_and_throw=false
+sp_cleanup.use_parentheses_in_expressions=false
+sp_cleanup.use_this_for_non_static_field_access=false
+sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
+sp_cleanup.use_this_for_non_static_method_access=false
+sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..11069ed
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+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.
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 0000000..4c63315
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,92 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+Copyright (C) 2012 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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <groupId>com.googlesource.gerrit.plugins.replication</groupId>
+ <artifactId>replication</artifactId>
+ <packaging>jar</packaging>
+ <version>1.0-SNAPSHOT</version>
+
+ <properties>
+ <Gerrit-ApiType>plugin</Gerrit-ApiType>
+ <Gerrit-ApiVersion>2.4-rc0-244-gdbd1acb</Gerrit-ApiVersion>
+ </properties>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <version>2.4</version>
+ <configuration>
+ <archive>
+ <manifestEntries>
+ <Gerrit-Module>com.googlesource.gerrit.plugins.replication.ReplicationModule</Gerrit-Module>
+ <Gerrit-SshModule>com.googlesource.gerrit.plugins.replication.SshModule</Gerrit-SshModule>
+
+ <Implementation-Vendor>Gerrit Code Review</Implementation-Vendor>
+ <Implementation-URL>http://code.google.com/p/gerrit/</Implementation-URL>
+
+ <Implementation-Title>Plugin ${project.artifactId}</Implementation-Title>
+ <Implementation-Version>${project.version}</Implementation-Version>
+
+ <Gerrit-ApiType>${Gerrit-ApiType}</Gerrit-ApiType>
+ <Gerrit-ApiVersion>${Gerrit-ApiVersion}</Gerrit-ApiVersion>
+ </manifestEntries>
+ </archive>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>2.3.2</version>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ <encoding>UTF-8</encoding>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <dependencies>
+ <dependency>
+ <groupId>com.google.gerrit</groupId>
+ <artifactId>gerrit-${Gerrit-ApiType}-api</artifactId>
+ <version>${Gerrit-ApiVersion}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.8.1</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <repositories>
+ <repository>
+ <id>gerrit-api-repository</id>
+ <url>https://gerrit-api.commondatastorage.googleapis.com/snapshot/</url>
+ </repository>
+ </repositories>
+</project>
diff --git a/src/main/java/com/googlesource/gerrit/plugins/replication/Destination.java b/src/main/java/com/googlesource/gerrit/plugins/replication/Destination.java
new file mode 100644
index 0000000..e87b975
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/replication/Destination.java
@@ -0,0 +1,364 @@
+// Copyright (C) 2009 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.replication;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.gerrit.reviewdb.client.AccountGroup;
+import com.google.gerrit.reviewdb.client.Project;
+import com.google.gerrit.reviewdb.server.ReviewDb;
+import com.google.gerrit.server.CurrentUser;
+import com.google.gerrit.server.InternalUser;
+import com.google.gerrit.server.account.GroupCache;
+import com.google.gerrit.server.account.ListGroupMembership;
+import com.google.gerrit.server.config.FactoryModule;
+import com.google.gerrit.server.git.GitRepositoryManager;
+import com.google.gerrit.server.git.PerThreadRequestScope;
+import com.google.gerrit.server.git.WorkQueue;
+import com.google.gerrit.server.project.NoSuchProjectException;
+import com.google.gerrit.server.project.PerRequestProjectControlCache;
+import com.google.gerrit.server.project.ProjectControl;
+import com.google.gwtorm.server.SchemaFactory;
+import com.google.inject.AbstractModule;
+import com.google.inject.Injector;
+import com.google.inject.assistedinject.FactoryModuleBuilder;
+import com.google.inject.servlet.RequestScoped;
+
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.transport.RefSpec;
+import org.eclipse.jgit.transport.RemoteConfig;
+import org.eclipse.jgit.transport.URIish;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+class Destination {
+ private final int poolThreads;
+ private final String poolName;
+
+ private final RemoteConfig remote;
+ private final String[] adminUrls;
+ private final int delay;
+ private final int retryDelay;
+ private final Map<URIish, PushOne> pending = new HashMap<URIish, PushOne>();
+ private final PushOne.Factory opFactory;
+ private final ProjectControl.Factory projectControlFactory;
+ private final GitRepositoryManager gitManager;
+ private final boolean replicatePermissions;
+ private volatile WorkQueue.Executor pool;
+
+ Destination(final Injector injector,
+ final RemoteConfig rc,
+ final Config cfg,
+ final SchemaFactory<ReviewDb> db,
+ final RemoteSiteUser.Factory replicationUserFactory,
+ final InternalUser.Factory internalUserFactory,
+ final GitRepositoryManager gitRepositoryManager,
+ final GroupCache groupCache) {
+ remote = rc;
+ gitManager = gitRepositoryManager;
+ delay = Math.max(0, getInt(rc, cfg, "replicationdelay", 15));
+ retryDelay = Math.max(0, getInt(rc, cfg, "replicationretry", 1));
+ adminUrls = cfg.getStringList("remote", rc.getName(), "adminUrl");
+
+ poolThreads = Math.max(0, getInt(rc, cfg, "threads", 1));
+ poolName = "ReplicateTo-" + rc.getName();
+ replicatePermissions =
+ cfg.getBoolean("remote", rc.getName(), "replicatePermissions", true);
+
+ final CurrentUser remoteUser;
+ String[] authGroupNames = cfg.getStringList("remote", rc.getName(), "authGroup");
+ if (authGroupNames.length > 0) {
+ ImmutableSet.Builder<AccountGroup.UUID> builder = ImmutableSet.builder();
+ for (String name : authGroupNames) {
+ AccountGroup g = groupCache.get(new AccountGroup.NameKey(name));
+ if (g != null) {
+ builder.add(g.getGroupUUID());
+ } else {
+ ReplicationQueue.log.warn(String.format(
+ "Group \"%s\" not recognized, removing from authGroup", name));
+ }
+ }
+ remoteUser = replicationUserFactory.create(
+ new ListGroupMembership(builder.build()));
+ } else {
+ remoteUser = internalUserFactory.create();
+ }
+
+ projectControlFactory = injector.createChildInjector(new AbstractModule() {
+ @Override
+ protected void configure() {
+ bindScope(RequestScoped.class, PerThreadRequestScope.REQUEST);
+ bind(PerRequestProjectControlCache.class).in(RequestScoped.class);
+ bind(CurrentUser.class).toInstance(remoteUser);
+ }
+ }).getInstance(ProjectControl.Factory.class);
+
+ opFactory = injector.createChildInjector(new FactoryModule() {
+ @Override
+ protected void configure() {
+ bind(Destination.class).toInstance(Destination.this);
+ bind(RemoteConfig.class).toInstance(remote);
+ install(new FactoryModuleBuilder().build(PushOne.Factory.class));
+ }
+ }).getInstance(PushOne.Factory.class);
+ }
+
+ void start(WorkQueue workQueue) {
+ pool = workQueue.createQueue(poolThreads, poolName);
+ }
+
+ int shutdown() {
+ int cnt = 0;
+ if (pool != null) {
+ cnt = pool.shutdownNow().size();
+ pool.unregisterWorkQueue();
+ pool = null;
+ }
+ return cnt;
+ }
+
+ private static int getInt(
+ RemoteConfig rc, Config cfg, String name, int defValue) {
+ return cfg.getInt("remote", rc.getName(), name, defValue);
+ }
+
+ void schedule(Project.NameKey project, String ref, URIish uri) {
+ PerThreadRequestScope ctx = new PerThreadRequestScope();
+ PerThreadRequestScope old = PerThreadRequestScope.set(ctx);
+ try {
+ try {
+ if (!controlFor(project).isVisible()) {
+ return;
+ }
+ } catch (NoSuchProjectException err) {
+ ReplicationQueue.log.error(String.format(
+ "source project %s not available", project), err);
+ return;
+ }
+ } finally {
+ PerThreadRequestScope.set(old);
+ }
+
+ if (!replicatePermissions) {
+ PushOne e;
+ synchronized (pending) {
+ e = pending.get(uri);
+ }
+ if (e == null) {
+ Repository git;
+ try {
+ git = gitManager.openRepository(project);
+ } catch (IOException err) {
+ ReplicationQueue.log.error(String.format(
+ "source project %s not available", project), err);
+ return;
+ }
+ try {
+ Ref head = git.getRef(Constants.HEAD);
+ if (head != null
+ && head.isSymbolic()
+ && GitRepositoryManager.REF_CONFIG.equals(head.getLeaf().getName())) {
+ return;
+ }
+ } catch (IOException err) {
+ ReplicationQueue.log.error(String.format(
+ "cannot check type of project %s", project), err);
+ return;
+ } finally {
+ git.close();
+ }
+ }
+ }
+
+ synchronized (pending) {
+ PushOne e = pending.get(uri);
+ if (e == null) {
+ e = opFactory.create(project, uri);
+ pool.schedule(e, delay, TimeUnit.SECONDS);
+ pending.put(uri, e);
+ }
+ e.addRef(ref);
+ }
+ }
+
+ /**
+ * It schedules again a PushOp instance.
+ * <p>
+ * It is assumed to be previously scheduled and found a
+ * transport exception. It will schedule it as a push
+ * operation to be retried after the minutes count
+ * determined by class attribute retryDelay.
+ * <p>
+ * In case the PushOp instance to be scheduled has same
+ * URI than one also pending for retry, it adds to the one
+ * pending the refs list of the parameter instance.
+ * <p>
+ * In case the PushOp instance to be scheduled has same
+ * URI than one pending, but not pending for retry, it
+ * indicates the one pending should be canceled when it
+ * starts executing, removes it from pending list, and
+ * adds its refs to the parameter instance. The parameter
+ * instance is scheduled for retry.
+ * <p>
+ * Notice all operations to indicate a PushOp should be
+ * canceled, or it is retrying, or remove/add it from/to
+ * pending Map should be protected by the lock on pending
+ * Map class instance attribute.
+ *
+ * @param pushOp The PushOp instance to be scheduled.
+ */
+ void reschedule(PushOne pushOp) {
+ // It locks access to pending variable.
+ synchronized (pending) {
+ URIish uri = pushOp.getURI();
+ PushOne pendingPushOp = pending.get(uri);
+
+ if (pendingPushOp != null) {
+ // There is one PushOp instance already pending to same URI.
+
+ if (pendingPushOp.isRetrying()) {
+ // The one pending is one already retrying, so it should
+ // maintain it and add to it the refs of the one passed
+ // as parameter to the method.
+
+ // This scenario would happen if a PushOp has started running
+ // and then before it failed due transport exception, another
+ // one to same URI started. The first one would fail and would
+ // be rescheduled, being present in pending list. When the
+ // second one fails, it will also be rescheduled and then,
+ // here, find out replication to its URI is already pending
+ // for retry (blocking).
+ pendingPushOp.addRefs(pushOp.getRefs());
+
+ } else {
+ // The one pending is one that is NOT retrying, it was just
+ // scheduled believing no problem would happen. The one pending
+ // should be canceled, and this is done by setting its canceled
+ // flag, removing it from pending list, and adding its refs to
+ // the pushOp instance that should then, later, in this method,
+ // be scheduled for retry.
+
+ // Notice that the PushOp found pending will start running and,
+ // when notifying it is starting (with pending lock protection),
+ // it will see it was canceled and then it will do nothing with
+ // pending list and it will not execute its run implementation.
+
+ pendingPushOp.cancel();
+ pending.remove(uri);
+
+ pushOp.addRefs(pendingPushOp.getRefs());
+ }
+ }
+
+ if (pendingPushOp == null || !pendingPushOp.isRetrying()) {
+ // The PushOp method param instance should be scheduled for retry.
+ // Remember when retrying it should be used different delay.
+
+ pushOp.setToRetry();
+
+ pending.put(uri, pushOp);
+ pool.schedule(pushOp, retryDelay, TimeUnit.MINUTES);
+ }
+ }
+ }
+
+ ProjectControl controlFor(Project.NameKey project)
+ throws NoSuchProjectException {
+ return projectControlFactory.controlFor(project);
+ }
+
+ void notifyStarting(PushOne op) {
+ synchronized (pending) {
+ if (!op.wasCanceled()) {
+ pending.remove(op.getURI());
+ }
+ }
+ }
+
+ boolean wouldPushRef(String ref) {
+ if (!replicatePermissions && GitRepositoryManager.REF_CONFIG.equals(ref)) {
+ return false;
+ }
+ for (RefSpec s : remote.getPushRefSpecs()) {
+ if (s.matchSource(ref)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ boolean isReplicatePermissions() {
+ return replicatePermissions;
+ }
+
+ List<URIish> getURIs(Project.NameKey project, String urlMatch) {
+ List<URIish> r = Lists.newArrayListWithCapacity(remote.getURIs().size());
+ for (URIish uri : remote.getURIs()) {
+ if (matches(uri, urlMatch)) {
+ String name = project.get();
+ if (needsUrlEncoding(uri)) {
+ name = encode(name);
+ }
+ String replacedPath = ReplicationQueue.replaceName(uri.getPath(), name);
+ if (replacedPath != null) {
+ uri = uri.setPath(replacedPath);
+ r.add(uri);
+ }
+ }
+ }
+ return r;
+ }
+
+ static boolean needsUrlEncoding(URIish uri) {
+ return "http".equalsIgnoreCase(uri.getScheme())
+ || "https".equalsIgnoreCase(uri.getScheme())
+ || "amazon-s3".equalsIgnoreCase(uri.getScheme());
+ }
+
+ static String encode(String str) {
+ try {
+ // Some cleanup is required. The '/' character is always encoded as %2F
+ // however remote servers will expect it to be not encoded as part of the
+ // path used to the repository. Space is incorrectly encoded as '+' for this
+ // context. In the path part of a URI space should be %20, but in form data
+ // space is '+'. Our cleanup replace fixes these two issues.
+ return URLEncoder.encode(str, "UTF-8")
+ .replaceAll("%2[fF]", "/")
+ .replace("+", "%20");
+ } catch (UnsupportedEncodingException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ String[] getAdminUrls() {
+ return adminUrls;
+ }
+
+ private static boolean matches(URIish uri, String urlMatch) {
+ if (urlMatch == null || urlMatch.equals("") || urlMatch.equals("*")) {
+ return true;
+ }
+ return uri.toString().contains(urlMatch);
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/replication/OnStartStop.java b/src/main/java/com/googlesource/gerrit/plugins/replication/OnStartStop.java
new file mode 100644
index 0000000..90d4644
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/replication/OnStartStop.java
@@ -0,0 +1,61 @@
+// Copyright (C) 2012 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.replication;
+
+import com.google.common.util.concurrent.Atomics;
+import com.google.gerrit.extensions.events.LifecycleListener;
+import com.google.gerrit.extensions.systemstatus.ServerInformation;
+import com.google.inject.Inject;
+
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+class OnStartStop implements LifecycleListener {
+ private final AtomicReference<Future<?>> pushAllFuture;
+ private final ServerInformation srvInfo;
+ private final PushAll.Factory pushAll;
+ private final ReplicationQueue queue;
+
+ @Inject
+ OnStartStop(
+ ServerInformation srvInfo,
+ PushAll.Factory pushAll,
+ ReplicationQueue queue) {
+ this.srvInfo = srvInfo;
+ this.pushAll = pushAll;
+ this.queue = queue;
+ this.pushAllFuture = Atomics.newReference();
+ }
+
+ @Override
+ public void start() {
+ queue.start();
+
+ if (srvInfo.getState() == ServerInformation.State.STARTUP
+ && queue.replicateAllOnPluginStart) {
+ pushAllFuture.set(pushAll.create(null).schedule(30, TimeUnit.SECONDS));
+ }
+ }
+
+ @Override
+ public void stop() {
+ Future<?> f = pushAllFuture.getAndSet(null);
+ if (f != null) {
+ f.cancel(true);
+ }
+ queue.stop();
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/replication/PushAll.java b/src/main/java/com/googlesource/gerrit/plugins/replication/PushAll.java
new file mode 100644
index 0000000..6d99536
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/replication/PushAll.java
@@ -0,0 +1,75 @@
+// Copyright (C) 2009 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.replication;
+
+import com.google.gerrit.reviewdb.client.Project;
+import com.google.gerrit.server.git.WorkQueue;
+import com.google.gerrit.server.project.ProjectCache;
+import com.google.inject.Inject;
+import com.google.inject.assistedinject.Assisted;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import javax.annotation.Nullable;
+
+class PushAll implements Runnable {
+ private static final Logger log = LoggerFactory.getLogger(PushAll.class);
+
+ interface Factory {
+ PushAll create(String urlMatch);
+ }
+
+ private final WorkQueue workQueue;
+ private final ProjectCache projectCache;
+ private final ReplicationQueue replication;
+ private final String urlMatch;
+
+ @Inject
+ PushAll(WorkQueue wq, ProjectCache projectCache, ReplicationQueue rq,
+ @Assisted @Nullable String urlMatch) {
+ this.workQueue = wq;
+ this.projectCache = projectCache;
+ this.replication = rq;
+ this.urlMatch = urlMatch;
+ }
+
+ Future<?> schedule(long delay, TimeUnit unit) {
+ return workQueue.getDefaultQueue().schedule(this, delay, unit);
+ }
+
+ @Override
+ public void run() {
+ try {
+ for (Project.NameKey nameKey : projectCache.all()) {
+ replication.scheduleFullSync(nameKey, urlMatch);
+ }
+ } catch (Exception e) {
+ log.error("Cannot enumerate known projects", e);
+ }
+ }
+
+ @Override
+ public String toString() {
+ String s = "Replicate All Projects";
+ if (urlMatch != null) {
+ s = s + " to " + urlMatch;
+ }
+ return s;
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/replication/PushOne.java b/src/main/java/com/googlesource/gerrit/plugins/replication/PushOne.java
new file mode 100644
index 0000000..eecb9e1
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/replication/PushOne.java
@@ -0,0 +1,430 @@
+// Copyright (C) 2009 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.replication;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import com.google.gerrit.extensions.events.GitReferenceUpdatedListener;
+import com.google.gerrit.reviewdb.client.Project;
+import com.google.gerrit.reviewdb.server.ReviewDb;
+import com.google.gerrit.server.git.GitRepositoryManager;
+import com.google.gerrit.server.git.PerThreadRequestScope;
+import com.google.gerrit.server.git.ProjectRunnable;
+import com.google.gerrit.server.git.TagCache;
+import com.google.gerrit.server.git.VisibleRefFilter;
+import com.google.gerrit.server.project.NoSuchProjectException;
+import com.google.gerrit.server.project.ProjectControl;
+import com.google.gwtorm.server.OrmException;
+import com.google.gwtorm.server.SchemaFactory;
+import com.google.inject.Inject;
+import com.google.inject.assistedinject.Assisted;
+
+import com.jcraft.jsch.JSchException;
+
+import org.eclipse.jgit.errors.NoRemoteRepositoryException;
+import org.eclipse.jgit.errors.NotSupportedException;
+import org.eclipse.jgit.errors.RepositoryNotFoundException;
+import org.eclipse.jgit.errors.TransportException;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.NullProgressMonitor;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.transport.CredentialsProvider;
+import org.eclipse.jgit.transport.FetchConnection;
+import org.eclipse.jgit.transport.PushResult;
+import org.eclipse.jgit.transport.RefSpec;
+import org.eclipse.jgit.transport.RemoteConfig;
+import org.eclipse.jgit.transport.RemoteRefUpdate;
+import org.eclipse.jgit.transport.Transport;
+import org.eclipse.jgit.transport.URIish;
+import org.slf4j.Logger;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A push to remote operation started by {@link GitReferenceUpdatedListener}.
+ * <p>
+ * Instance members are protected by the lock within PushQueue. Callers must
+ * take that lock to ensure they are working with a current view of the object.
+ */
+class PushOne implements ProjectRunnable {
+ private static final Logger log = ReplicationQueue.log;
+ static final String ALL_REFS = "..all..";
+
+ interface Factory {
+ PushOne create(Project.NameKey d, URIish u);
+ }
+
+ private final GitRepositoryManager gitManager;
+ private final SchemaFactory<ReviewDb> schema;
+ private final Destination pool;
+ private final RemoteConfig config;
+ private final CredentialsProvider credentialsProvider;
+ private final TagCache tagCache;
+
+ private final Project.NameKey projectName;
+ private final URIish uri;
+ private final Set<String> delta = Sets.newHashSetWithExpectedSize(4);
+ private boolean pushAllRefs;
+ private Repository git;
+ private boolean retrying;
+ private boolean canceled;
+
+ @Inject
+ PushOne(final GitRepositoryManager grm,
+ final SchemaFactory<ReviewDb> s,
+ final Destination p,
+ final RemoteConfig c,
+ final SecureCredentialsFactory cpFactory,
+ final TagCache tc,
+ @Assisted final Project.NameKey d,
+ @Assisted final URIish u) {
+ gitManager = grm;
+ schema = s;
+ pool = p;
+ config = c;
+ credentialsProvider = cpFactory.create(c.getName());
+ tagCache = tc;
+ projectName = d;
+ uri = u;
+ }
+
+ @Override
+ public Project.NameKey getProjectNameKey() {
+ return projectName;
+ }
+
+ @Override
+ public String getRemoteName() {
+ return config.getName();
+ }
+
+ @Override
+ public boolean hasCustomizedPrint() {
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return "push " + uri;
+ }
+
+ boolean isRetrying() {
+ return retrying;
+ }
+
+ void setToRetry() {
+ retrying = true;
+ }
+
+ void cancel() {
+ canceled = true;
+ }
+
+ boolean wasCanceled() {
+ return canceled;
+ }
+
+ URIish getURI() {
+ return uri;
+ }
+
+ void addRef(String ref) {
+ if (ALL_REFS.equals(ref)) {
+ delta.clear();
+ pushAllRefs = true;
+ } else if (!pushAllRefs) {
+ delta.add(ref);
+ }
+ }
+
+ Set<String> getRefs() {
+ return pushAllRefs ? Sets.newHashSet(ALL_REFS) : delta;
+ }
+
+ void addRefs(Set<String> refs) {
+ if (!pushAllRefs) {
+ for (String ref : refs) {
+ addRef(ref);
+ }
+ }
+ }
+
+ @Override
+ public void run() {
+ PerThreadRequestScope ctx = new PerThreadRequestScope();
+ PerThreadRequestScope old = PerThreadRequestScope.set(ctx);
+ try {
+ runPushOperation();
+ } finally {
+ PerThreadRequestScope.set(old);
+ }
+ }
+
+ private void runPushOperation() {
+ // Lock the queue, and remove ourselves, so we can't be modified once
+ // we start replication (instead a new instance, with the same URI, is
+ // created and scheduled for a future point in time.)
+ //
+ pool.notifyStarting(this);
+
+ // It should only verify if it was canceled after calling notifyStarting,
+ // since the canceled flag would be set locking the queue.
+ if (!canceled) {
+ try {
+ git = gitManager.openRepository(projectName);
+ runImpl();
+ } catch (RepositoryNotFoundException e) {
+ log.error("Cannot replicate " + projectName + "; " + e.getMessage());
+
+ } catch (NoRemoteRepositoryException e) {
+ log.error("Cannot replicate to " + uri + "; repository not found");
+
+ } catch (NotSupportedException e) {
+ log.error("Cannot replicate to " + uri, e);
+
+ } catch (TransportException e) {
+ Throwable cause = e.getCause();
+ if (cause instanceof JSchException
+ && cause.getMessage().startsWith("UnknownHostKey:")) {
+ log.error("Cannot replicate to " + uri + ": " + cause.getMessage());
+ } else {
+ log.error("Cannot replicate to " + uri, e);
+ }
+
+ // The remote push operation should be retried.
+ pool.reschedule(this);
+ } catch (IOException e) {
+ log.error("Cannot replicate to " + uri, e);
+
+ } catch (RuntimeException e) {
+ log.error("Unexpected error during replication to " + uri, e);
+
+ } catch (Error e) {
+ log.error("Unexpected error during replication to " + uri, e);
+
+ } finally {
+ if (git != null) {
+ git.close();
+ }
+ }
+ }
+ }
+
+ private void runImpl() throws IOException {
+ Transport tn = Transport.open(git, uri);
+ PushResult res;
+ try {
+ res = pushVia(tn);
+ } finally {
+ try {
+ tn.close();
+ } catch (Throwable e2) {
+ log.warn("Unexpected error while closing " + uri, e2);
+ }
+ }
+
+ for (RemoteRefUpdate u : res.getRemoteUpdates()) {
+ switch (u.getStatus()) {
+ case OK:
+ case UP_TO_DATE:
+ case NON_EXISTING:
+ break;
+
+ case NOT_ATTEMPTED:
+ case AWAITING_REPORT:
+ case REJECTED_NODELETE:
+ case REJECTED_NONFASTFORWARD:
+ case REJECTED_REMOTE_CHANGED:
+ log.error(String.format("Failed replicate of %s to %s: status %s",
+ u.getRemoteName(), uri, u.getStatus()));
+ break;
+
+ case REJECTED_OTHER_REASON:
+ if ("non-fast-forward".equals(u.getMessage())) {
+ log.error(String.format("Failed replicate of %s to %s"
+ + ", remote rejected non-fast-forward push."
+ + " Check receive.denyNonFastForwards variable in config file"
+ + " of destination repository.", u.getRemoteName(), uri));
+ } else {
+ log.error(String.format(
+ "Failed replicate of %s to %s, reason: %s",
+ u.getRemoteName(), uri, u.getMessage()));
+ }
+ break;
+ }
+ }
+ }
+
+ private PushResult pushVia(Transport tn)
+ throws IOException, NotSupportedException, TransportException {
+ tn.applyConfig(config);
+ tn.setCredentialsProvider(credentialsProvider);
+
+ List<RemoteRefUpdate> todo = generateUpdates(tn);
+ if (todo.isEmpty()) {
+ // If we have no commands selected, we have nothing to do.
+ // Calling JGit at this point would just redo the work we
+ // already did, and come up with the same answer. Instead
+ // send back an empty result.
+ return new PushResult();
+ }
+
+ return tn.push(NullProgressMonitor.INSTANCE, todo);
+ }
+
+ private List<RemoteRefUpdate> generateUpdates(Transport tn)
+ throws IOException {
+ ProjectControl pc;
+ try {
+ pc = pool.controlFor(projectName);
+ } catch (NoSuchProjectException e) {
+ return Collections.emptyList();
+ }
+
+ Map<String, Ref> local = git.getAllRefs();
+ if (!pc.allRefsAreVisible()) {
+ if (!pushAllRefs) {
+ // If we aren't mirroring, reduce the space we need to filter
+ // to only the references we will update during this operation.
+ //
+ Map<String, Ref> n = Maps.newHashMap();
+ for (String src : delta) {
+ Ref r = local.get(src);
+ if (r != null) {
+ n.put(src, r);
+ }
+ }
+ local = n;
+ }
+
+ ReviewDb db;
+ try {
+ db = schema.open();
+ } catch (OrmException e) {
+ log.error("Cannot read database to replicate to " + projectName, e);
+ return Collections.emptyList();
+ }
+ try {
+ local = new VisibleRefFilter(tagCache, git, pc, db, true).filter(local, true);
+ } finally {
+ db.close();
+ }
+ }
+
+ return pushAllRefs ? doPushAll(tn, local) : doPushDelta(local);
+ }
+
+ private List<RemoteRefUpdate> doPushAll(Transport tn, Map<String, Ref> local)
+ throws NotSupportedException, TransportException, IOException {
+ List<RemoteRefUpdate> cmds = Lists.newArrayList();
+ boolean noPerms = !pool.isReplicatePermissions();
+ Map<String, Ref> remote = listRemote(tn);
+ for (Ref src : local.values()) {
+ if (noPerms && GitRepositoryManager.REF_CONFIG.equals(src.getName())) {
+ continue;
+ }
+
+ RefSpec spec = matchSrc(src.getName());
+ if (spec != null) {
+ Ref dst = remote.get(spec.getDestination());
+ if (dst == null || !src.getObjectId().equals(dst.getObjectId())) {
+ // Doesn't exist yet, or isn't the same value, request to push.
+ push(cmds, spec, src);
+ }
+ }
+ }
+
+ if (config.isMirror()) {
+ for (Ref ref : remote.values()) {
+ if (!Constants.HEAD.equals(ref.getName())) {
+ RefSpec spec = matchDst(ref.getName());
+ if (spec != null && !local.containsKey(spec.getSource())) {
+ // No longer on local side, request removal.
+ delete(cmds, spec);
+ }
+ }
+ }
+ }
+ return cmds;
+ }
+
+ private List<RemoteRefUpdate> doPushDelta(Map<String, Ref> local)
+ throws IOException {
+ List<RemoteRefUpdate> cmds = Lists.newArrayList();
+ boolean noPerms = !pool.isReplicatePermissions();
+ for (String src : delta) {
+ RefSpec spec = matchSrc(src);
+ if (spec != null) {
+ // If the ref still exists locally, send it, otherwise delete it.
+ Ref srcRef = local.get(src);
+ if (srcRef != null &&
+ !(noPerms && GitRepositoryManager.REF_CONFIG.equals(src))) {
+ push(cmds, spec, srcRef);
+ } else if (config.isMirror()) {
+ delete(cmds, spec);
+ }
+ }
+ }
+ return cmds;
+ }
+
+ private Map<String, Ref> listRemote(Transport tn)
+ throws NotSupportedException, TransportException {
+ FetchConnection fc = tn.openFetch();
+ try {
+ return fc.getRefsMap();
+ } finally {
+ fc.close();
+ }
+ }
+
+ private RefSpec matchSrc(String ref) {
+ for (RefSpec s : config.getPushRefSpecs()) {
+ if (s.matchSource(ref)) {
+ return s.expandFromSource(ref);
+ }
+ }
+ return null;
+ }
+
+ private RefSpec matchDst(String ref) {
+ for (RefSpec s : config.getPushRefSpecs()) {
+ if (s.matchDestination(ref)) {
+ return s.expandFromDestination(ref);
+ }
+ }
+ return null;
+ }
+
+ private void push(List<RemoteRefUpdate> cmds, RefSpec spec, Ref src)
+ throws IOException {
+ String dst = spec.getDestination();
+ boolean force = spec.isForceUpdate();
+ cmds.add(new RemoteRefUpdate(git, src, dst, force, null, null));
+ }
+
+ private void delete(List<RemoteRefUpdate> cmds, RefSpec spec)
+ throws IOException {
+ String dst = spec.getDestination();
+ boolean force = spec.isForceUpdate();
+ cmds.add(new RemoteRefUpdate(git, (Ref) null, dst, force, null, null));
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/replication/RemoteSiteUser.java b/src/main/java/com/googlesource/gerrit/plugins/replication/RemoteSiteUser.java
new file mode 100644
index 0000000..22887e1
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/replication/RemoteSiteUser.java
@@ -0,0 +1,58 @@
+// Copyright (C) 2009 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.replication;
+
+import com.google.gerrit.reviewdb.client.AccountProjectWatch;
+import com.google.gerrit.reviewdb.client.Change;
+import com.google.gerrit.server.AccessPath;
+import com.google.gerrit.server.CurrentUser;
+import com.google.gerrit.server.account.CapabilityControl;
+import com.google.gerrit.server.account.GroupMembership;
+import com.google.inject.Inject;
+import com.google.inject.assistedinject.Assisted;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Set;
+
+class RemoteSiteUser extends CurrentUser {
+ interface Factory {
+ RemoteSiteUser create(@Assisted GroupMembership authGroups);
+ }
+
+ private final GroupMembership effectiveGroups;
+
+ @Inject
+ RemoteSiteUser(CapabilityControl.Factory capabilityControlFactory,
+ @Assisted GroupMembership authGroups) {
+ super(capabilityControlFactory, AccessPath.GIT);
+ effectiveGroups = authGroups;
+ }
+
+ @Override
+ public GroupMembership getEffectiveGroups() {
+ return effectiveGroups;
+ }
+
+ @Override
+ public Set<Change.Id> getStarredChanges() {
+ return Collections.emptySet();
+ }
+
+ @Override
+ public Collection<AccountProjectWatch> getNotificationFilters() {
+ return Collections.emptySet();
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationModule.java b/src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationModule.java
new file mode 100644
index 0000000..974cf4a
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationModule.java
@@ -0,0 +1,46 @@
+// Copyright (C) 2012 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.replication;
+
+import com.google.gerrit.extensions.events.GitReferenceUpdatedListener;
+import com.google.gerrit.extensions.events.LifecycleListener;
+import com.google.gerrit.extensions.events.NewProjectCreatedListener;
+import com.google.gerrit.extensions.registration.DynamicSet;
+import com.google.inject.AbstractModule;
+import com.google.inject.Scopes;
+import com.google.inject.assistedinject.FactoryModuleBuilder;
+import com.google.inject.internal.UniqueAnnotations;
+
+class ReplicationModule extends AbstractModule {
+ @Override
+ protected void configure() {
+ bind(ReplicationQueue.class).in(Scopes.SINGLETON);
+
+ DynamicSet.bind(binder(), GitReferenceUpdatedListener.class)
+ .to(ReplicationQueue.class);
+
+ DynamicSet.bind(binder(), NewProjectCreatedListener.class)
+ .to(ReplicationQueue.class);
+
+ bind(OnStartStop.class).in(Scopes.SINGLETON);
+ bind(LifecycleListener.class)
+ .annotatedWith(UniqueAnnotations.create())
+ .to(OnStartStop.class);
+
+ bind(SecureCredentialsFactory.class).in(Scopes.SINGLETON);
+ install(new FactoryModuleBuilder().build(PushAll.Factory.class));
+ install(new FactoryModuleBuilder().build(RemoteSiteUser.Factory.class));
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java b/src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java
new file mode 100644
index 0000000..e61aab5
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java
@@ -0,0 +1,393 @@
+// Copyright (C) 2009 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.replication;
+
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import com.google.gerrit.extensions.events.GitReferenceUpdatedListener;
+import com.google.gerrit.extensions.events.LifecycleListener;
+import com.google.gerrit.extensions.events.NewProjectCreatedListener;
+import com.google.gerrit.reviewdb.client.Project;
+import com.google.gerrit.reviewdb.server.ReviewDb;
+import com.google.gerrit.server.InternalUser;
+import com.google.gerrit.server.account.GroupCache;
+import com.google.gerrit.server.config.SitePaths;
+import com.google.gerrit.server.git.GitRepositoryManager;
+import com.google.gerrit.server.git.WorkQueue;
+import com.google.gwtorm.server.SchemaFactory;
+import com.google.inject.Inject;
+import com.google.inject.Injector;
+
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.errors.TransportException;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.RefUpdate;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.storage.file.FileBasedConfig;
+import org.eclipse.jgit.storage.file.FileRepository;
+import org.eclipse.jgit.transport.RefSpec;
+import org.eclipse.jgit.transport.RemoteConfig;
+import org.eclipse.jgit.transport.RemoteSession;
+import org.eclipse.jgit.transport.SshSessionFactory;
+import org.eclipse.jgit.transport.URIish;
+import org.eclipse.jgit.util.FS;
+import org.eclipse.jgit.util.QuotedString;
+import org.eclipse.jgit.util.io.StreamCopyThread;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.URISyntaxException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+/** Manages automatic replication to remote repositories. */
+class ReplicationQueue implements
+ LifecycleListener,
+ GitReferenceUpdatedListener,
+ NewProjectCreatedListener {
+ static final Logger log = LoggerFactory.getLogger(ReplicationQueue.class);
+
+ static String replaceName(String in, String name) {
+ String key = "${name}";
+ int n = in.indexOf(key);
+ if (0 <= n) {
+ return in.substring(0, n) + name + in.substring(n + key.length());
+ }
+ return null;
+ }
+
+ private final Injector injector;
+ private final WorkQueue workQueue;
+ private final List<Destination> configs;
+ private final SchemaFactory<ReviewDb> database;
+ private final RemoteSiteUser.Factory replicationUserFactory;
+ private final InternalUser.Factory internalUserFactory;
+ private final GitRepositoryManager gitRepositoryManager;
+ private final GroupCache groupCache;
+ private volatile boolean running;
+ boolean replicateAllOnPluginStart;
+
+ @Inject
+ ReplicationQueue(final Injector i, final WorkQueue wq, final SitePaths site,
+ final RemoteSiteUser.Factory ruf, final InternalUser.Factory iuf,
+ final SchemaFactory<ReviewDb> db,
+ final GitRepositoryManager grm, GroupCache gc)
+ throws ConfigInvalidException, IOException {
+ injector = i;
+ workQueue = wq;
+ database = db;
+ replicationUserFactory = ruf;
+ internalUserFactory = iuf;
+ gitRepositoryManager = grm;
+ groupCache = gc;
+ configs = allDestinations(new File(site.etc_dir, "replication.config"));
+ }
+
+ @Override
+ public void start() {
+ for (Destination cfg : configs) {
+ cfg.start(workQueue);
+ }
+ running = true;
+ }
+
+ @Override
+ public void stop() {
+ running = false;
+ int discarded = 0;
+ for (Destination cfg : configs) {
+ discarded += cfg.shutdown();
+ }
+ if (discarded > 0) {
+ log.warn(String.format(
+ "Cancelled %d replication events during shutdown",
+ discarded));
+ }
+ }
+
+ void scheduleFullSync(final Project.NameKey project, final String urlMatch) {
+ if (!running) {
+ log.warn("Replication plugin did not finish startup before event");
+ return;
+ }
+
+ for (Destination cfg : configs) {
+ for (URIish uri : cfg.getURIs(project, urlMatch)) {
+ cfg.schedule(project, PushOne.ALL_REFS, uri);
+ }
+ }
+ }
+
+ @Override
+ public void onGitReferenceUpdated(GitReferenceUpdatedListener.Event event) {
+ if (!running) {
+ log.warn("Replication plugin did not finish startup before event");
+ return;
+ }
+
+ Project.NameKey project = new Project.NameKey(event.getProjectName());
+ for (GitReferenceUpdatedListener.Update u : event.getUpdates()) {
+ for (Destination cfg : configs) {
+ if (cfg.wouldPushRef(u.getRefName())) {
+ for (URIish uri : cfg.getURIs(project, null)) {
+ cfg.schedule(project, u.getRefName(), uri);
+ }
+ }
+ }
+ }
+ }
+
+ private List<Destination> allDestinations(File cfgPath)
+ throws ConfigInvalidException, IOException {
+ FileBasedConfig cfg = new FileBasedConfig(cfgPath, FS.DETECTED);
+ if (!cfg.getFile().exists()) {
+ log.warn("No " + cfg.getFile() + "; not replicating");
+ return Collections.emptyList();
+ }
+ if (cfg.getFile().length() == 0) {
+ log.info("Empty " + cfg.getFile() + "; not replicating");
+ return Collections.emptyList();
+ }
+
+ try {
+ cfg.load();
+ } catch (ConfigInvalidException e) {
+ throw new ConfigInvalidException(String.format(
+ "Config file %s is invalid: %s",cfg.getFile(), e.getMessage()), e);
+ } catch (IOException e) {
+ throw new IOException(String.format(
+ "Cannot read %s: %s", cfg.getFile(), e.getMessage()), e);
+ }
+
+ replicateAllOnPluginStart = cfg.getBoolean(
+ "gerrit", "replicateOnStartup",
+ true);
+
+ ImmutableList.Builder<Destination> dest = ImmutableList.builder();
+ for (RemoteConfig c : allRemotes(cfg)) {
+ if (c.getURIs().isEmpty()) {
+ continue;
+ }
+
+ for (URIish u : c.getURIs()) {
+ if (u.getPath() == null || !u.getPath().contains("${name}")) {
+ throw new ConfigInvalidException(String.format(
+ "remote.%s.url \"%s\" lacks ${name} placeholder in %s",
+ c.getName(), u, cfg.getFile()));
+ }
+ }
+
+ // If destination for push is not set assume equal to source.
+ for (RefSpec ref : c.getPushRefSpecs()) {
+ if (ref.getDestination() == null) {
+ ref.setDestination(ref.getSource());
+ }
+ }
+
+ if (c.getPushRefSpecs().isEmpty()) {
+ c.addPushRefSpec(new RefSpec()
+ .setSourceDestination("refs/*", "refs/*")
+ .setForceUpdate(true));
+ }
+
+ dest.add(new Destination(injector, c, cfg, database,
+ replicationUserFactory, internalUserFactory,
+ gitRepositoryManager, groupCache));
+ }
+ return dest.build();
+ }
+
+ private static List<RemoteConfig> allRemotes(FileBasedConfig cfg)
+ throws ConfigInvalidException {
+ Set<String> names = cfg.getSubsections("remote");
+ List<RemoteConfig> result = Lists.newArrayListWithCapacity(names.size());
+ for (String name : names) {
+ try {
+ result.add(new RemoteConfig(cfg, name));
+ } catch (URISyntaxException e) {
+ throw new ConfigInvalidException(String.format(
+ "remote %s has invalid URL in %s", name, cfg.getFile()));
+ }
+ }
+ return result;
+ }
+
+ @Override
+ public void onNewProjectCreated(NewProjectCreatedListener.Event event) {
+ if (configs.isEmpty()) {
+ return;
+ }
+ if (!running) {
+ log.error("Replication plugin did not finish startup before event");
+ return;
+ }
+
+ Project.NameKey projectName = new Project.NameKey(event.getProjectName());
+ for (Destination config : configs) {
+ List<URIish> uriList = config.getURIs(projectName, "*");
+ String[] adminUrls = config.getAdminUrls();
+ boolean adminURLUsed = false;
+
+ for (String url : adminUrls) {
+ if (Strings.isNullOrEmpty(url)) {
+ continue;
+ }
+
+ URIish uri;
+ try {
+ uri = new URIish(url);
+ } catch (URISyntaxException e) {
+ log.warn(String.format("adminURL '%s' is invalid: %s", url, e.getMessage()));
+ continue;
+ }
+
+ String path = replaceName(uri.getPath(), projectName.get());
+ if (path == null) {
+ log.warn(String.format("adminURL %s does not contain ${name}", uri));
+ continue;
+ }
+
+ uri = uri.setPath(path);
+ if (!isSSH(uri)) {
+ log.warn(String.format("adminURL '%s' is invalid: only SSH is supported", uri));
+ continue;
+ }
+
+ createProject(uri, event.getHeadName());
+ adminURLUsed = true;
+ }
+
+ if (!adminURLUsed) {
+ for (URIish uri : uriList) {
+ createProject(uri, event.getHeadName());
+ }
+ }
+ }
+ }
+
+ private void createProject(URIish replicateURI, String head) {
+ if (!replicateURI.isRemote()) {
+ createLocally(replicateURI, head);
+ } else if (isSSH(replicateURI)) {
+ createRemoteSsh(replicateURI, head);
+ } else {
+ log.warn(String.format("Cannot create new project on remote site %s."
+ + " Only local paths and SSH URLs are supported"
+ + " for remote repository creation", replicateURI));
+ }
+ }
+
+ private static void createLocally(URIish uri, String head) {
+ try {
+ Repository repo = new FileRepository(uri.getPath());
+ try {
+ repo.create(true /* bare */);
+
+ RefUpdate u = repo.updateRef(Constants.HEAD);
+ u.disableRefLog();
+ u.link(head);
+ } finally {
+ repo.close();
+ }
+ } catch (IOException e) {
+ log.error(String.format("Failed to create repository %s", uri.getPath()), e);
+ }
+ }
+
+ private static void createRemoteSsh(URIish uri, String head) {
+ String quotedPath = QuotedString.BOURNE.quote(uri.getPath());
+ String cmd = "mkdir -p " + quotedPath
+ + "&& cd " + quotedPath
+ + "&& git init --bare"
+ + "&& git symbolic-ref HEAD " + QuotedString.BOURNE.quote(head);
+ OutputStream errStream = newErrorBufferStream();
+ try {
+ RemoteSession ssh = connect(uri);
+ Process proc = ssh.exec(cmd, 0);
+ proc.getOutputStream().close();
+ StreamCopyThread out = new StreamCopyThread(proc.getInputStream(), errStream);
+ StreamCopyThread err = new StreamCopyThread(proc.getErrorStream(), errStream);
+ out.start();
+ err.start();
+ try {
+ proc.waitFor();
+ out.halt();
+ err.halt();
+ } catch (InterruptedException interrupted) {
+ // Don't wait, drop out immediately.
+ }
+ ssh.disconnect();
+ } catch (IOException e) {
+ log.error(String.format(
+ "Error creating remote repository at %s:\n"
+ + " Exception: %s\n"
+ + " Command: %s\n"
+ + " Output: %s",
+ uri, e, cmd, errStream), e);
+ }
+ }
+
+ private static RemoteSession connect(URIish uri) throws TransportException {
+ return SshSessionFactory.getInstance().getSession(uri, null, FS.DETECTED, 0);
+ }
+
+ private static OutputStream newErrorBufferStream() {
+ return new OutputStream() {
+ private final StringBuilder out = new StringBuilder();
+ private final StringBuilder line = new StringBuilder();
+
+ @Override
+ public synchronized String toString() {
+ while (out.length() > 0 && out.charAt(out.length() - 1) == '\n') {
+ out.setLength(out.length() - 1);
+ }
+ return out.toString();
+ }
+
+ @Override
+ public synchronized void write(final int b) {
+ if (b == '\r') {
+ return;
+ }
+
+ line.append((char) b);
+
+ if (b == '\n') {
+ out.append(line);
+ line.setLength(0);
+ }
+ }
+ };
+ }
+
+ private static boolean isSSH(URIish uri) {
+ String scheme = uri.getScheme();
+ if (!uri.isRemote()) {
+ return false;
+ }
+ if (scheme != null && scheme.toLowerCase().contains("ssh")) {
+ return true;
+ }
+ if (scheme == null && uri.getHost() != null && uri.getPath() != null) {
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/replication/SecureCredentialsFactory.java b/src/main/java/com/googlesource/gerrit/plugins/replication/SecureCredentialsFactory.java
new file mode 100644
index 0000000..7bb9831
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/replication/SecureCredentialsFactory.java
@@ -0,0 +1,59 @@
+// Copyright (C) 2011 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.replication;
+
+import com.google.gerrit.server.config.SitePaths;
+import com.google.inject.Inject;
+
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.storage.file.FileBasedConfig;
+import org.eclipse.jgit.util.FS;
+
+import java.io.IOException;
+
+/** Looks up a remote's password in secure.config. */
+class SecureCredentialsFactory {
+ private final Config config;
+
+ @Inject
+ SecureCredentialsFactory(SitePaths site)
+ throws ConfigInvalidException, IOException {
+ config = load(site);
+ }
+
+ private static Config load(SitePaths site)
+ throws ConfigInvalidException, IOException {
+ FileBasedConfig cfg = new FileBasedConfig(site.secure_config, FS.DETECTED);
+ if (cfg.getFile().exists() && cfg.getFile().length() > 0) {
+ try {
+ cfg.load();
+ } catch (ConfigInvalidException e) {
+ throw new ConfigInvalidException(String.format(
+ "Config file %s is invalid: %s", cfg.getFile(), e.getMessage()), e);
+ } catch (IOException e) {
+ throw new IOException(String.format(
+ "Cannot read %s: %s", cfg.getFile(), e.getMessage()), e);
+ }
+ }
+ return cfg;
+ }
+
+ SecureCredentialsProvider create(String remoteName) {
+ String user = config.getString("remote", remoteName, "username");
+ String pass = config.getString("remote", remoteName, "password");
+ return new SecureCredentialsProvider(user, pass);
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/replication/SecureCredentialsProvider.java b/src/main/java/com/googlesource/gerrit/plugins/replication/SecureCredentialsProvider.java
new file mode 100644
index 0000000..a878ed9
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/replication/SecureCredentialsProvider.java
@@ -0,0 +1,81 @@
+// Copyright (C) 2011 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.replication;
+
+import org.eclipse.jgit.errors.UnsupportedCredentialItem;
+import org.eclipse.jgit.transport.CredentialItem;
+import org.eclipse.jgit.transport.CredentialsProvider;
+import org.eclipse.jgit.transport.URIish;
+
+/** Looks up a remote's password in secure.config. */
+class SecureCredentialsProvider extends CredentialsProvider {
+ private final String cfgUser;
+ private final String cfgPass;
+
+ SecureCredentialsProvider(String user, String pass) {
+ cfgUser = user;
+ cfgPass = pass;
+ }
+
+ @Override
+ public boolean isInteractive() {
+ return false;
+ }
+
+ @Override
+ public boolean supports(CredentialItem... items) {
+ for (CredentialItem i : items) {
+ if (i instanceof CredentialItem.Username) {
+ continue;
+ } else if (i instanceof CredentialItem.Password) {
+ continue;
+ } else {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public boolean get(URIish uri, CredentialItem... items)
+ throws UnsupportedCredentialItem {
+ String username = uri.getUser();
+ if (username == null) {
+ username = cfgUser;
+ }
+ if (username == null) {
+ return false;
+ }
+
+ String password = uri.getPass();
+ if (password == null) {
+ password = cfgPass;
+ }
+ if (password == null) {
+ return false;
+ }
+
+ for (CredentialItem i : items) {
+ if (i instanceof CredentialItem.Username) {
+ ((CredentialItem.Username) i).setValue(username);
+ } else if (i instanceof CredentialItem.Password) {
+ ((CredentialItem.Password) i).setValue(password.toCharArray());
+ } else {
+ throw new UnsupportedCredentialItem(uri, i.getPromptText());
+ }
+ }
+ return true;
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/replication/SshModule.java b/src/main/java/com/googlesource/gerrit/plugins/replication/SshModule.java
new file mode 100644
index 0000000..89486d3
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/replication/SshModule.java
@@ -0,0 +1,24 @@
+// Copyright (C) 2012 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.replication;
+
+import com.google.gerrit.sshd.PluginCommandModule;
+
+class SshModule extends PluginCommandModule {
+ @Override
+ protected void configureCommands() {
+ command("start").to(StartCommand.class);
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/replication/StartCommand.java b/src/main/java/com/googlesource/gerrit/plugins/replication/StartCommand.java
new file mode 100644
index 0000000..a6148ea
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/replication/StartCommand.java
@@ -0,0 +1,72 @@
+// Copyright (C) 2009 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.replication;
+
+import com.google.gerrit.common.data.GlobalCapability;
+import com.google.gerrit.reviewdb.client.Project;
+import com.google.gerrit.server.project.ProjectCache;
+import com.google.gerrit.sshd.RequiresCapability;
+import com.google.gerrit.sshd.SshCommand;
+import com.google.inject.Inject;
+
+import org.kohsuke.args4j.Argument;
+import org.kohsuke.args4j.Option;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+/** Force a project to replicate, again. */
+@RequiresCapability(GlobalCapability.START_REPLICATION)
+final class StartCommand extends SshCommand {
+ @Option(name = "--all", usage = "push all known projects")
+ private boolean all;
+
+ @Option(name = "--url", metaVar = "PATTERN", usage = "pattern to match URL on")
+ private String urlMatch;
+
+ @Argument(index = 0, multiValued = true, metaVar = "PROJECT", usage = "project name")
+ private List<String> projectNames = new ArrayList<String>(2);
+
+ @Inject
+ private PushAll.Factory pushAllFactory;
+
+ @Inject
+ private ReplicationQueue replication;
+
+ @Inject
+ private ProjectCache projectCache;
+
+ @Override
+ protected void run() throws Failure {
+ if (all && projectNames.size() > 0) {
+ throw new UnloggedFailure(1, "error: cannot combine --all and PROJECT");
+ }
+
+ if (all) {
+ pushAllFactory.create(urlMatch).schedule(0, TimeUnit.SECONDS);
+
+ } else {
+ for (String name : projectNames) {
+ Project.NameKey key = new Project.NameKey(name);
+ if (projectCache.get(key) != null) {
+ replication.scheduleFullSync(key, urlMatch);
+ } else {
+ throw new UnloggedFailure(1, "error: '" + name + "': not a Gerrit project");
+ }
+ }
+ }
+ }
+}
diff --git a/src/main/resources/Documentation/cmd-start.md b/src/main/resources/Documentation/cmd-start.md
new file mode 100644
index 0000000..39cbda9
--- /dev/null
+++ b/src/main/resources/Documentation/cmd-start.md
@@ -0,0 +1,106 @@
+@PLUGIN@ start
+==============
+
+NAME
+----
+@PLUGIN@ start - Manually trigger replication, to recover a node
+
+SYNOPSIS
+--------
+```
+ssh -p @SSH_PORT@ @SSH_HOST@ @PLUGIN@ start
+ [--url <PATTERN>]
+ {--all | <PROJECT> ...}
+```
+
+DESCRIPTION
+-----------
+Schedules replication of the specified projects to all configured
+replication destinations, or only those whose URLs match the pattern
+given on the command line.
+
+Normally Gerrit automatically schedules replication whenever it
+makes a change to a managed Git repository. However, there are
+other reasons why an administrator may wish to trigger replication:
+
+* Destination disappears, then later comes back online.
+
+ If a destination went offline for a period of time, when it
+ comes back, it may be missing commits that it should have.
+ Triggering a replication run for all projects against that URL
+ will update it.
+
+* After repacking locally, and using `rsync` to distribute the new
+ pack files to the destinations.
+
+ If the local server is repacked, and then the resulting pack
+ files are sent to remote peers using `rsync -a
+ --delete-after`, there is a chance that the rsync missed a
+ change that was added during the rsync data transfer, and the
+ rsync will remove that changes's data from the remote, even
+ though the automatic replication pushed it there in parallel
+ to the rsync.
+
+ Its a good idea to run replicate with `--all` to ensure all
+ projects are consistent after the rsync is complete.
+
+* After deleting a ref by hand.
+
+ If a ref must be removed (e.g. to purge a change or patch set
+ that shouldn't have been created, and that must be eradicated)
+ that delete must be done by direct git access on the local,
+ managed repository. Gerrit won't know about the delete, and
+ is unable to replicate it automatically. Triggering
+ replication on just the affected project can update the
+ mirrors.
+
+ACCESS
+------
+Caller must be a member of the privileged 'Administrators' group,
+or have been granted [the 'Start Replication' global capability][1].
+
+[1]: ../../../Documentation/access-control.html#capability_startReplication
+
+SCRIPTING
+---------
+This command is intended to be used in scripts.
+
+OPTIONS
+-------
+
+`--all`
+: Schedule replicating for all projects.
+
+`--url <PATTERN>`
+: Replicate only to replication destinations whose URL contains
+ the substring <PATTERN>. This can be useful to replicate
+ only to a previously down node, which has been brought back
+ online.
+
+EXAMPLES
+--------
+Replicate every project, to every configured remote:
+
+```
+ $ ssh -p @SSH_PORT@ @SSH_HOST@ @PLUGIN@ start --all
+```
+
+Replicate only to `srv2` now that it is back online:
+
+```
+ $ ssh -p @SSH_PORT@ @SSH_HOST@ @PLUGIN@ start --url srv2 --all
+```
+
+Replicate only the `tools/gerrit` project, after deleting a ref
+locally by hand:
+
+```
+ $ git --git-dir=/home/git/tools/gerrit.git update-ref -d refs/changes/00/100/1
+ $ ssh -p @SSH_PORT@ @SSH_HOST@ @PLUGIN@ start tools/gerrit
+```
+
+SEE ALSO
+--------
+
+* [Replication Configuration](config.html)
+* [Access Control](../../../Documentation/access-control.html)
diff --git a/src/main/resources/Documentation/config.md b/src/main/resources/Documentation/config.md
new file mode 100644
index 0000000..0fee601
--- /dev/null
+++ b/src/main/resources/Documentation/config.md
@@ -0,0 +1,268 @@
+Replication Configuration
+=========================
+
+This plugin can automatically push any changes Gerrit Code Review
+makes to its managed Git repositories to another system. Usually this
+would be configured to provide mirroring of changes, for warm-standby
+backups, or a load-balanced public mirror farm.
+
+The replication runs on a short delay. This gives the server a small
+time window to batch updates going to the same project, such as when a
+user uploads multiple changes at once.
+
+Typically replication should be done over SSH, with a passwordless
+public/private key pair. On a trusted network it is also possible to
+use replication over the insecure (but much faster due to no
+authentication overhead or encryption) git:// protocol, by enabling
+the `receive-pack` service on the receiving system, but this
+configuration is not recommended. It is also possible to specify a
+local path as replication target. This makes e.g. sense if a network
+share is mounted to which the repositories should be replicated.
+
+Enabling Replication
+--------------------
+
+If replicating over SSH (recommended), ensure the host key of the
+remote system(s) is already in the Gerrit user's `~/.ssh/known_hosts`
+file. The easiest way to add the host key is to connect once by hand
+with the command line:
+
+```
+ sudo su -c 'ssh mirror1.us.some.org echo' gerrit2
+```
+
+<a name="example_file">
+Next, create `$site_path/etc/replication.config` as a Git-style config
+file, for example to replicate in parallel to four different hosts:</a>
+
+```
+ [remote "host-one"]
+ url = gerrit2@host-one.example.com:/some/path/${name}.git
+
+ [remote "pubmirror"]
+ url = mirror1.us.some.org:/pub/git/${name}.git
+ url = mirror2.us.some.org:/pub/git/${name}.git
+ url = mirror3.us.some.org:/pub/git/${name}.git
+ push = +refs/heads/*:refs/heads/*
+ push = +refs/tags/*:refs/tags/*
+ threads = 3
+ authGroup = Public Mirror Group
+ authGroup = Second Public Mirror Group
+```
+
+Then reload the replication plugin to pick up the new configuration:
+
+```
+ ssh -p 29418 localhost gerrit plugin reload replication
+```
+
+To manually trigger replication at runtime, see
+SSH command [start](cmd-start.html).
+
+File `replication.config`
+-------------------------
+
+The optional file `$site_path/etc/replication.config` is a Git-style
+config file that controls the replication settings for the replication
+plugin.
+
+The file is composed of one or more `remote` sections, each remote
+section provides common configuration settings for one or more
+destination URLs.
+
+Each remote section uses its own thread pool. If pushing to
+multiple remotes, over differing types of network connections
+(e.g. LAN and also public Internet), its a good idea to put them
+into different remote sections, so that replication to the slower
+connection does not starve out the faster local one. The example
+file above does this.
+
+In the keys below, the `NAME` portion is unused by this plugin, but
+must be unique to distinguish the different sections if more than one
+remote section appears in the file.
+
+gerrit.replicateOnStartup
+: If true, replicates to all remotes on startup to ensure they
+ are in-sync with this server. By default, true.
+
+remote.NAME.url
+: Address of the remote server to push to. Multiple URLs may be
+ specified within a single remote block, listing different
+ destinations which share the same settings. Assuming
+ sufficient threads in the thread pool, Gerrit pushes to all
+ URLs in parallel, using one thread per URL.
+
+ Within each URL value the magic placeholder `${name}` is
+ replaced with the Gerrit project name. This is a Gerrit
+ specific extension to the otherwise standard Git URL syntax
+ and it must be included in each URL so that Gerrit can figure
+ out where each project needs to be replicated.
+
+ See [git push][1] for details on Git URL syntax.
+
+[1]: http://www.git-scm.com/docs/git-push#URLS
+
+remote.NAME.adminUrl
+: Address of the alternative remote server only for repository
+ creation. Multiple URLs may be specified within a single
+ remote block, listing different destinations which share the
+ same settings.
+
+ The adminUrl can be used as a ssh alternative to the url
+ option, but only related to repository creation. If not
+ specified, the repository creation tries to follow the default
+ way through the url value specified.
+
+ It is useful when remote.NAME.url protocols does not allow
+ repository creation although their usage are mandatory in the
+ local environment. In that case, an alternative SSH url could
+ be specified to repository creation.
+
+remote.NAME.receivepack
+: Path of the `git-receive-pack` executable on the remote
+ system, if using the SSH transport.
+
+ Defaults to `git-receive-pack`.
+
+remote.NAME.uploadpack
+: Path of the `git-upload-pack` executable on the remote system,
+ if using the SSH transport.
+
+ Defaults to `git-upload-pack`.
+
+remote.NAME.push
+: Standard Git refspec denoting what should be replicated.
+ Setting this to `+refs/heads/*:refs/heads/*` would mirror only
+ the active branches, but not the change refs under
+ `refs/changes/`, or the tags under `refs/tags/`.
+
+ Multiple push keys can be supplied, to specify multiple
+ patterns to match against. In the [example above][2], remote
+ "pubmirror" uses two push keys to match both `refs/heads/*`
+ and `refs/tags/*`, but excludes all others, including
+ `refs/changes/*`.
+
+ Defaults to `+refs/*:refs/*` (all refs) if not specified.
+
+[2]: #example_file
+
+remote.NAME.timeout
+: Number of seconds to wait for a network read or write to
+ complete before giving up and declaring the remote side is not
+ responding. If 0, there is no timeout, and the push client
+ waits indefinitely.
+
+ A timeout should be large enough to mostly transfer the
+ objects to the other side. 1 second may be too small for
+ larger projects, especially over a WAN link, while 10-30
+ seconds is a much more reasonable timeout value.
+
+ Defaults to 0 seconds, wait indefinitely.
+
+remote.NAME.replicationDelay
+: Number of seconds to wait before scheduling a remote push
+ operation. Setting the delay to 0 effectively disables the
+ delay, causing the push to start as soon as possible.
+
+ This is a Gerrit specific extension to the Git remote block.
+
+ By default, 15 seconds.
+
+remote.NAME.replicationRetry
+: Number of minutes to wait before scheduling a remote push
+ operation previously failed due to an offline remote server.
+
+ If a remote push operation fails because a remote server was
+ offline, all push operations to the same destination URL are
+ blocked, and the remote push is continuously retried.
+
+ This is a Gerrit specific extension to the Git remote block.
+
+ By default, 1 minute.
+
+remote.NAME.threads
+: Number of worker threads to dedicate to pushing to the
+ repositories described by this remote. Each thread can push
+ one project at a time, to one destination URL. Scheduling
+ within the thread pool is done on a per-project basis. If a
+ remote block describes 4 URLs, allocating 4 threads in the
+ pool will permit some level of parallel pushing.
+
+ By default, 1 thread.
+
+remote.NAME.authGroup
+: Specifies the name of a group that the remote should use to
+ access the repositories. Multiple authGroups may be specified
+ within a single remote block to signify a wider access right.
+ In the project administration web interface the read access
+ can be specified for this group to control if a project should
+ be replicated or not to the remote.
+
+ By default, replicates without group control, i.e replicates
+ everything to all remotes.
+
+remote.NAME.replicatePermissions
+: If true, permissions-only projects and the refs/meta/config
+ branch will also be replicated to the remote site. These
+ projects and branches may be needed to keep a backup or slave
+ server current.
+
+ By default, true, replicating everything.
+
+remote.NAME.mirror
+: If true, replication will remove remote branches that absent
+ locally or invisible to the replication (for example read
+ access denied via `authGroup` option).
+
+ By default, false, do not remove remote branches.
+
+File `secure.config`
+--------------------
+
+The optional file `$site_path/secure.config` is a Git-style config
+file that provides secure values that should not be world-readable,
+such as passwords. Passwords for HTTP remotes can be obtained from
+this file.
+
+remote.NAME.username
+: Username to use for HTTP authentication on this remote, if not
+ given in the URL.
+
+remote.NAME.password
+: Password to use for HTTP authentication on this remote.
+
+File `~/.ssh/config`
+--------------------
+
+If present, Gerrit reads and caches `~/.ssh/config` at startup, and
+supports most SSH configuration options. For example:
+
+```
+ Host host-one.example.com:
+ IdentityFile ~/.ssh/id_hostone
+ PreferredAuthentications publickey
+
+ Host mirror*.us.some.org:
+ User mirror-updater
+ IdentityFile ~/.ssh/id_pubmirror
+ PreferredAuthentications publickey
+```
+
+Supported options:
+
+ * Host
+ * Hostname
+ * User
+ * Port
+ * IdentityFile
+ * PreferredAuthentications
+ * StrictHostKeyChecking
+
+SSH authentication must be by passwordless public key, as there is no
+facility to read passphases on startup or passwords during the SSH
+connection setup, and SSH agents are not supported from Java.
+
+Host keys for any destination SSH servers must appear in the user's
+`~/.ssh/known_hosts` file, and must be added in advance, before Gerrit
+starts. If a host key is not listed, Gerrit will be unable to connect
+to that destination, and replication to that URL will fail.
diff --git a/src/test/java/com/googlesource/gerrit/plugins/replication/PushReplicationTest.java b/src/test/java/com/googlesource/gerrit/plugins/replication/PushReplicationTest.java
new file mode 100644
index 0000000..1e2df38
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/plugins/replication/PushReplicationTest.java
@@ -0,0 +1,44 @@
+// Copyright (C) 2011 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.replication;
+
+import static com.googlesource.gerrit.plugins.replication.Destination.encode;
+import static com.googlesource.gerrit.plugins.replication.Destination.needsUrlEncoding;
+
+import junit.framework.TestCase;
+
+import org.eclipse.jgit.transport.URIish;
+
+import java.net.URISyntaxException;
+
+public class PushReplicationTest extends TestCase {
+ public void testNeedsUrlEncoding() throws URISyntaxException {
+ assertTrue(needsUrlEncoding(new URIish("http://host/path")));
+ assertTrue(needsUrlEncoding(new URIish("https://host/path")));
+ assertTrue(needsUrlEncoding(new URIish("amazon-s3://config/bucket/path")));
+
+ assertFalse(needsUrlEncoding(new URIish("host:path")));
+ assertFalse(needsUrlEncoding(new URIish("user@host:path")));
+ assertFalse(needsUrlEncoding(new URIish("git://host/path")));
+ assertFalse(needsUrlEncoding(new URIish("ssh://host/path")));
+ }
+
+ public void testUrlEncoding() {
+ assertEquals("foo/bar/thing", encode("foo/bar/thing"));
+ assertEquals("--%20All%20Projects%20--", encode("-- All Projects --"));
+ assertEquals("name/with%20a%20space", encode("name/with a space"));
+ assertEquals("name%0Awith-LF", encode("name\nwith-LF"));
+ }
+}