Project

General

Profile

Download (2.16 KB) Statistics
| Branch: | Tag: | Revision:

foreman-docker / app / services / foreman_docker / image_search.rb @ f02a9ce2

1
module ForemanDocker
2
  class ImageSearch
3
    def initialize(*args)
4
      @sources = {}
5
      args.each do |source|
6
        add_source(source)
7
      end
8
    end
9

    
10
    def add_source(source)
11
      case source
12
      when ForemanDocker::Docker
13
        @sources[:compute_resource] ||= []
14
        @sources[:compute_resource] << source
15
      when Service::RegistryApi
16
        @sources[:registry] ||= []
17
        @sources[:registry] << source
18
      end
19
    end
20

    
21
    def remove_source(source)
22
      @sources.each do |_, sources|
23
        sources.delete(source)
24
      end
25
    end
26

    
27
    def search(query)
28
      return [] if query[:term].blank? || query[:term] == ':'
29

    
30
      unless query[:tags] == 'true'
31
        images(query[:term])
32
      else
33
        tags(query[:term])
34
      end
35
    end
36

    
37
    def images(query)
38
      sources_results_for(:search, query)
39
    end
40

    
41
    def tags(query)
42
      image_name, tag = query.split(':')
43
      sources_results_for(:tags, image_name, tag)
44
        .map { |tag_name| { 'name' => tag_name } }
45
    end
46

    
47
    def available?(query)
48
      tags(query).present?
49
    end
50

    
51
    private
52

    
53
    def registry_search(registry, term)
54
      registry.search(term)['results']
55
    end
56

    
57
    def compute_resource_search(compute_resource, query)
58
      images = compute_resource.local_images(query)
59
      images.flat_map do |image|
60
        image.info['RepoTags'].map do |tag|
61
          { 'name' => tag.split(':').first }
62
        end
63
      end.uniq
64
    end
65

    
66
    def compute_resource_image(compute_resource, image_name)
67
      compute_resource.image(image_name)
68
    rescue ::Docker::Error::NotFoundError
69
      nil
70
    end
71

    
72
    def compute_resource_tags(compute_resource, image_name, tag)
73
      image = compute_resource_image(compute_resource, image_name)
74
      image ? compute_resource.tags_for_local_image(image, tag) : []
75
    end
76

    
77
    def registry_tags(registry, image_name, tag)
78
      registry.tags(image_name, tag).map { |t| t['name'] }
79
    end
80

    
81
    def sources_results_for(search, *args)
82
      result = []
83
      @sources.each do |kind, sources|
84
        sources.each do |source|
85
          result << self.send("#{kind}_#{search}", source, *args)
86
        end
87
      end
88
      result.flatten.compact
89
    end
90
  end
91
end
92