service.go 11 KB

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