service.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. package registry
  2. import (
  3. "crypto/tls"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "strings"
  8. "sync"
  9. "golang.org/x/net/context"
  10. "github.com/Sirupsen/logrus"
  11. "github.com/docker/distribution/reference"
  12. "github.com/docker/distribution/registry/client/auth"
  13. "github.com/docker/docker/api/types"
  14. registrytypes "github.com/docker/docker/api/types/registry"
  15. )
  16. const (
  17. // DefaultSearchLimit is the default value for maximum number of returned search results.
  18. DefaultSearchLimit = 25
  19. )
  20. // Service is the interface defining what a registry service should implement.
  21. type Service interface {
  22. Auth(ctx context.Context, authConfig *types.AuthConfig, userAgent string) (status, token string, err error)
  23. LookupPullEndpoints(hostname string) (endpoints []APIEndpoint, err error)
  24. LookupPushEndpoints(hostname string) (endpoints []APIEndpoint, err error)
  25. ResolveRepository(name reference.Named) (*RepositoryInfo, error)
  26. Search(ctx context.Context, term string, limit int, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error)
  27. ServiceConfig() *registrytypes.ServiceConfig
  28. TLSConfig(hostname string) (*tls.Config, error)
  29. LoadMirrors([]string) error
  30. LoadInsecureRegistries([]string) error
  31. }
  32. // DefaultService is a registry service. It tracks configuration data such as a list
  33. // of mirrors.
  34. type DefaultService struct {
  35. config *serviceConfig
  36. mu sync.Mutex
  37. }
  38. // NewService returns a new instance of DefaultService ready to be
  39. // installed into an engine.
  40. func NewService(options ServiceOptions) *DefaultService {
  41. return &DefaultService{
  42. config: newServiceConfig(options),
  43. }
  44. }
  45. // ServiceConfig returns the public registry service configuration.
  46. func (s *DefaultService) ServiceConfig() *registrytypes.ServiceConfig {
  47. s.mu.Lock()
  48. defer s.mu.Unlock()
  49. servConfig := registrytypes.ServiceConfig{
  50. InsecureRegistryCIDRs: make([]*(registrytypes.NetIPNet), 0),
  51. IndexConfigs: make(map[string]*(registrytypes.IndexInfo)),
  52. Mirrors: make([]string, 0),
  53. }
  54. // construct a new ServiceConfig which will not retrieve s.Config directly,
  55. // and look up items in s.config with mu locked
  56. servConfig.InsecureRegistryCIDRs = append(servConfig.InsecureRegistryCIDRs, s.config.ServiceConfig.InsecureRegistryCIDRs...)
  57. for key, value := range s.config.ServiceConfig.IndexConfigs {
  58. servConfig.IndexConfigs[key] = value
  59. }
  60. servConfig.Mirrors = append(servConfig.Mirrors, s.config.ServiceConfig.Mirrors...)
  61. return &servConfig
  62. }
  63. // LoadMirrors loads registry mirrors for Service
  64. func (s *DefaultService) LoadMirrors(mirrors []string) error {
  65. s.mu.Lock()
  66. defer s.mu.Unlock()
  67. return s.config.LoadMirrors(mirrors)
  68. }
  69. // LoadInsecureRegistries loads insecure registries for Service
  70. func (s *DefaultService) LoadInsecureRegistries(registries []string) error {
  71. s.mu.Lock()
  72. defer s.mu.Unlock()
  73. return s.config.LoadInsecureRegistries(registries)
  74. }
  75. // Auth contacts the public registry with the provided credentials,
  76. // and returns OK if authentication was successful.
  77. // It can be used to verify the validity of a client's credentials.
  78. func (s *DefaultService) Auth(ctx context.Context, authConfig *types.AuthConfig, userAgent string) (status, token string, err error) {
  79. // TODO Use ctx when searching for repositories
  80. serverAddress := authConfig.ServerAddress
  81. if serverAddress == "" {
  82. serverAddress = IndexServer
  83. }
  84. if !strings.HasPrefix(serverAddress, "https://") && !strings.HasPrefix(serverAddress, "http://") {
  85. serverAddress = "https://" + serverAddress
  86. }
  87. u, err := url.Parse(serverAddress)
  88. if err != nil {
  89. return "", "", fmt.Errorf("unable to parse server address: %v", err)
  90. }
  91. endpoints, err := s.LookupPushEndpoints(u.Host)
  92. if err != nil {
  93. return "", "", err
  94. }
  95. for _, endpoint := range endpoints {
  96. login := loginV2
  97. if endpoint.Version == APIVersion1 {
  98. login = loginV1
  99. }
  100. status, token, err = login(authConfig, endpoint, userAgent)
  101. if err == nil {
  102. return
  103. }
  104. if fErr, ok := err.(fallbackError); ok {
  105. err = fErr.err
  106. logrus.Infof("Error logging in to %s endpoint, trying next endpoint: %v", endpoint.Version, err)
  107. continue
  108. }
  109. return "", "", err
  110. }
  111. return "", "", err
  112. }
  113. // splitReposSearchTerm breaks a search term into an index name and remote name
  114. func splitReposSearchTerm(reposName string) (string, string) {
  115. nameParts := strings.SplitN(reposName, "/", 2)
  116. var indexName, remoteName string
  117. if len(nameParts) == 1 || (!strings.Contains(nameParts[0], ".") &&
  118. !strings.Contains(nameParts[0], ":") && nameParts[0] != "localhost") {
  119. // This is a Docker Index repos (ex: samalba/hipache or ubuntu)
  120. // 'docker.io'
  121. indexName = IndexName
  122. remoteName = reposName
  123. } else {
  124. indexName = nameParts[0]
  125. remoteName = nameParts[1]
  126. }
  127. return indexName, remoteName
  128. }
  129. // Search queries the public registry for images matching the specified
  130. // search terms, and returns the results.
  131. func (s *DefaultService) Search(ctx context.Context, term string, limit int, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) {
  132. // TODO Use ctx when searching for repositories
  133. if err := validateNoScheme(term); err != nil {
  134. return nil, err
  135. }
  136. indexName, remoteName := splitReposSearchTerm(term)
  137. // Search is a long-running operation, just lock s.config to avoid block others.
  138. s.mu.Lock()
  139. index, err := newIndexInfo(s.config, indexName)
  140. s.mu.Unlock()
  141. if err != nil {
  142. return nil, err
  143. }
  144. // *TODO: Search multiple indexes.
  145. endpoint, err := NewV1Endpoint(index, userAgent, http.Header(headers))
  146. if err != nil {
  147. return nil, err
  148. }
  149. var client *http.Client
  150. if authConfig != nil && authConfig.IdentityToken != "" && authConfig.Username != "" {
  151. creds := NewStaticCredentialStore(authConfig)
  152. scopes := []auth.Scope{
  153. auth.RegistryScope{
  154. Name: "catalog",
  155. Actions: []string{"search"},
  156. },
  157. }
  158. modifiers := DockerHeaders(userAgent, nil)
  159. v2Client, foundV2, err := v2AuthHTTPClient(endpoint.URL, endpoint.client.Transport, modifiers, creds, scopes)
  160. if err != nil {
  161. if fErr, ok := err.(fallbackError); ok {
  162. logrus.Errorf("Cannot use identity token for search, v2 auth not supported: %v", fErr.err)
  163. } else {
  164. return nil, err
  165. }
  166. } else if foundV2 {
  167. // Copy non transport http client features
  168. v2Client.Timeout = endpoint.client.Timeout
  169. v2Client.CheckRedirect = endpoint.client.CheckRedirect
  170. v2Client.Jar = endpoint.client.Jar
  171. logrus.Debugf("using v2 client for search to %s", endpoint.URL)
  172. client = v2Client
  173. }
  174. }
  175. if client == nil {
  176. client = endpoint.client
  177. if err := authorizeClient(client, authConfig, endpoint); err != nil {
  178. return nil, err
  179. }
  180. }
  181. r := newSession(client, authConfig, endpoint)
  182. if index.Official {
  183. localName := remoteName
  184. if strings.HasPrefix(localName, "library/") {
  185. // If pull "library/foo", it's stored locally under "foo"
  186. localName = strings.SplitN(localName, "/", 2)[1]
  187. }
  188. return r.SearchRepositories(localName, limit)
  189. }
  190. return r.SearchRepositories(remoteName, limit)
  191. }
  192. // ResolveRepository splits a repository name into its components
  193. // and configuration of the associated registry.
  194. func (s *DefaultService) ResolveRepository(name reference.Named) (*RepositoryInfo, error) {
  195. s.mu.Lock()
  196. defer s.mu.Unlock()
  197. return newRepositoryInfo(s.config, name)
  198. }
  199. // APIEndpoint represents a remote API endpoint
  200. type APIEndpoint struct {
  201. Mirror bool
  202. URL *url.URL
  203. Version APIVersion
  204. Official bool
  205. TrimHostname bool
  206. TLSConfig *tls.Config
  207. }
  208. // ToV1Endpoint returns a V1 API endpoint based on the APIEndpoint
  209. func (e APIEndpoint) ToV1Endpoint(userAgent string, metaHeaders http.Header) (*V1Endpoint, error) {
  210. return newV1Endpoint(*e.URL, e.TLSConfig, userAgent, metaHeaders)
  211. }
  212. // TLSConfig constructs a client TLS configuration based on server defaults
  213. func (s *DefaultService) TLSConfig(hostname string) (*tls.Config, error) {
  214. s.mu.Lock()
  215. defer s.mu.Unlock()
  216. return newTLSConfig(hostname, isSecureIndex(s.config, hostname))
  217. }
  218. // tlsConfig constructs a client TLS configuration based on server defaults
  219. func (s *DefaultService) tlsConfig(hostname string) (*tls.Config, error) {
  220. return newTLSConfig(hostname, isSecureIndex(s.config, hostname))
  221. }
  222. func (s *DefaultService) tlsConfigForMirror(mirrorURL *url.URL) (*tls.Config, error) {
  223. return s.tlsConfig(mirrorURL.Host)
  224. }
  225. // LookupPullEndpoints creates a list of endpoints to try to pull from, in order of preference.
  226. // It gives preference to v2 endpoints over v1, mirrors over the actual
  227. // registry, and HTTPS over plain HTTP.
  228. func (s *DefaultService) LookupPullEndpoints(hostname string) (endpoints []APIEndpoint, err error) {
  229. s.mu.Lock()
  230. defer s.mu.Unlock()
  231. return s.lookupEndpoints(hostname)
  232. }
  233. // LookupPushEndpoints creates a list of endpoints to try to push to, in order of preference.
  234. // It gives preference to v2 endpoints over v1, and HTTPS over plain HTTP.
  235. // Mirrors are not included.
  236. func (s *DefaultService) LookupPushEndpoints(hostname string) (endpoints []APIEndpoint, err error) {
  237. s.mu.Lock()
  238. defer s.mu.Unlock()
  239. allEndpoints, err := s.lookupEndpoints(hostname)
  240. if err == nil {
  241. for _, endpoint := range allEndpoints {
  242. if !endpoint.Mirror {
  243. endpoints = append(endpoints, endpoint)
  244. }
  245. }
  246. }
  247. return endpoints, err
  248. }
  249. func (s *DefaultService) lookupEndpoints(hostname string) (endpoints []APIEndpoint, err error) {
  250. endpoints, err = s.lookupV2Endpoints(hostname)
  251. if err != nil {
  252. return nil, err
  253. }
  254. if s.config.V2Only {
  255. return endpoints, nil
  256. }
  257. legacyEndpoints, err := s.lookupV1Endpoints(hostname)
  258. if err != nil {
  259. return nil, err
  260. }
  261. endpoints = append(endpoints, legacyEndpoints...)
  262. return endpoints, nil
  263. }