repository.rb 16.8 KB
Newer Older
1 2 3
module Elasticsearch
  module Git
    module Repository
Nick Thomas's avatar
Nick Thomas committed
4
      CreateIndexException = Class.new(StandardError)
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

      BLOBS_BATCH = 100
      COMMMITS_BATCH = 500

      extend ActiveSupport::Concern

      included do
        include Elasticsearch::Git::Model
        include Elasticsearch::Git::EncoderHelper

        mapping _parent: { type: 'project' } do
          indexes :blob do
            indexes :id,          type: :text,
                                  index_options: 'offsets',
                                  analyzer: :sha_analyzer
            indexes :rid,         type: :keyword
            indexes :oid,         type: :text,
                                  index_options: 'offsets',
                                  analyzer: :sha_analyzer
            indexes :commit_sha,  type: :text,
                                  index_options: 'offsets',
                                  analyzer: :sha_analyzer
            indexes :path,        type: :text,
                                  analyzer: :path_analyzer
            indexes :file_name,   type: :text,
                                  analyzer: :code_analyzer,
                                  search_analyzer: :code_search_analyzer
            indexes :content,     type: :text,
                                  index_options: 'offsets',
                                  analyzer: :code_analyzer,
                                  search_analyzer: :code_search_analyzer
            indexes :language,    type: :keyword
          end

          indexes :commit do
            indexes :id,          type: :text,
                                  index_options: 'offsets',
                                  analyzer: :sha_analyzer
            indexes :rid,         type: :keyword
            indexes :sha,         type: :text,
                                  index_options: 'offsets',
                                  analyzer: :sha_analyzer

            indexes :author do
              indexes :name,      type: :text, index_options: 'offsets'
              indexes :email,     type: :text, index_options: 'offsets'
              indexes :time,      type: :date, format: :basic_date_time_no_millis
            end

            indexes :commiter do
              indexes :name,      type: :text, index_options: 'offsets'
              indexes :email,     type: :text, index_options: 'offsets'
              indexes :time,      type: :date, format: :basic_date_time_no_millis
            end

            indexes :message,     type: :text, index_options: 'offsets'
          end
        end

        # Indexing all text-like blobs in repository
        #
        # All data stored in global index
        # Repository can be selected by 'rid' field
        # If you want - this field can be used for store 'project' id
        #
        # blob {
        #   id - uniq id of blob from all repositories
        #   oid - blob id in repository
        #   content - blob content
        #   commit_sha - last actual commit sha
        # }
        #
        # For search from blobs use type 'blob'
        def index_blobs(from_rev: nil, to_rev: repository_for_indexing.last_commit.oid)
          from, to = parse_revs(from_rev, to_rev)

          diff = repository_for_indexing.diff(from, to)
          deltas = diff.deltas

          deltas.reverse.each_slice(BLOBS_BATCH) do |slice|
            bulk_operations = slice.map do |delta|
              if delta.status == :deleted
                next if delta.old_file[:mode].to_s(8) == "160000"
88

89 90 91 92
                b = LiteBlob.new(repository_for_indexing, delta.old_file)
                delete_blob(b)
              else
                next if delta.new_file[:mode].to_s(8) == "160000"
93

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
                b = LiteBlob.new(repository_for_indexing, delta.new_file)
                index_blob(b, to)
              end
            end

            perform_bulk bulk_operations

            yield slice, deltas.length if block_given?
          end

          ObjectSpace.garbage_collect
        end

        def perform_bulk(bulk_operations)
          bulk_operations.compact!

          return false if bulk_operations.empty?

          client_for_indexing.bulk body: bulk_operations
        end

        def delete_blob(blob)
          return unless blob.text?
117

118 119 120 121 122 123 124 125 126 127 128 129
          {
            delete: {
              _index: "#{self.class.index_name}",
              _type: self.class.name.underscore,
              _id: "#{repository_id}_#{blob.path}",
              _parent: project_id
            }
          }
        end

        def index_blob(blob, target_sha)
          return unless can_index_blob?(blob)
130

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
          {
            index:  {
              _index: "#{self.class.index_name}",
              _type: self.class.name.underscore,
              _id: "#{repository_id}_#{blob.path}",
              _parent: project_id,
              data: {
                blob: {
                  type: "blob",
                  oid: blob.id,
                  rid: repository_id,
                  content: blob.data,
                  commit_sha: target_sha,
                  path: blob.path,

                  # We're duplicating file_name parameter here because
                  # we need another analyzer for it.
                  # Ideally this should be done with copy_to: 'blob.file_name' option
                  # but it does not work in ES v2.3.*. We're doing it so to not make users
                  # install newest versions
                  # https://github.com/elastic/elasticsearch-mapper-attachments/issues/124
                  file_name: blob.path,

                  language: blob.language ? blob.language.name : "Text"
                }
              }
            }
          }
        end

        # Index text-like files which size less 1.mb
        def can_index_blob?(blob)
          blob.text? && (blob.size && blob.size.to_i < 1048576)
        end

        # Indexing all commits in repository
        #
        # All data stored in global index
        # Repository can be filtered by 'rid' field
        # If you want - this field can be used git store 'project' id
        #
        # commit {
        #  sha - commit sha
        #  author {
        #    name - commit author name
        #    email - commit author email
        #    time - commit time
        #  }
        #  commiter {
        #    name - committer name
        #    email - committer email
        #    time - commit time
        #  }
        #  message - commit message
        # }
        #
        # For search from commits use type 'commit'
        def index_commits(from_rev: nil, to_rev: repository_for_indexing.last_commit.oid)
          from, to = parse_revs(from_rev, to_rev)
          range = [from, to].compact.join('..')
          out, err, status = Open3.capture3("git log #{range} --format=\"%H\"", chdir: repository_for_indexing.path)

          if status.success? && err.blank?
