service.go 9.3 KB

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