1package artifactserver
2
3import (
4	"io"
5	"net/http"
6	"strconv"
7
8	"github.com/concourse/baggageclaim"
9	"github.com/concourse/concourse/atc/db"
10)
11
12func (s *Server) GetArtifact(team db.Team) http.Handler {
13	logger := s.logger.Session("get-artifact")
14
15	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
16
17		w.Header().Set("Content-Type", "application/octet-stream")
18
19		artifactID, err := strconv.Atoi(r.FormValue(":artifact_id"))
20		if err != nil {
21			logger.Error("failed-to-get-artifact-id", err)
22			w.WriteHeader(http.StatusInternalServerError)
23			return
24		}
25
26		artifactVolume, found, err := team.FindVolumeForWorkerArtifact(artifactID)
27		if err != nil {
28			logger.Error("failed-to-get-artifact-volume", err)
29			w.WriteHeader(http.StatusInternalServerError)
30			return
31		}
32
33		if !found {
34			logger.Error("failed-to-find-artifact-volume", err)
35			w.WriteHeader(http.StatusNotFound)
36			return
37		}
38
39		workerVolume, found, err := s.workerClient.FindVolume(logger, team.ID(), artifactVolume.Handle())
40		if err != nil {
41			logger.Error("failed-to-get-worker-volume", err)
42			w.WriteHeader(http.StatusInternalServerError)
43			return
44		}
45
46		if !found {
47			logger.Error("failed-to-find-worker-volume", err)
48			w.WriteHeader(http.StatusNotFound)
49			return
50		}
51
52		reader, err := workerVolume.StreamOut(r.Context(), "/", baggageclaim.GzipEncoding)
53		if err != nil {
54			logger.Error("failed-to-stream-volume-contents", err)
55			w.WriteHeader(http.StatusInternalServerError)
56			return
57		}
58
59		defer reader.Close()
60
61		_, err = io.Copy(w, reader)
62		if err != nil {
63			logger.Error("failed-to-encode-artifact", err)
64		}
65	})
66}
67