Nick Thomas's avatar
Nick Thomas committed
194
            # TODO: use rugged walker!!!
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
            commit_oids = out.split("\n")

            commit_oids.each_slice(COMMMITS_BATCH) do |batch|
              bulk_operations = batch.map do |commit|
                index_commit(repository_for_indexing.lookup(commit))
              end

              perform_bulk bulk_operations

              yield batch, commit_oids.length if block_given?
            end

            ObjectSpace.garbage_collect
          end
        end

        def index_commit(commit)
          author    = commit.author
          committer = commit.committer

          {
            index:  {
              _index: "#{self.class.index_name}",
              _type: self.class.name.underscore,
              _id: "#{repository_id}_#{commit.oid}",
              _parent: project_id,
              data: {
                commit: {
                  type: "commit",
                  rid: repository_id,
                  sha: commit.oid,
                  author: {
                    name: encode!(author[:name]),
                    email: encode!(author[:email]),
229
                    time: author[:time].strftime('%Y%m%dT%H%M%S%z')
230 231 232 233
                  },
                  committer: {
                    name: encode!(committer[:name]),
                    email: encode!(committer[:email]),
234
                    time: committer[:time].strftime('%Y%m%dT%H%M%S%z')
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
                  },
                  message: encode!(commit.message)
                }
              }
            }
          }
        end

        def parse_revs(from_rev, to_rev)
          from = if index_new_branch?(from_rev)
                   if to_rev == repository_for_indexing.last_commit.oid
                     nil
                   else
                     repository_for_indexing.merge_base(
                       to_rev,
                       repository_for_indexing.last_commit.oid
                     )
                   end
                 else
                   from_rev
                 end

Rémy Coutable's avatar
Rémy Coutable committed
257
          [from, to_rev]
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
        end

        def index_new_branch?(from)
          from == '0000000000000000000000000000000000000000'
        end

        # Representation of repository as indexed json
        # Attention: It can be very very very huge hash
        def as_indexed_json(options = {})
          data = {}
          data[:blobs] = index_blobs_array
          data[:commits] = index_commits_array
          data
        end

        # Indexing blob from current index
        def index_blobs_array
          result = []

          target_sha = repository_for_indexing.head.target.oid

          if repository_for_indexing.bare?
            tree = repository_for_indexing.lookup(target_sha).tree
            result.push(recurse_blobs_index_hash(tree))
          else
            repository_for_indexing.index.each do |blob|
              b = LiteBlob.new(repository_for_indexing, blob)
Rémy Coutable's avatar
Rémy Coutable committed
285 286 287 288 289 290 291 292 293 294 295 296

              if b.text?
                result.push(
                  {
                    type: 'blob',
                    id: "#{target_sha}_#{b.path}",
                    rid: repository_id,
                    oid: b.id,
                    content: b.data,
                    commit_sha: target_sha
                  })
              end
297 298 299 300 301 302 303 304 305 306 307 308
            end
          end

          result
        end

        def recurse_blobs_index_hash(tree, path = "")
          result = []

          tree.each_blob do |blob|
            blob[:path] = path + blob[:name]
            b = LiteBlob.new(repository_for_indexing, blob)
Rémy Coutable's avatar
Rémy Coutable committed
309 310 311 312 313 314 315 316 317 318 319 320

            if b.text?
              result.push(
                {
                  type: 'blob',
                  id: "#{repository_for_indexing.head.target.oid}_#{path}#{blob[:name]}",
                  rid: repository_id,
                  oid: b.id,
                  content: b.data,
                  commit_sha: repository_for_indexing.head.target.oid
                })
            end
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
          end

          tree.each_tree do |nested_tree|
            result.push(recurse_blobs_index_hash(repository_for_indexing.lookup(nested_tree[:oid]), "#{nested_tree[:name]}/"))
          end

          result.flatten
        end

        # Lookup all object ids for commit objects
        def index_commits_array
          res = []

          repository_for_indexing.each_id do |oid|
            obj = repository_for_indexing.lookup(oid)
            if obj.type == :commit
              res.push(
                {
                  type: 'commit',
                  sha: obj.oid,
                  author: obj.author,
                  committer: obj.committer,
                  message: encode!(obj.message)
                }
              )
            end
          end

          res
        end

        def search(query, type: :all, page: 1, per: 20, options: {})
          options[:repository_id] = repository_id if options[:repository_id].nil?
          self.class.search(query, type: type, page: page, per: per, options: options)
        end

        # Repository id used for identity data from different repositories
        # Update this value if needed
        def set_repository_id(id = nil)
          @repository_id = id || path_to_repo
        end

        # For Overwrite
        def repository_id
          @repository_id
        end

        unless defined?(path_to_repo)
          def path_to_repo
