repository.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. package client
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "net/url"
  11. "strconv"
  12. "time"
  13. "github.com/docker/distribution"
  14. "github.com/docker/distribution/context"
  15. "github.com/docker/distribution/digest"
  16. "github.com/docker/distribution/reference"
  17. "github.com/docker/distribution/registry/api/v2"
  18. "github.com/docker/distribution/registry/client/transport"
  19. "github.com/docker/distribution/registry/storage/cache"
  20. "github.com/docker/distribution/registry/storage/cache/memory"
  21. )
  22. // Registry provides an interface for calling Repositories, which returns a catalog of repositories.
  23. type Registry interface {
  24. Repositories(ctx context.Context, repos []string, last string) (n int, err error)
  25. }
  26. // checkHTTPRedirect is a callback that can manipulate redirected HTTP
  27. // requests. It is used to preserve Accept and Range headers.
  28. func checkHTTPRedirect(req *http.Request, via []*http.Request) error {
  29. if len(via) >= 10 {
  30. return errors.New("stopped after 10 redirects")
  31. }
  32. if len(via) > 0 {
  33. for headerName, headerVals := range via[0].Header {
  34. if headerName != "Accept" && headerName != "Range" {
  35. continue
  36. }
  37. for _, val := range headerVals {
  38. // Don't add to redirected request if redirected
  39. // request already has a header with the same
  40. // name and value.
  41. hasValue := false
  42. for _, existingVal := range req.Header[headerName] {
  43. if existingVal == val {
  44. hasValue = true
  45. break
  46. }
  47. }
  48. if !hasValue {
  49. req.Header.Add(headerName, val)
  50. }
  51. }
  52. }
  53. }
  54. return nil
  55. }
  56. // NewRegistry creates a registry namespace which can be used to get a listing of repositories
  57. func NewRegistry(ctx context.Context, baseURL string, transport http.RoundTripper) (Registry, error) {
  58. ub, err := v2.NewURLBuilderFromString(baseURL, false)
  59. if err != nil {
  60. return nil, err
  61. }
  62. client := &http.Client{
  63. Transport: transport,
  64. Timeout: 1 * time.Minute,
  65. CheckRedirect: checkHTTPRedirect,
  66. }
  67. return &registry{
  68. client: client,
  69. ub: ub,
  70. context: ctx,
  71. }, nil
  72. }
  73. type registry struct {
  74. client *http.Client
  75. ub *v2.URLBuilder
  76. context context.Context
  77. }
  78. // Repositories returns a lexigraphically sorted catalog given a base URL. The 'entries' slice will be filled up to the size
  79. // of the slice, starting at the value provided in 'last'. The number of entries will be returned along with io.EOF if there
  80. // are no more entries
  81. func (r *registry) Repositories(ctx context.Context, entries []string, last string) (int, error) {
  82. var numFilled int
  83. var returnErr error
  84. values := buildCatalogValues(len(entries), last)
  85. u, err := r.ub.BuildCatalogURL(values)
  86. if err != nil {
  87. return 0, err
  88. }
  89. resp, err := r.client.Get(u)
  90. if err != nil {
  91. return 0, err
  92. }
  93. defer resp.Body.Close()
  94. if SuccessStatus(resp.StatusCode) {
  95. var ctlg struct {
  96. Repositories []string `json:"repositories"`
  97. }
  98. decoder := json.NewDecoder(resp.Body)
  99. if err := decoder.Decode(&ctlg); err != nil {
  100. return 0, err
  101. }
  102. for cnt := range ctlg.Repositories {
  103. entries[cnt] = ctlg.Repositories[cnt]
  104. }
  105. numFilled = len(ctlg.Repositories)
  106. link := resp.Header.Get("Link")
  107. if link == "" {
  108. returnErr = io.EOF
  109. }
  110. } else {
  111. return 0, HandleErrorResponse(resp)
  112. }
  113. return numFilled, returnErr
  114. }
  115. // NewRepository creates a new Repository for the given repository name and base URL.
  116. func NewRepository(ctx context.Context, name reference.Named, baseURL string, transport http.RoundTripper) (distribution.Repository, error) {
  117. ub, err := v2.NewURLBuilderFromString(baseURL, false)
  118. if err != nil {
  119. return nil, err
  120. }
  121. client := &http.Client{
  122. Transport: transport,
  123. CheckRedirect: checkHTTPRedirect,
  124. // TODO(dmcgowan): create cookie jar
  125. }
  126. return &repository{
  127. client: client,
  128. ub: ub,
  129. name: name,
  130. context: ctx,
  131. }, nil
  132. }
  133. type repository struct {
  134. client *http.Client
  135. ub *v2.URLBuilder
  136. context context.Context
  137. name reference.Named
  138. }
  139. func (r *repository) Named() reference.Named {
  140. return r.name
  141. }
  142. func (r *repository) Blobs(ctx context.Context) distribution.BlobStore {
  143. statter := &blobStatter{
  144. name: r.name,
  145. ub: r.ub,
  146. client: r.client,
  147. }
  148. return &blobs{
  149. name: r.name,
  150. ub: r.ub,
  151. client: r.client,
  152. statter: cache.NewCachedBlobStatter(memory.NewInMemoryBlobDescriptorCacheProvider(), statter),
  153. }
  154. }
  155. func (r *repository) Manifests(ctx context.Context, options ...distribution.ManifestServiceOption) (distribution.ManifestService, error) {
  156. // todo(richardscothern): options should be sent over the wire
  157. return &manifests{
  158. name: r.name,
  159. ub: r.ub,
  160. client: r.client,
  161. etags: make(map[string]string),
  162. }, nil
  163. }
  164. func (r *repository) Tags(ctx context.Context) distribution.TagService {
  165. return &tags{
  166. client: r.client,
  167. ub: r.ub,
  168. context: r.context,
  169. name: r.Named(),
  170. }
  171. }
  172. // tags implements remote tagging operations.
  173. type tags struct {
  174. client *http.Client
  175. ub *v2.URLBuilder
  176. context context.Context
  177. name reference.Named
  178. }
  179. // All returns all tags
  180. func (t *tags) All(ctx context.Context) ([]string, error) {
  181. var tags []string
  182. u, err := t.ub.BuildTagsURL(t.name)
  183. if err != nil {
  184. return tags, err
  185. }
  186. resp, err := t.client.Get(u)
  187. if err != nil {
  188. return tags, err
  189. }
  190. defer resp.Body.Close()
  191. if SuccessStatus(resp.StatusCode) {
  192. b, err := ioutil.ReadAll(resp.Body)
  193. if err != nil {
  194. return tags, err
  195. }
  196. tagsResponse := struct {
  197. Tags []string `json:"tags"`
  198. }{}
  199. if err := json.Unmarshal(b, &tagsResponse); err != nil {
  200. return tags, err
  201. }
  202. tags = tagsResponse.Tags
  203. return tags, nil
  204. }
  205. return tags, HandleErrorResponse(resp)
  206. }
  207. func descriptorFromResponse(response *http.Response) (distribution.Descriptor, error) {
  208. desc := distribution.Descriptor{}
  209. headers := response.Header
  210. ctHeader := headers.Get("Content-Type")
  211. if ctHeader == "" {
  212. return distribution.Descriptor{}, errors.New("missing or empty Content-Type header")
  213. }
  214. desc.MediaType = ctHeader
  215. digestHeader := headers.Get("Docker-Content-Digest")
  216. if digestHeader == "" {
  217. bytes, err := ioutil.ReadAll(response.Body)
  218. if err != nil {
  219. return distribution.Descriptor{}, err
  220. }
  221. _, desc, err := distribution.UnmarshalManifest(ctHeader, bytes)
  222. if err != nil {
  223. return distribution.Descriptor{}, err
  224. }
  225. return desc, nil
  226. }
  227. dgst, err := digest.ParseDigest(digestHeader)
  228. if err != nil {
  229. return distribution.Descriptor{}, err
  230. }
  231. desc.Digest = dgst
  232. lengthHeader := headers.Get("Content-Length")
  233. if lengthHeader == "" {
  234. return distribution.Descriptor{}, errors.New("missing or empty Content-Length header")
  235. }
  236. length, err := strconv.ParseInt(lengthHeader, 10, 64)
  237. if err != nil {
  238. return distribution.Descriptor{}, err
  239. }
  240. desc.Size = length
  241. return desc, nil
  242. }
  243. // Get issues a HEAD request for a Manifest against its named endpoint in order
  244. // to construct a descriptor for the tag. If the registry doesn't support HEADing
  245. // a manifest, fallback to GET.
  246. func (t *tags) Get(ctx context.Context, tag string) (distribution.Descriptor, error) {
  247. ref, err := reference.WithTag(t.name, tag)
  248. if err != nil {
  249. return distribution.Descriptor{}, err
  250. }
  251. u, err := t.ub.BuildManifestURL(ref)
  252. if err != nil {
  253. return distribution.Descriptor{}, err
  254. }
  255. req, err := http.NewRequest("HEAD", u, nil)
  256. if err != nil {
  257. return distribution.Descriptor{}, err
  258. }
  259. for _, t := range distribution.ManifestMediaTypes() {
  260. req.Header.Add("Accept", t)
  261. }
  262. var attempts int
  263. resp, err := t.client.Do(req)
  264. check:
  265. if err != nil {
  266. return distribution.Descriptor{}, err
  267. }
  268. defer resp.Body.Close()
  269. switch {
  270. case resp.StatusCode >= 200 && resp.StatusCode < 400:
  271. return descriptorFromResponse(resp)
  272. case resp.StatusCode == http.StatusMethodNotAllowed:
  273. req, err = http.NewRequest("GET", u, nil)
  274. if err != nil {
  275. return distribution.Descriptor{}, err
  276. }
  277. for _, t := range distribution.ManifestMediaTypes() {
  278. req.Header.Add("Accept", t)
  279. }
  280. resp, err = t.client.Do(req)
  281. attempts++
  282. if attempts > 1 {
  283. return distribution.Descriptor{}, err
  284. }
  285. goto check
  286. default:
  287. return distribution.Descriptor{}, HandleErrorResponse(resp)
  288. }
  289. }
  290. func (t *tags) Lookup(ctx context.Context, digest distribution.Descriptor) ([]string, error) {
  291. panic("not implemented")
  292. }
  293. func (t *tags) Tag(ctx context.Context, tag string, desc distribution.Descriptor) error {
  294. panic("not implemented")
  295. }
  296. func (t *tags) Untag(ctx context.Context, tag string) error {
  297. panic("not implemented")
  298. }
  299. type manifests struct {
  300. name reference.Named
  301. ub *v2.URLBuilder
  302. client *http.Client
  303. etags map[string]string
  304. }
  305. func (ms *manifests) Exists(ctx context.Context, dgst digest.Digest) (bool, error) {
  306. ref, err := reference.WithDigest(ms.name, dgst)
  307. if err != nil {
  308. return false, err
  309. }
  310. u, err := ms.ub.BuildManifestURL(ref)
  311. if err != nil {
  312. return false, err
  313. }
  314. resp, err := ms.client.Head(u)
  315. if err != nil {
  316. return false, err
  317. }
  318. if SuccessStatus(resp.StatusCode) {
  319. return true, nil
  320. } else if resp.StatusCode == http.StatusNotFound {
  321. return false, nil
  322. }
  323. return false, HandleErrorResponse(resp)
  324. }
  325. // AddEtagToTag allows a client to supply an eTag to Get which will be
  326. // used for a conditional HTTP request. If the eTag matches, a nil manifest
  327. // and ErrManifestNotModified error will be returned. etag is automatically
  328. // quoted when added to this map.
  329. func AddEtagToTag(tag, etag string) distribution.ManifestServiceOption {
  330. return etagOption{tag, etag}
  331. }
  332. type etagOption struct{ tag, etag string }
  333. func (o etagOption) Apply(ms distribution.ManifestService) error {
  334. if ms, ok := ms.(*manifests); ok {
  335. ms.etags[o.tag] = fmt.Sprintf(`"%s"`, o.etag)
  336. return nil
  337. }
  338. return fmt.Errorf("etag options is a client-only option")
  339. }
  340. func (ms *manifests) Get(ctx context.Context, dgst digest.Digest, options ...distribution.ManifestServiceOption) (distribution.Manifest, error) {
  341. var (
  342. digestOrTag string
  343. ref reference.Named
  344. err error
  345. )
  346. for _, option := range options {
  347. if opt, ok := option.(distribution.WithTagOption); ok {
  348. digestOrTag = opt.Tag
  349. ref, err = reference.WithTag(ms.name, opt.Tag)
  350. if err != nil {
  351. return nil, err
  352. }
  353. } else {
  354. err := option.Apply(ms)
  355. if err != nil {
  356. return nil, err
  357. }
  358. }
  359. }
  360. if digestOrTag == "" {
  361. digestOrTag = dgst.String()
  362. ref, err = reference.WithDigest(ms.name, dgst)
  363. if err != nil {
  364. return nil, err
  365. }
  366. }
  367. u, err := ms.ub.BuildManifestURL(ref)
  368. if err != nil {
  369. return nil, err
  370. }
  371. req, err := http.NewRequest("GET", u, nil)
  372. if err != nil {
  373. return nil, err
  374. }
  375. for _, t := range distribution.ManifestMediaTypes() {
  376. req.Header.Add("Accept", t)
  377. }
  378. if _, ok := ms.etags[digestOrTag]; ok {
  379. req.Header.Set("If-None-Match", ms.etags[digestOrTag])
  380. }
  381. resp, err := ms.client.Do(req)
  382. if err != nil {
  383. return nil, err
  384. }
  385. defer resp.Body.Close()
  386. if resp.StatusCode == http.StatusNotModified {
  387. return nil, distribution.ErrManifestNotModified
  388. } else if SuccessStatus(resp.StatusCode) {
  389. mt := resp.Header.Get("Content-Type")
  390. body, err := ioutil.ReadAll(resp.Body)
  391. if err != nil {
  392. return nil, err
  393. }
  394. m, _, err := distribution.UnmarshalManifest(mt, body)
  395. if err != nil {
  396. return nil, err
  397. }
  398. return m, nil
  399. }
  400. return nil, HandleErrorResponse(resp)
  401. }
  402. // Put puts a manifest. A tag can be specified using an options parameter which uses some shared state to hold the
  403. // tag name in order to build the correct upload URL.
  404. func (ms *manifests) Put(ctx context.Context, m distribution.Manifest, options ...distribution.ManifestServiceOption) (digest.Digest, error) {
  405. ref := ms.name
  406. var tagged bool
  407. for _, option := range options {
  408. if opt, ok := option.(distribution.WithTagOption); ok {
  409. var err error
  410. ref, err = reference.WithTag(ref, opt.Tag)
  411. if err != nil {
  412. return "", err
  413. }
  414. tagged = true
  415. } else {
  416. err := option.Apply(ms)
  417. if err != nil {
  418. return "", err
  419. }
  420. }
  421. }
  422. mediaType, p, err := m.Payload()
  423. if err != nil {
  424. return "", err
  425. }
  426. if !tagged {
  427. // generate a canonical digest and Put by digest
  428. _, d, err := distribution.UnmarshalManifest(mediaType, p)
  429. if err != nil {
  430. return "", err
  431. }
  432. ref, err = reference.WithDigest(ref, d.Digest)
  433. if err != nil {
  434. return "", err
  435. }
  436. }
  437. manifestURL, err := ms.ub.BuildManifestURL(ref)
  438. if err != nil {
  439. return "", err
  440. }
  441. putRequest, err := http.NewRequest("PUT", manifestURL, bytes.NewReader(p))
  442. if err != nil {
  443. return "", err
  444. }
  445. putRequest.Header.Set("Content-Type", mediaType)
  446. resp, err := ms.client.Do(putRequest)
  447. if err != nil {
  448. return "", err
  449. }
  450. defer resp.Body.Close()
  451. if SuccessStatus(resp.StatusCode) {
  452. dgstHeader := resp.Header.Get("Docker-Content-Digest")
  453. dgst, err := digest.ParseDigest(dgstHeader)
  454. if err != nil {
  455. return "", err
  456. }
  457. return dgst, nil
  458. }
  459. return "", HandleErrorResponse(resp)
  460. }
  461. func (ms *manifests) Delete(ctx context.Context, dgst digest.Digest) error {
  462. ref, err := reference.WithDigest(ms.name, dgst)
  463. if err != nil {
  464. return err
  465. }
  466. u, err := ms.ub.BuildManifestURL(ref)
  467. if err != nil {
  468. return err
  469. }
  470. req, err := http.NewRequest("DELETE", u, nil)
  471. if err != nil {
  472. return err
  473. }
  474. resp, err := ms.client.Do(req)
  475. if err != nil {
  476. return err
  477. }
  478. defer resp.Body.Close()
  479. if SuccessStatus(resp.StatusCode) {
  480. return nil
  481. }
  482. return HandleErrorResponse(resp)
  483. }
  484. // todo(richardscothern): Restore interface and implementation with merge of #1050
  485. /*func (ms *manifests) Enumerate(ctx context.Context, manifests []distribution.Manifest, last distribution.Manifest) (n int, err error) {
  486. panic("not supported")
  487. }*/
  488. type blobs struct {
  489. name reference.Named
  490. ub *v2.URLBuilder
  491. client *http.Client
  492. statter distribution.BlobDescriptorService
  493. distribution.BlobDeleter
  494. }
  495. func sanitizeLocation(location, base string) (string, error) {
  496. baseURL, err := url.Parse(base)
  497. if err != nil {
  498. return "", err
  499. }
  500. locationURL, err := url.Parse(location)
  501. if err != nil {
  502. return "", err
  503. }
  504. return baseURL.ResolveReference(locationURL).String(), nil
  505. }
  506. func (bs *blobs) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
  507. return bs.statter.Stat(ctx, dgst)
  508. }
  509. func (bs *blobs) Get(ctx context.Context, dgst digest.Digest) ([]byte, error) {
  510. reader, err := bs.Open(ctx, dgst)
  511. if err != nil {
  512. return nil, err
  513. }
  514. defer reader.Close()
  515. return ioutil.ReadAll(reader)
  516. }
  517. func (bs *blobs) Open(ctx context.Context, dgst digest.Digest) (distribution.ReadSeekCloser, error) {
  518. ref, err := reference.WithDigest(bs.name, dgst)
  519. if err != nil {
  520. return nil, err
  521. }
  522. blobURL, err := bs.ub.BuildBlobURL(ref)
  523. if err != nil {
  524. return nil, err
  525. }
  526. return transport.NewHTTPReadSeeker(bs.client, blobURL,
  527. func(resp *http.Response) error {
  528. if resp.StatusCode == http.StatusNotFound {
  529. return distribution.ErrBlobUnknown
  530. }
  531. return HandleErrorResponse(resp)
  532. }), nil
  533. }
  534. func (bs *blobs) ServeBlob(ctx context.Context, w http.ResponseWriter, r *http.Request, dgst digest.Digest) error {
  535. panic("not implemented")
  536. }
  537. func (bs *blobs) Put(ctx context.Context, mediaType string, p []byte) (distribution.Descriptor, error) {
  538. writer, err := bs.Create(ctx)
  539. if err != nil {
  540. return distribution.Descriptor{}, err
  541. }
  542. dgstr := digest.Canonical.New()
  543. n, err := io.Copy(writer, io.TeeReader(bytes.NewReader(p), dgstr.Hash()))
  544. if err != nil {
  545. return distribution.Descriptor{}, err
  546. }
  547. if n < int64(len(p)) {
  548. return distribution.Descriptor{}, fmt.Errorf("short copy: wrote %d of %d", n, len(p))
  549. }
  550. desc := distribution.Descriptor{
  551. MediaType: mediaType,
  552. Size: int64(len(p)),
  553. Digest: dgstr.Digest(),
  554. }
  555. return writer.Commit(ctx, desc)
  556. }
  557. // createOptions is a collection of blob creation modifiers relevant to general
  558. // blob storage intended to be configured by the BlobCreateOption.Apply method.
  559. type createOptions struct {
  560. Mount struct {
  561. ShouldMount bool
  562. From reference.Canonical
  563. }
  564. }
  565. type optionFunc func(interface{}) error
  566. func (f optionFunc) Apply(v interface{}) error {
  567. return f(v)
  568. }
  569. // WithMountFrom returns a BlobCreateOption which designates that the blob should be
  570. // mounted from the given canonical reference.
  571. func WithMountFrom(ref reference.Canonical) distribution.BlobCreateOption {
  572. return optionFunc(func(v interface{}) error {
  573. opts, ok := v.(*createOptions)
  574. if !ok {
  575. return fmt.Errorf("unexpected options type: %T", v)
  576. }
  577. opts.Mount.ShouldMount = true
  578. opts.Mount.From = ref
  579. return nil
  580. })
  581. }
  582. func (bs *blobs) Create(ctx context.Context, options ...distribution.BlobCreateOption) (distribution.BlobWriter, error) {
  583. var opts createOptions
  584. for _, option := range options {
  585. err := option.Apply(&opts)
  586. if err != nil {
  587. return nil, err
  588. }
  589. }
  590. var values []url.Values
  591. if opts.Mount.ShouldMount {
  592. values = append(values, url.Values{"from": {opts.Mount.From.Name()}, "mount": {opts.Mount.From.Digest().String()}})
  593. }
  594. u, err := bs.ub.BuildBlobUploadURL(bs.name, values...)
  595. if err != nil {
  596. return nil, err
  597. }
  598. resp, err := bs.client.Post(u, "", nil)
  599. if err != nil {
  600. return nil, err
  601. }
  602. defer resp.Body.Close()
  603. switch resp.StatusCode {
  604. case http.StatusCreated:
  605. desc, err := bs.statter.Stat(ctx, opts.Mount.From.Digest())
  606. if err != nil {
  607. return nil, err
  608. }
  609. return nil, distribution.ErrBlobMounted{From: opts.Mount.From, Descriptor: desc}
  610. case http.StatusAccepted:
  611. // TODO(dmcgowan): Check for invalid UUID
  612. uuid := resp.Header.Get("Docker-Upload-UUID")
  613. location, err := sanitizeLocation(resp.Header.Get("Location"), u)
  614. if err != nil {
  615. return nil, err
  616. }
  617. return &httpBlobUpload{
  618. statter: bs.statter,
  619. client: bs.client,
  620. uuid: uuid,
  621. startedAt: time.Now(),
  622. location: location,
  623. }, nil
  624. default:
  625. return nil, HandleErrorResponse(resp)
  626. }
  627. }
  628. func (bs *blobs) Resume(ctx context.Context, id string) (distribution.BlobWriter, error) {
  629. panic("not implemented")
  630. }
  631. func (bs *blobs) Delete(ctx context.Context, dgst digest.Digest) error {
  632. return bs.statter.Clear(ctx, dgst)
  633. }
  634. type blobStatter struct {
  635. name reference.Named
  636. ub *v2.URLBuilder
  637. client *http.Client
  638. }
  639. func (bs *blobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
  640. ref, err := reference.WithDigest(bs.name, dgst)
  641. if err != nil {
  642. return distribution.Descriptor{}, err
  643. }
  644. u, err := bs.ub.BuildBlobURL(ref)
  645. if err != nil {
  646. return distribution.Descriptor{}, err
  647. }
  648. resp, err := bs.client.Head(u)
  649. if err != nil {
  650. return distribution.Descriptor{}, err
  651. }
  652. defer resp.Body.Close()
  653. if SuccessStatus(resp.StatusCode) {
  654. lengthHeader := resp.Header.Get("Content-Length")
  655. if lengthHeader == "" {
  656. return distribution.Descriptor{}, fmt.Errorf("missing content-length header for request: %s", u)
  657. }
  658. length, err := strconv.ParseInt(lengthHeader, 10, 64)
  659. if err != nil {
  660. return distribution.Descriptor{}, fmt.Errorf("error parsing content-length: %v", err)
  661. }
  662. return distribution.Descriptor{
  663. MediaType: resp.Header.Get("Content-Type"),
  664. Size: length,
  665. Digest: dgst,
  666. }, nil
  667. } else if resp.StatusCode == http.StatusNotFound {
  668. return distribution.Descriptor{}, distribution.ErrBlobUnknown
  669. }
  670. return distribution.Descriptor{}, HandleErrorResponse(resp)
  671. }
  672. func buildCatalogValues(maxEntries int, last string) url.Values {
  673. values := url.Values{}
  674. if maxEntries > 0 {
  675. values.Add("n", strconv.Itoa(maxEntries))
  676. }
  677. if last != "" {
  678. values.Add("last", last)
  679. }
  680. return values
  681. }
  682. func (bs *blobStatter) Clear(ctx context.Context, dgst digest.Digest) error {
  683. ref, err := reference.WithDigest(bs.name, dgst)
  684. if err != nil {
  685. return err
  686. }
  687. blobURL, err := bs.ub.BuildBlobURL(ref)
  688. if err != nil {
  689. return err
  690. }
  691. req, err := http.NewRequest("DELETE", blobURL, nil)
  692. if err != nil {
  693. return err
  694. }
  695. resp, err := bs.client.Do(req)
  696. if err != nil {
  697. return err
  698. }
  699. defer resp.Body.Close()
  700. if SuccessStatus(resp.StatusCode) {
  701. return nil
  702. }
  703. return HandleErrorResponse(resp)
  704. }
  705. func (bs *blobStatter) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error {
  706. return nil
  707. }