github.com/pf-qiu/concourse/v6@v6.7.3-0.20201207032516-1f455d73275f/atc/api/jobserver/clear_task_cache.go (about)

     1  package jobserver
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  
     8  	"code.cloudfoundry.org/lager"
     9  	"github.com/pf-qiu/concourse/v6/atc"
    10  	"github.com/pf-qiu/concourse/v6/atc/db"
    11  	"github.com/google/jsonapi"
    12  )
    13  
    14  func (s *Server) ClearTaskCache(pipeline db.Pipeline) http.Handler {
    15  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    16  		logger := s.logger.Session("clear-task-cache")
    17  		jobName := r.FormValue(":job_name")
    18  		stepName := r.FormValue(":step_name")
    19  		cachePath := r.FormValue(atc.ClearTaskCacheQueryPath)
    20  
    21  		job, found, err := pipeline.Job(jobName)
    22  		if err != nil {
    23  			logger.Error("failed-to-get-job", err)
    24  			w.WriteHeader(http.StatusInternalServerError)
    25  			return
    26  		}
    27  
    28  		if !found {
    29  			logger.Debug("could-not-find-job", lager.Data{
    30  				"jobName":   jobName,
    31  				"stepName":  stepName,
    32  				"cachePath": cachePath,
    33  			})
    34  			w.Header().Set("Content-Type", jsonapi.MediaType)
    35  			w.WriteHeader(http.StatusNotFound)
    36  			_ = jsonapi.MarshalErrors(w, []*jsonapi.ErrorObject{{
    37  				Title:  "Job Not Found Error",
    38  				Detail: fmt.Sprintf("Job with name '%s' not found.", jobName),
    39  				Status: "404",
    40  			}})
    41  			return
    42  		}
    43  
    44  		rowsDeleted, err := job.ClearTaskCache(stepName, cachePath)
    45  
    46  		if err != nil {
    47  			logger.Error("failed-to-clear-task-cache", err)
    48  			w.Header().Set("Content-Type", jsonapi.MediaType)
    49  			w.WriteHeader(http.StatusInternalServerError)
    50  			_ = jsonapi.MarshalErrors(w, []*jsonapi.ErrorObject{{
    51  				Title:  "Clear Task Cache Error",
    52  				Detail: err.Error(),
    53  				Status: "500",
    54  			}})
    55  			return
    56  		}
    57  
    58  		s.writeJSONResponse(w, atc.ClearTaskCacheResponse{CachesRemoved: rowsDeleted})
    59  	})
    60  }
    61  
    62  func (s *Server) writeJSONResponse(w http.ResponseWriter, obj interface{}) {
    63  	w.Header().Set("Content-Type", "application/json")
    64  	w.WriteHeader(http.StatusOK)
    65  
    66  	responseJSON, err := json.Marshal(obj)
    67  	if err != nil {
    68  		s.logger.Error("failed-to-marshal-response", err)
    69  		w.WriteHeader(http.StatusInternalServerError)
    70  		fmt.Fprintf(w, "failed to generate error response: %s", err)
    71  		return
    72  	}
    73  
    74  	_, err = w.Write(responseJSON)
    75  	if err != nil {
    76  		s.logger.Error("failed-to-write-response", err)
    77  		w.WriteHeader(http.StatusInternalServerError)
    78  		return
    79  	}
    80  
    81  }