Project

General

Profile

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

foreman_docker / app / controllers / image_search_controller.rb @ 367f39d2

1
class ImageSearchController < ::ApplicationController
2
  def auto_complete_repository_name
3
    catch_network_errors do
4
      available = image_search_service.available?(params[:search])
5
      render :text => available.to_s
6
    end
7
  end
8

    
9
  def auto_complete_image_tag
10
    catch_network_errors do
11
      tags = image_search_service.search({
12
        term: params[:search],
13
        tags: 'true'
14
      })
15

    
16
      respond_to do |format|
17
        format.js do
18
          render :json => prepare_for_autocomplete(tags)
19
        end
20
      end
21
    end
22
  end
23

    
24
  def search_repository
25
    catch_network_errors do
26
      repositories = image_search_service.search({
27
        term: params[:search].split(':').first,
28
        tags: 'false'
29
      })
30

    
31
      respond_to do |format|
32
        format.js do
33
          render :partial => 'repository_search_results',
34
                 :locals  => { :repositories => repositories,
35
                               :use_hub => use_hub? }
36
        end
37
      end
38
    end
39
  end
40

    
41
  private
42

    
43
  def catch_network_errors
44
    yield
45
  rescue Docker::Error::NotFoundError => e
46
    # not an error
47
    logger.debug "image not found: #{e.backtrace}"
48
    render :js, :nothing => true
49
  rescue Docker::Error::DockerError, Excon::Errors::Error, SystemCallError => e
50
    render :js => _("An error occured during repository search: '%s'") % e.message,
51
           :status => 500
52
  end
53

    
54
  def use_hub?
55
    @registry.nil?
56
  end
57

    
58
  def action_permission
59
    case params[:action]
60
    when 'auto_complete_repository_name', 'auto_complete_image_tag', 'search_repository'
61
      :search_repository
62
    else
63
      super
64
    end
65
  end
66

    
67
  # This is the format jQuery UI autocomplete expects
68
  def prepare_for_autocomplete(tags)
69
    tags.map do |tag|
70
      tag = tag.is_a?(Hash) ? tag.fetch('name', tag) : tag
71
      tag = CGI.escapeHTML(tag)
72
      { :label => tag, :value => tag }
73
    end
74
  end
75

    
76
  def image_search_service
77
    @image_search_service ||= ForemanDocker::ImageSearch.new(*sources)
78
  end
79

    
80
  def sources
81
    if params[:registry] == 'hub'
82
      @registry ||= Service::RegistryApi.docker_hub
83
      @compute_resource ||= ComputeResource.authorized(:view_compute_resources).find(params[:id])
84
      [@registry, @compute_resource]
85
    elsif params[:registry] == 'registry' && params[:registry_id].present?
86
      @registry ||= DockerRegistry.authorized(:view_registries)
87
        .find(params[:registry_id]).api
88
      [@registry]
89
    end
90
  end
91
end