Rémy Coutable's avatar
Rémy Coutable committed
370
            @path_to_repo.presence || raise(NotImplementedError, 'Please, define "path_to_repo" method, or set "path_to_repo" via "repository_for_indexing" method')
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
          end
        end

        def repository_for_indexing(repo_path = nil)
          return @rugged_repo_indexer if defined? @rugged_repo_indexer

          @path_to_repo ||= repo_path || path_to_repo

          set_repository_id

          @rugged_repo_indexer = Rugged::Repository.new(@path_to_repo)
        end

        def client_for_indexing
          @client_for_indexing ||= Elasticsearch::Client.new retry_on_failure: 5
        end
      end

      module ClassMethods
        def search(query, type: :all, page: 1, per: 20, options: {})
Nick Thomas's avatar
Nick Thomas committed
391
          results = { blobs: [], commits: [] }
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413

          case type.to_sym
          when :all
            results[:blobs] = search_blob(query, page: page, per: per, options: options)
            results[:commits] = search_commit(query, page: page, per: per, options: options)
          when :blob
            results[:blobs] = search_blob(query, page: page, per: per, options: options)
          when :commit
            results[:commits] = search_commit(query, page: page, per: per, options: options)
          end

          results
        end

        def search_commit(query, page: 1, per: 20, options: {})
          page ||= 1

          fields = %w(message^10 sha^5 author.name^2 author.email^2 committer.name committer.email).map {|i| "commit.#{i}"}

          query_hash = {
            query: {
              bool: {
414
                must: {
415 416 417
                  simple_query_string: {
                    fields: fields,
                    query: query,
418
                    default_operator: :and
419
                  }
420 421
                },
                filter: [{ term: { 'commit.type' => 'commit' } }]
422 423 424 425 426 427 428
              }
            },
            size: per,
            from: per * (page - 1)
          }

          if query.blank?
Nick Thomas's avatar
Nick Thomas committed
429
            query_hash[:query][:bool][:must] = { match_all: {} }
430 431 432 433
            query_hash[:track_scores] = true
          end

          if options[:repository_id]
434
            query_hash[:query][:bool][:filter] << {
435 436 437 438 439 440 441 442 443 444 445
              terms: {
                'commit.rid' => [options[:repository_id]].flatten
              }
            }
          end

          if options[:additional_filter]
            query_hash[:query][:bool][:filter] << options[:additional_filter]
          end

          if options[:highlight]
Rémy Coutable's avatar
Rémy Coutable committed
446
            es_fields = fields.map { |field| field.split('^').first }.each_with_object({}) do |field, memo|
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
              memo[field.to_sym] = {}
            end

            query_hash[:highlight] = {
              pre_tags: ["gitlabelasticsearch→"],
              post_tags: ["←gitlabelasticsearch"],
              fields: es_fields
            }
          end

          options[:order] = :default if options[:order].blank?

          query_hash[:sort] = [:_score]

          res = self.__elasticsearch__.search(query_hash)
          {
            results: res.results,
            total_count: res.size
          }
        end

        def search_blob(query, type: :all, page: 1, per: 20, options: {})
          page ||= 1

          query_hash = {
            query: {
              bool: {
                must: {
                  simple_query_string: {
                    query: query,
                    default_operator: :and,
Nick Thomas's avatar
Nick Thomas committed
478
                    fields: %w[blob.content blob.file_name]
479
                  }
480 481
                },
                filter: [{ term: { 'blob.type' => 'blob' } }]
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
              }
            },
            size: per,
            from: per * (page - 1)
          }

          if options[:repository_id]
            query_hash[:query][:bool][:filter] << {
              terms: {
                'blob.rid' => [options[:repository_id]].flatten
              }
            }
          end

          if options[:additional_filter]
            query_hash[:query][:bool][:filter] << options[:additional_filter]
          end

          if options[:language]
            query_hash[:query][:bool][:filter] << {
              terms: {
                'blob.language' => [options[:language]].flatten
              }
            }
          end

          options[:order] = :default if options[:order].blank?

          query_hash[:sort] = [:_score]

          if options[:highlight]
            query_hash[:highlight] = {
              pre_tags: ["gitlabelasticsearch→"],
              post_tags: ["←gitlabelasticsearch"],
              order: "score",
              fields: {
                "blob.content" => {},
519
                "blob.file_name" => {}
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
              }
            }
          end

          res = self.__elasticsearch__.search(query_hash)

          {
            results: res.results,
            total_count: res.size
          }
        end
      end
    end
  end
end