Verified Commit 0cc94878 authored by Yorick Peterse's avatar Yorick Peterse
Browse files

Rewrite the GitHub importer from scratch

Prior to this MR there were two GitHub related importers:

* Github::Import: the main importer used for GitHub projects
* Gitlab::GithubImport: importer that's somewhat confusingly used for
  importing Gitea projects (apparently they have a compatible API)

This MR renames the Gitea importer to Gitlab::LegacyGithubImport and
introduces a new GitHub importer in the Gitlab::GithubImport namespace.
This new GitHub importer uses Sidekiq for importing multiple resources
in parallel, though it also has the ability to import data sequentially
should this be necessary.

The new code is spread across the following directories:

* lib/gitlab/github_import: this directory contains most of the importer
  code such as the classes used for importing resources.
* app/workers/gitlab/github_import: this directory contains the Sidekiq
  workers, most of which simply use the code from the directory above.
* app/workers/concerns/gitlab/github_import: this directory provides a
  few modules that are included in every GitHub importer worker.

== Stages

The import work is divided into separate stages, with each stage
importing a specific set of data. Stages will schedule the work that
needs to be performed, followed by scheduling a job for the
"AdvanceStageWorker" worker. This worker will periodically check if all
work is completed and schedule the next stage if this is the case. If
work is not yet completed this worker will reschedule itself.

Using this approach we don't have to block threads by calling `sleep()`,
as doing so for large projects could block the thread from doing any
work for many hours.

== Retrying Work

Workers will reschedule themselves whenever necessary. For example,
hitting the GitHub API's rate limit will result in jobs rescheduling
themselves. These jobs are not processed until the rate limit has been
reset.

== User Lookups

Part of the importing process involves looking up user details in the
GitHub API so we can map them to GitLab users. The old importer used
an in-memory cache, but this obviously doesn't work when the work is
spread across different threads.

The new importer uses a Redis cache and makes sure we only perform
API/database calls if absolutely necessary.  Frequently used keys are
refreshed, and lookup misses are also cached; removing the need for
performing API/database calls if we know we don't have the data we're
looking for.

== Performance & Models

The new importer in various places uses raw INSERT statements (as
generated by `Gitlab::Database.bulk_insert`) instead of using Rails
models. This allows us to bypass any validations and callbacks,
drastically reducing the number of SQL queries and Gitaly RPC calls
necessary to import projects.

To ensure the code produces valid data the corresponding tests check if
the produced rows are valid according to the model validation rules.
parent 03f8f3d3
Loading
Loading
Loading
Loading
+2 −2
Original line number Diff line number Diff line
@@ -43,7 +43,7 @@ def create
    @target_namespace = find_or_create_namespace(namespace_path, current_user.namespace_path)

    if can?(current_user, :create_projects, @target_namespace)
      @project = Gitlab::GithubImport::ProjectCreator.new(repo, @project_name, @target_namespace, current_user, access_params, type: provider).execute
      @project = Gitlab::LegacyGithubImport::ProjectCreator.new(repo, @project_name, @target_namespace, current_user, access_params, type: provider).execute
    else
      render 'unauthorized'
    end
@@ -52,7 +52,7 @@ def create
  private

  def client
    @client ||= Gitlab::GithubImport::Client.new(session[access_token_key], client_options)
    @client ||= Gitlab::LegacyGithubImport::Client.new(session[access_token_key], client_options)
  end

  def verify_import_enabled
+37 −0
Original line number Diff line number Diff line
@@ -354,6 +354,7 @@ def self.with_feature_available_for_user(feature, user)
  scope :abandoned, -> { where('projects.last_activity_at < ?', 6.months.ago) }

  scope :excluding_project, ->(project) { where.not(id: project) }
  scope :import_started, -> { where(import_status: 'started') }

  state_machine :import_status, initial: :none do
    event :import_schedule do
@@ -1411,6 +1412,31 @@ def after_rename_repo
    Gitlab::PagesTransfer.new.rename_project(path_before_change, self.path, namespace.full_path)
  end

  def after_import
    repository.after_import
    import_finish
    remove_import_jid
    update_project_counter_caches
  end

  def update_project_counter_caches
    classes = [
      Projects::OpenIssuesCountService,
      Projects::OpenMergeRequestsCountService
    ]

    classes.each do |klass|
      klass.new(self).refresh_cache
    end
  end

  def remove_import_jid
    return unless import_jid

    Gitlab::SidekiqStatus.unset(import_jid)
    update_column(:import_jid, nil)
  end

  def running_or_pending_build_count(force: false)
    Rails.cache.fetch(['projects', id, 'running_or_pending_build_count'], force: force) do
      builds.running_or_pending.count(:all)
@@ -1658,6 +1684,17 @@ def gl_repository(is_wiki:)
    Gitlab::GlRepository.gl_repository(self, is_wiki)
  end

  # Refreshes the expiration time of the associated import job ID.
  #
  # This method can be used by asynchronous importers to refresh the status,
  # preventing the StuckImportJobsWorker from marking the import as failed.
  def refresh_import_jid_expiration
    return unless import_jid

    Gitlab::SidekiqStatus
      .set(import_jid, StuckImportJobsWorker::IMPORT_JOBS_EXPIRATION)
  end

  private

  def storage
+17 −1
Original line number Diff line number Diff line
@@ -4,6 +4,18 @@ class ImportService < BaseService

    Error = Class.new(StandardError)

    # Returns true if this importer is supposed to perform its work in the
    # background.
    #
    # This method will only return `true` if async importing is explicitly
    # supported by an importer class (`Gitlab::GithubImport::ParallelImporter`
    # for example).
    def async?
      return false unless has_importer?

      importer_class.respond_to?(:async?) && importer_class.async?
    end

    def execute
      add_repository_to_project unless project.gitlab_project_import?

@@ -80,7 +92,11 @@ def has_importer?
    end

    def importer
      Gitlab::ImportSources.importer(project.import_type).new(project)
      importer_class.new(project)
    end

    def importer_class
      Gitlab::ImportSources.importer(project.import_type)
    end

    def unknown_url?
+28 −0
Original line number Diff line number Diff line
# frozen_string_literal: true

module Gitlab
  module GithubImport
    # NotifyUponDeath can be included into a GitHub worker class if it should
    # notify any JobWaiter instances upon being moved to the Sidekiq dead queue.
    #
    # Note that this will only notify the waiter upon graceful termination, a
    # SIGKILL will still result in the waiter _not_ being notified.
    #
    # Workers including this module must have jobs passed where the last
    # argument is the key to notify, as a String.
    module NotifyUponDeath
      extend ActiveSupport::Concern

      included do
        # If a job is being exhausted we still want to notify the
        # AdvanceStageWorker. This prevents the entire import from getting stuck
        # just because 1 job threw too many errors.
        sidekiq_retries_exhausted do |job|
          if job.args.length == 3 && (key = job.args.last) && key.is_a?(String)
            JobWaiter.notify(key, job.jid)
          end
        end
      end
    end
  end
end
+16 −0
Original line number Diff line number Diff line
module Gitlab
  module GithubImport
    module Queue
      extend ActiveSupport::Concern

      included do
        # If a job produces an error it may block a stage from advancing
        # forever. To prevent this from happening we prevent jobs from going to
        # the dead queue. This does mean some resources may not be imported, but
        # this is better than a project being stuck in the "import" state
        # forever.
        sidekiq_options queue: 'github_importer', dead: false, retry: 10
      end
    end
  end
end
Loading