Rename Config to Server and use singular one in main

This commit is contained in:
Matthew Holt 2018-04-15 08:31:50 -06:00
parent b98c171644
commit df3b6aa1cf
5 changed files with 164 additions and 185 deletions

View file

@ -25,36 +25,30 @@ var cmdRoot = &cobra.Command{
//Version: fmt.Sprintf("rest-server %s compiled with %v on %v/%v\n", version, runtime.Version(), runtime.GOOS, runtime.GOARCH), //Version: fmt.Sprintf("rest-server %s compiled with %v on %v/%v\n", version, runtime.Version(), runtime.GOOS, runtime.GOARCH),
} }
var server = restserver.Server{
Path: "/tmp/restic",
Listen: ":8000",
}
var ( var (
repoPath = "/tmp/restic" showVersion bool
listen = ":8000" cpuProfile string
logFile string
cpuProfile string
tlsKey string
tlsCert string
useTLS bool
noAuth bool
appendOnly bool
privateRepos bool
prometheus bool
debug bool
showVersion bool
) )
func init() { func init() {
flags := cmdRoot.Flags() flags := cmdRoot.Flags()
flags.StringVar(&cpuProfile, "cpu-profile", cpuProfile, "write CPU profile to file") flags.StringVar(&cpuProfile, "cpu-profile", cpuProfile, "write CPU profile to file")
flags.BoolVar(&debug, "debug", debug, "output debug messages") flags.BoolVar(&server.Debug, "debug", server.Debug, "output debug messages")
flags.StringVar(&listen, "listen", listen, "listen address") flags.StringVar(&server.Listen, "listen", server.Listen, "listen address")
flags.StringVar(&logFile, "log", logFile, "log HTTP requests in the combined log format") flags.StringVar(&server.Log, "log", server.Log, "log HTTP requests in the combined log format")
flags.StringVar(&repoPath, "path", repoPath, "data directory") flags.StringVar(&server.Path, "path", server.Path, "data directory")
flags.BoolVar(&useTLS, "tls", useTLS, "turn on TLS support") flags.BoolVar(&server.TLS, "tls", server.TLS, "turn on TLS support")
flags.StringVar(&tlsCert, "tls-cert", tlsCert, "TLS certificate path") flags.StringVar(&server.TLSCert, "tls-cert", server.TLSCert, "TLS certificate path")
flags.StringVar(&tlsKey, "tls-key", tlsKey, "TLS key path") flags.StringVar(&server.TLSKey, "tls-key", server.TLSKey, "TLS key path")
flags.BoolVar(&noAuth, "no-auth", noAuth, "disable .htpasswd authentication") flags.BoolVar(&server.NoAuth, "no-auth", server.NoAuth, "disable .htpasswd authentication")
flags.BoolVar(&appendOnly, "append-only", appendOnly, "enable append only mode") flags.BoolVar(&server.AppendOnly, "append-only", server.AppendOnly, "enable append only mode")
flags.BoolVar(&privateRepos, "private-repos", privateRepos, "users can only access their private repo") flags.BoolVar(&server.PrivateRepos, "private-repos", server.PrivateRepos, "users can only access their private repo")
flags.BoolVar(&prometheus, "prometheus", prometheus, "enable Prometheus metrics") flags.BoolVar(&server.Prometheus, "prometheus", server.Prometheus, "enable Prometheus metrics")
flags.BoolVarP(&showVersion, "version", "V", showVersion, "output version and exit") flags.BoolVarP(&showVersion, "version", "V", showVersion, "output version and exit")
} }
@ -62,37 +56,37 @@ var version = "manually"
func tlsSettings() (bool, string, string, error) { func tlsSettings() (bool, string, string, error) {
var key, cert string var key, cert string
if !useTLS && (tlsKey != "" || tlsCert != "") { if !server.TLS && (server.TLSKey != "" || server.TLSCert != "") {
return false, "", "", errors.New("requires enabled TLS") return false, "", "", errors.New("requires enabled TLS")
} else if !useTLS { } else if !server.TLS {
return false, "", "", nil return false, "", "", nil
} }
if tlsKey != "" { if server.TLSKey != "" {
key = tlsKey key = server.TLSKey
} else { } else {
key = filepath.Join(repoPath, "private_key") key = filepath.Join(server.Path, "private_key")
} }
if tlsCert != "" { if server.TLSCert != "" {
cert = tlsCert cert = server.TLSCert
} else { } else {
cert = filepath.Join(repoPath, "public_key") cert = filepath.Join(server.Path, "public_key")
} }
return useTLS, key, cert, nil return server.TLS, key, cert, nil
} }
func getHandler(config restserver.Config) (http.Handler, error) { func getHandler(server restserver.Server) (http.Handler, error) {
mux := restserver.NewHandler(config) mux := restserver.NewHandler(server)
if config.NoAuth { if server.NoAuth {
log.Println("Authentication disabled") log.Println("Authentication disabled")
return mux, nil return mux, nil
} }
log.Println("Authentication enabled") log.Println("Authentication enabled")
htpasswdFile, err := restserver.NewHtpasswdFromFile(filepath.Join(config.Path, ".htpasswd")) htpasswdFile, err := restserver.NewHtpasswdFromFile(filepath.Join(server.Path, ".htpasswd"))
if err != nil { if err != nil {
return nil, fmt.Errorf("cannot load .htpasswd (use --no-auth to disable): %v", err) return nil, fmt.Errorf("cannot load .htpasswd (use --no-auth to disable): %v", err)
} }
return config.AuthHandler(htpasswdFile, mux), nil return server.AuthHandler(htpasswdFile, mux), nil
} }
func runRoot(cmd *cobra.Command, args []string) error { func runRoot(cmd *cobra.Command, args []string) error {
@ -103,7 +97,7 @@ func runRoot(cmd *cobra.Command, args []string) error {
log.SetFlags(0) log.SetFlags(0)
log.Printf("Data directory: %s", repoPath) log.Printf("Data directory: %s", server.Path)
if cpuProfile != "" { if cpuProfile != "" {
f, err := os.Create(cpuProfile) f, err := os.Create(cpuProfile)
@ -117,27 +111,12 @@ func runRoot(cmd *cobra.Command, args []string) error {
defer pprof.StopCPUProfile() defer pprof.StopCPUProfile()
} }
config := restserver.Config{ handler, err := getHandler(server)
Path: repoPath,
Listen: listen,
Log: logFile,
CPUProfile: cpuProfile,
TLSKey: tlsKey,
TLSCert: tlsCert,
TLS: useTLS,
NoAuth: noAuth,
AppendOnly: appendOnly,
PrivateRepos: privateRepos,
Prometheus: prometheus,
Debug: debug,
}
handler, err := getHandler(config)
if err != nil { if err != nil {
log.Fatalf("error: %v", err) log.Fatalf("error: %v", err)
} }
if privateRepos { if server.PrivateRepos {
log.Println("Private repositories enabled") log.Println("Private repositories enabled")
} else { } else {
log.Println("Private repositories disabled") log.Println("Private repositories disabled")
@ -148,15 +127,15 @@ func runRoot(cmd *cobra.Command, args []string) error {
return err return err
} }
if !enabledTLS { if !enabledTLS {
log.Printf("Starting server on %s\n", listen) log.Printf("Starting server on %s\n", server.Listen)
err = http.ListenAndServe(listen, handler) err = http.ListenAndServe(server.Listen, handler)
} else { } else {
log.Println("TLS enabled") log.Println("TLS enabled")
log.Printf("Private key: %s", privateKey) log.Printf("Private key: %s", privateKey)
log.Printf("Public key(certificate): %s", publicKey) log.Printf("Public key(certificate): %s", publicKey)
log.Printf("Starting server on %s\n", listen) log.Printf("Starting server on %s\n", server.Listen)
err = http.ListenAndServeTLS(listen, publicKey, privateKey, handler) err = http.ListenAndServeTLS(server.Listen, publicKey, privateKey, handler)
} }
return err return err

View file

@ -38,13 +38,13 @@ func TestTLSSettings(t *testing.T) {
for _, test := range tests { for _, test := range tests {
t.Run("", func(t *testing.T) { t.Run("", func(t *testing.T) {
// defer func() { restserver.Config = defaultConfig }() // defer func() { restserver.Server = defaultConfig }()
if test.passed.Path != "" { if test.passed.Path != "" {
repoPath = test.passed.Path server.Path = test.passed.Path
} }
useTLS = test.passed.TLS server.TLS = test.passed.TLS
tlsKey = test.passed.TLSKey server.TLSKey = test.passed.TLSKey
tlsCert = test.passed.TLSCert server.TLSCert = test.passed.TLSCert
gotTLS, gotKey, gotCert, err := tlsSettings() gotTLS, gotKey, gotCert, err := tlsSettings()
if err != nil && !test.expected.Error { if err != nil && !test.expected.Error {
@ -82,13 +82,13 @@ func TestGetHandler(t *testing.T) {
defer os.Remove(dir) defer os.Remove(dir)
// With NoAuth = false and no .htpasswd // With NoAuth = false and no .htpasswd
_, err = getHandler(restserver.Config{Path: dir}) _, err = getHandler(restserver.Server{Path: dir})
if err == nil { if err == nil {
t.Errorf("NoAuth=false: expected error, got nil") t.Errorf("NoAuth=false: expected error, got nil")
} }
// With NoAuth = true and no .htpasswd // With NoAuth = true and no .htpasswd
_, err = getHandler(restserver.Config{NoAuth: true, Path: dir}) _, err = getHandler(restserver.Server{NoAuth: true, Path: dir})
if err != nil { if err != nil {
t.Errorf("NoAuth=true: expected no error, got %v", err) t.Errorf("NoAuth=true: expected no error, got %v", err)
} }
@ -102,7 +102,7 @@ func TestGetHandler(t *testing.T) {
defer os.Remove(htpasswd) defer os.Remove(htpasswd)
// With NoAuth = false and with .htpasswd // With NoAuth = false and with .htpasswd
_, err = getHandler(restserver.Config{Path: dir}) _, err = getHandler(restserver.Server{Path: dir})
if err != nil { if err != nil {
t.Errorf("NoAuth=false with .htpasswd: expected no error, got %v", err) t.Errorf("NoAuth=false with .htpasswd: expected no error, got %v", err)
} }

View file

@ -20,8 +20,8 @@ import (
"goji.io/pat" "goji.io/pat"
) )
// Config determines how a Mux's handlers behave. // Server determines how a Mux's handlers behave.
type Config struct { type Server struct {
Path string Path string
Listen string Listen string
Log string Log string
@ -36,7 +36,7 @@ type Config struct {
Debug bool Debug bool
} }
func (c Config) isHashed(dir string) bool { func (s Server) isHashed(dir string) bool {
return dir == "data" return dir == "data"
} }
@ -55,7 +55,7 @@ func valid(name string) bool {
var validTypes = []string{"data", "index", "keys", "locks", "snapshots", "config"} var validTypes = []string{"data", "index", "keys", "locks", "snapshots", "config"}
func (c Config) isValidType(name string) bool { func (s Server) isValidType(name string) bool {
for _, tpe := range validTypes { for _, tpe := range validTypes {
if name == tpe { if name == tpe {
return true return true
@ -85,8 +85,8 @@ func join(base string, names ...string) (string, error) {
return filepath.Join(clean...), nil return filepath.Join(clean...), nil
} }
// getRepo returns the repository location, relative to c.Path. // getRepo returns the repository location, relative to s.Path.
func (c Config) getRepo(r *http.Request) string { func (s Server) getRepo(r *http.Request) string {
if strings.HasPrefix(fmt.Sprintf("%s", middleware.Pattern(r.Context())), "/:repo") { if strings.HasPrefix(fmt.Sprintf("%s", middleware.Pattern(r.Context())), "/:repo") {
return pat.Param(r, "repo") return pat.Param(r, "repo")
} }
@ -95,32 +95,32 @@ func (c Config) getRepo(r *http.Request) string {
} }
// getPath returns the path for a file type in the repo. // getPath returns the path for a file type in the repo.
func (c Config) getPath(r *http.Request, fileType string) (string, error) { func (s Server) getPath(r *http.Request, fileType string) (string, error) {
if !c.isValidType(fileType) { if !s.isValidType(fileType) {
return "", errors.New("invalid file type") return "", errors.New("invalid file type")
} }
return join(c.Path, c.getRepo(r), fileType) return join(s.Path, s.getRepo(r), fileType)
} }
// getFilePath returns the path for a file in the repo. // getFilePath returns the path for a file in the repo.
func (c Config) getFilePath(r *http.Request, fileType, name string) (string, error) { func (s Server) getFilePath(r *http.Request, fileType, name string) (string, error) {
if !c.isValidType(fileType) { if !s.isValidType(fileType) {
return "", errors.New("invalid file type") return "", errors.New("invalid file type")
} }
if c.isHashed(fileType) { if s.isHashed(fileType) {
if len(name) < 2 { if len(name) < 2 {
return "", errors.New("file name is too short") return "", errors.New("file name is too short")
} }
return join(c.Path, c.getRepo(r), fileType, name[:2], name) return join(s.Path, s.getRepo(r), fileType, name[:2], name)
} }
return join(c.Path, c.getRepo(r), fileType, name) return join(s.Path, s.getRepo(r), fileType, name)
} }
// getUser returns the username from the request, or an empty string if none. // getUser returns the username from the request, or an empty string if none.
func (c Config) getUser(r *http.Request) string { func (s Server) getUser(r *http.Request) string {
username, _, ok := r.BasicAuth() username, _, ok := r.BasicAuth()
if !ok { if !ok {
return "" return ""
@ -129,10 +129,10 @@ func (c Config) getUser(r *http.Request) string {
} }
// getMetricLabels returns the prometheus labels from the request. // getMetricLabels returns the prometheus labels from the request.
func (c Config) getMetricLabels(r *http.Request) prometheus.Labels { func (s Server) getMetricLabels(r *http.Request) prometheus.Labels {
labels := prometheus.Labels{ labels := prometheus.Labels{
"user": c.getUser(r), "user": s.getUser(r),
"repo": c.getRepo(r), "repo": s.getRepo(r),
"type": pat.Param(r, "type"), "type": pat.Param(r, "type"),
} }
return labels return labels
@ -150,14 +150,14 @@ func isUserPath(username, path string) bool {
// AuthHandler wraps h with a http.HandlerFunc that performs basic authentication against the user/passwords pairs // AuthHandler wraps h with a http.HandlerFunc that performs basic authentication against the user/passwords pairs
// stored in f and returns the http.HandlerFunc. // stored in f and returns the http.HandlerFunc.
func (c Config) AuthHandler(f *HtpasswdFile, h http.Handler) http.HandlerFunc { func (s Server) AuthHandler(f *HtpasswdFile, h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth() username, password, ok := r.BasicAuth()
if !ok || !f.Validate(username, password) { if !ok || !f.Validate(username, password) {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return return
} }
if c.PrivateRepos && !isUserPath(username, r.URL.Path) { if s.PrivateRepos && !isUserPath(username, r.URL.Path) {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return return
} }
@ -166,11 +166,11 @@ func (c Config) AuthHandler(f *HtpasswdFile, h http.Handler) http.HandlerFunc {
} }
// CheckConfig checks whether a configuration exists. // CheckConfig checks whether a configuration exists.
func (c Config) CheckConfig(w http.ResponseWriter, r *http.Request) { func (s Server) CheckConfig(w http.ResponseWriter, r *http.Request) {
if c.Debug { if s.Debug {
log.Println("CheckConfig()") log.Println("CheckConfig()")
} }
cfg, err := c.getPath(r, "config") cfg, err := s.getPath(r, "config")
if err != nil { if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return return
@ -178,7 +178,7 @@ func (c Config) CheckConfig(w http.ResponseWriter, r *http.Request) {
st, err := os.Stat(cfg) st, err := os.Stat(cfg)
if err != nil { if err != nil {
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
@ -189,11 +189,11 @@ func (c Config) CheckConfig(w http.ResponseWriter, r *http.Request) {
} }
// GetConfig allows for a config to be retrieved. // GetConfig allows for a config to be retrieved.
func (c Config) GetConfig(w http.ResponseWriter, r *http.Request) { func (s Server) GetConfig(w http.ResponseWriter, r *http.Request) {
if c.Debug { if s.Debug {
log.Println("GetConfig()") log.Println("GetConfig()")
} }
cfg, err := c.getPath(r, "config") cfg, err := s.getPath(r, "config")
if err != nil { if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return return
@ -201,7 +201,7 @@ func (c Config) GetConfig(w http.ResponseWriter, r *http.Request) {
bytes, err := ioutil.ReadFile(cfg) bytes, err := ioutil.ReadFile(cfg)
if err != nil { if err != nil {
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
@ -212,11 +212,11 @@ func (c Config) GetConfig(w http.ResponseWriter, r *http.Request) {
} }
// SaveConfig allows for a config to be saved. // SaveConfig allows for a config to be saved.
func (c Config) SaveConfig(w http.ResponseWriter, r *http.Request) { func (s Server) SaveConfig(w http.ResponseWriter, r *http.Request) {
if c.Debug { if s.Debug {
log.Println("SaveConfig()") log.Println("SaveConfig()")
} }
cfg, err := c.getPath(r, "config") cfg, err := s.getPath(r, "config")
if err != nil { if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return return
@ -224,7 +224,7 @@ func (c Config) SaveConfig(w http.ResponseWriter, r *http.Request) {
f, err := os.OpenFile(cfg, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600) f, err := os.OpenFile(cfg, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600)
if err != nil && os.IsExist(err) { if err != nil && os.IsExist(err) {
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
@ -233,7 +233,7 @@ func (c Config) SaveConfig(w http.ResponseWriter, r *http.Request) {
_, err = io.Copy(f, r.Body) _, err = io.Copy(f, r.Body)
if err != nil { if err != nil {
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
@ -250,24 +250,24 @@ func (c Config) SaveConfig(w http.ResponseWriter, r *http.Request) {
} }
// DeleteConfig removes a config. // DeleteConfig removes a config.
func (c Config) DeleteConfig(w http.ResponseWriter, r *http.Request) { func (s Server) DeleteConfig(w http.ResponseWriter, r *http.Request) {
if c.Debug { if s.Debug {
log.Println("DeleteConfig()") log.Println("DeleteConfig()")
} }
if c.AppendOnly { if s.AppendOnly {
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return return
} }
cfg, err := c.getPath(r, "config") cfg, err := s.getPath(r, "config")
if err != nil { if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return return
} }
if err := os.Remove(cfg); err != nil { if err := os.Remove(cfg); err != nil {
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
if os.IsNotExist(err) { if os.IsNotExist(err) {
@ -285,26 +285,26 @@ const (
) )
// ListBlobs lists all blobs of a given type in an arbitrary order. // ListBlobs lists all blobs of a given type in an arbitrary order.
func (c Config) ListBlobs(w http.ResponseWriter, r *http.Request) { func (s Server) ListBlobs(w http.ResponseWriter, r *http.Request) {
if c.Debug { if s.Debug {
log.Println("ListBlobs()") log.Println("ListBlobs()")
} }
switch r.Header.Get("Accept") { switch r.Header.Get("Accept") {
case mimeTypeAPIV2: case mimeTypeAPIV2:
c.ListBlobsV2(w, r) s.ListBlobsV2(w, r)
default: default:
c.ListBlobsV1(w, r) s.ListBlobsV1(w, r)
} }
} }
// ListBlobsV1 lists all blobs of a given type in an arbitrary order. // ListBlobsV1 lists all blobs of a given type in an arbitrary order.
func (c Config) ListBlobsV1(w http.ResponseWriter, r *http.Request) { func (s Server) ListBlobsV1(w http.ResponseWriter, r *http.Request) {
if c.Debug { if s.Debug {
log.Println("ListBlobsV1()") log.Println("ListBlobsV1()")
} }
fileType := pat.Param(r, "type") fileType := pat.Param(r, "type")
path, err := c.getPath(r, fileType) path, err := s.getPath(r, fileType)
if err != nil { if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return return
@ -312,7 +312,7 @@ func (c Config) ListBlobsV1(w http.ResponseWriter, r *http.Request) {
items, err := ioutil.ReadDir(path) items, err := ioutil.ReadDir(path)
if err != nil { if err != nil {
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
@ -321,12 +321,12 @@ func (c Config) ListBlobsV1(w http.ResponseWriter, r *http.Request) {
var names []string var names []string
for _, i := range items { for _, i := range items {
if c.isHashed(fileType) { if s.isHashed(fileType) {
subpath := filepath.Join(path, i.Name()) subpath := filepath.Join(path, i.Name())
var subitems []os.FileInfo var subitems []os.FileInfo
subitems, err = ioutil.ReadDir(subpath) subitems, err = ioutil.ReadDir(subpath)
if err != nil { if err != nil {
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
@ -342,7 +342,7 @@ func (c Config) ListBlobsV1(w http.ResponseWriter, r *http.Request) {
data, err := json.Marshal(names) data, err := json.Marshal(names)
if err != nil { if err != nil {
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
@ -360,12 +360,12 @@ type Blob struct {
} }
// ListBlobsV2 lists all blobs of a given type, together with their sizes, in an arbitrary order. // ListBlobsV2 lists all blobs of a given type, together with their sizes, in an arbitrary order.
func (c Config) ListBlobsV2(w http.ResponseWriter, r *http.Request) { func (s Server) ListBlobsV2(w http.ResponseWriter, r *http.Request) {
if c.Debug { if s.Debug {
log.Println("ListBlobsV2()") log.Println("ListBlobsV2()")
} }
fileType := pat.Param(r, "type") fileType := pat.Param(r, "type")
path, err := c.getPath(r, fileType) path, err := s.getPath(r, fileType)
if err != nil { if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return return
@ -373,7 +373,7 @@ func (c Config) ListBlobsV2(w http.ResponseWriter, r *http.Request) {
items, err := ioutil.ReadDir(path) items, err := ioutil.ReadDir(path)
if err != nil { if err != nil {
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
@ -382,12 +382,12 @@ func (c Config) ListBlobsV2(w http.ResponseWriter, r *http.Request) {
var blobs []Blob var blobs []Blob
for _, i := range items { for _, i := range items {
if c.isHashed(fileType) { if s.isHashed(fileType) {
subpath := filepath.Join(path, i.Name()) subpath := filepath.Join(path, i.Name())
var subitems []os.FileInfo var subitems []os.FileInfo
subitems, err = ioutil.ReadDir(subpath) subitems, err = ioutil.ReadDir(subpath)
if err != nil { if err != nil {
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
@ -403,7 +403,7 @@ func (c Config) ListBlobsV2(w http.ResponseWriter, r *http.Request) {
data, err := json.Marshal(blobs) data, err := json.Marshal(blobs)
if err != nil { if err != nil {
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
@ -415,12 +415,12 @@ func (c Config) ListBlobsV2(w http.ResponseWriter, r *http.Request) {
} }
// CheckBlob tests whether a blob exists. // CheckBlob tests whether a blob exists.
func (c Config) CheckBlob(w http.ResponseWriter, r *http.Request) { func (s Server) CheckBlob(w http.ResponseWriter, r *http.Request) {
if c.Debug { if s.Debug {
log.Println("CheckBlob()") log.Println("CheckBlob()")
} }
path, err := c.getFilePath(r, pat.Param(r, "type"), pat.Param(r, "name")) path, err := s.getFilePath(r, pat.Param(r, "type"), pat.Param(r, "name"))
if err != nil { if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return return
@ -428,7 +428,7 @@ func (c Config) CheckBlob(w http.ResponseWriter, r *http.Request) {
st, err := os.Stat(path) st, err := os.Stat(path)
if err != nil { if err != nil {
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
@ -439,12 +439,12 @@ func (c Config) CheckBlob(w http.ResponseWriter, r *http.Request) {
} }
// GetBlob retrieves a blob from the repository. // GetBlob retrieves a blob from the repository.
func (c Config) GetBlob(w http.ResponseWriter, r *http.Request) { func (s Server) GetBlob(w http.ResponseWriter, r *http.Request) {
if c.Debug { if s.Debug {
log.Println("GetBlob()") log.Println("GetBlob()")
} }
path, err := c.getFilePath(r, pat.Param(r, "type"), pat.Param(r, "name")) path, err := s.getFilePath(r, pat.Param(r, "type"), pat.Param(r, "name"))
if err != nil { if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return return
@ -452,7 +452,7 @@ func (c Config) GetBlob(w http.ResponseWriter, r *http.Request) {
file, err := os.Open(path) file, err := os.Open(path)
if err != nil { if err != nil {
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
@ -467,20 +467,20 @@ func (c Config) GetBlob(w http.ResponseWriter, r *http.Request) {
return return
} }
if c.Prometheus { if s.Prometheus {
labels := c.getMetricLabels(r) labels := s.getMetricLabels(r)
metricBlobReadTotal.With(labels).Inc() metricBlobReadTotal.With(labels).Inc()
metricBlobReadBytesTotal.With(labels).Add(float64(wc.Count())) metricBlobReadBytesTotal.With(labels).Add(float64(wc.Count()))
} }
} }
// SaveBlob saves a blob to the repository. // SaveBlob saves a blob to the repository.
func (c Config) SaveBlob(w http.ResponseWriter, r *http.Request) { func (s Server) SaveBlob(w http.ResponseWriter, r *http.Request) {
if c.Debug { if s.Debug {
log.Println("SaveBlob()") log.Println("SaveBlob()")
} }
path, err := c.getFilePath(r, pat.Param(r, "type"), pat.Param(r, "name")) path, err := s.getFilePath(r, pat.Param(r, "type"), pat.Param(r, "name"))
if err != nil { if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return return
@ -504,7 +504,7 @@ func (c Config) SaveBlob(w http.ResponseWriter, r *http.Request) {
} }
if err != nil { if err != nil {
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
@ -515,7 +515,7 @@ func (c Config) SaveBlob(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
_ = tf.Close() _ = tf.Close()
_ = os.Remove(path) _ = os.Remove(path)
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
@ -525,7 +525,7 @@ func (c Config) SaveBlob(w http.ResponseWriter, r *http.Request) {
if err := tf.Sync(); err != nil { if err := tf.Sync(); err != nil {
_ = tf.Close() _ = tf.Close()
_ = os.Remove(path) _ = os.Remove(path)
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
@ -534,39 +534,39 @@ func (c Config) SaveBlob(w http.ResponseWriter, r *http.Request) {
if err := tf.Close(); err != nil { if err := tf.Close(); err != nil {
_ = os.Remove(path) _ = os.Remove(path)
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return return
} }
if c.Prometheus { if s.Prometheus {
labels := c.getMetricLabels(r) labels := s.getMetricLabels(r)
metricBlobWriteTotal.With(labels).Inc() metricBlobWriteTotal.With(labels).Inc()
metricBlobWriteBytesTotal.With(labels).Add(float64(written)) metricBlobWriteBytesTotal.With(labels).Add(float64(written))
} }
} }
// DeleteBlob deletes a blob from the repository. // DeleteBlob deletes a blob from the repository.
func (c Config) DeleteBlob(w http.ResponseWriter, r *http.Request) { func (s Server) DeleteBlob(w http.ResponseWriter, r *http.Request) {
if c.Debug { if s.Debug {
log.Println("DeleteBlob()") log.Println("DeleteBlob()")
} }
if c.AppendOnly && pat.Param(r, "type") != "locks" { if s.AppendOnly && pat.Param(r, "type") != "locks" {
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden) http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return return
} }
path, err := c.getFilePath(r, pat.Param(r, "type"), pat.Param(r, "name")) path, err := s.getFilePath(r, pat.Param(r, "type"), pat.Param(r, "name"))
if err != nil { if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return return
} }
var size int64 var size int64
if c.Prometheus { if s.Prometheus {
stat, err := os.Stat(path) stat, err := os.Stat(path)
if err != nil { if err != nil {
size = stat.Size() size = stat.Size()
@ -574,7 +574,7 @@ func (c Config) DeleteBlob(w http.ResponseWriter, r *http.Request) {
} }
if err := os.Remove(path); err != nil { if err := os.Remove(path); err != nil {
if c.Debug { if s.Debug {
log.Print(err) log.Print(err)
} }
if os.IsNotExist(err) { if os.IsNotExist(err) {
@ -585,20 +585,20 @@ func (c Config) DeleteBlob(w http.ResponseWriter, r *http.Request) {
return return
} }
if c.Prometheus { if s.Prometheus {
labels := c.getMetricLabels(r) labels := s.getMetricLabels(r)
metricBlobDeleteTotal.With(labels).Inc() metricBlobDeleteTotal.With(labels).Inc()
metricBlobDeleteBytesTotal.With(labels).Add(float64(size)) metricBlobDeleteBytesTotal.With(labels).Add(float64(size))
} }
} }
// CreateRepo creates repository directories. // CreateRepo creates repository directories.
func (c Config) CreateRepo(w http.ResponseWriter, r *http.Request) { func (s Server) CreateRepo(w http.ResponseWriter, r *http.Request) {
if c.Debug { if s.Debug {
log.Println("CreateRepo()") log.Println("CreateRepo()")
} }
repo, err := join(c.Path, c.getRepo(r)) repo, err := join(s.Path, s.getRepo(r))
if err != nil { if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return return

View file

@ -230,7 +230,7 @@ func TestResticHandler(t *testing.T) {
}() }()
// set append-only mode and configure path // set append-only mode and configure path
mux := NewHandler(Config{ mux := NewHandler(Server{
AppendOnly: true, AppendOnly: true,
Path: tempdir, Path: tempdir,
}) })

60
mux.go
View file

@ -12,7 +12,7 @@ import (
"goji.io/pat" "goji.io/pat"
) )
func (c Config) debugHandler(next http.Handler) http.Handler { func (s Server) debugHandler(next http.Handler) http.Handler {
return http.HandlerFunc( return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) { func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", r.Method, r.URL) log.Printf("%s %s", r.Method, r.URL)
@ -20,8 +20,8 @@ func (c Config) debugHandler(next http.Handler) http.Handler {
}) })
} }
func (c Config) logHandler(next http.Handler) http.Handler { func (s Server) logHandler(next http.Handler) http.Handler {
accessLog, err := os.OpenFile(c.Log, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) accessLog, err := os.OpenFile(s.Log, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil { if err != nil {
log.Fatalf("error: %v", err) log.Fatalf("error: %v", err)
} }
@ -30,42 +30,42 @@ func (c Config) logHandler(next http.Handler) http.Handler {
} }
// NewHandler returns the master HTTP multiplexer/router. // NewHandler returns the master HTTP multiplexer/router.
func NewHandler(config Config) *goji.Mux { func NewHandler(server Server) *goji.Mux {
mux := goji.NewMux() mux := goji.NewMux()
if config.Debug { if server.Debug {
mux.Use(config.debugHandler) mux.Use(server.debugHandler)
} }
if config.Log != "" { if server.Log != "" {
mux.Use(config.logHandler) mux.Use(server.logHandler)
} }
if config.Prometheus { if server.Prometheus {
mux.Handle(pat.Get("/metrics"), promhttp.Handler()) mux.Handle(pat.Get("/metrics"), promhttp.Handler())
} }
mux.HandleFunc(pat.Head("/config"), config.CheckConfig) mux.HandleFunc(pat.Head("/config"), server.CheckConfig)
mux.HandleFunc(pat.Head("/:repo/config"), config.CheckConfig) mux.HandleFunc(pat.Head("/:repo/config"), server.CheckConfig)
mux.HandleFunc(pat.Get("/config"), config.GetConfig) mux.HandleFunc(pat.Get("/config"), server.GetConfig)
mux.HandleFunc(pat.Get("/:repo/config"), config.GetConfig) mux.HandleFunc(pat.Get("/:repo/config"), server.GetConfig)
mux.HandleFunc(pat.Post("/config"), config.SaveConfig) mux.HandleFunc(pat.Post("/config"), server.SaveConfig)
mux.HandleFunc(pat.Post("/:repo/config"), config.SaveConfig) mux.HandleFunc(pat.Post("/:repo/config"), server.SaveConfig)
mux.HandleFunc(pat.Delete("/config"), config.DeleteConfig) mux.HandleFunc(pat.Delete("/config"), server.DeleteConfig)
mux.HandleFunc(pat.Delete("/:repo/config"), config.DeleteConfig) mux.HandleFunc(pat.Delete("/:repo/config"), server.DeleteConfig)
mux.HandleFunc(pat.Get("/:type/"), config.ListBlobs) mux.HandleFunc(pat.Get("/:type/"), server.ListBlobs)
mux.HandleFunc(pat.Get("/:repo/:type/"), config.ListBlobs) mux.HandleFunc(pat.Get("/:repo/:type/"), server.ListBlobs)
mux.HandleFunc(pat.Head("/:type/:name"), config.CheckBlob) mux.HandleFunc(pat.Head("/:type/:name"), server.CheckBlob)
mux.HandleFunc(pat.Head("/:repo/:type/:name"), config.CheckBlob) mux.HandleFunc(pat.Head("/:repo/:type/:name"), server.CheckBlob)
mux.HandleFunc(pat.Get("/:type/:name"), config.GetBlob) mux.HandleFunc(pat.Get("/:type/:name"), server.GetBlob)
mux.HandleFunc(pat.Get("/:repo/:type/:name"), config.GetBlob) mux.HandleFunc(pat.Get("/:repo/:type/:name"), server.GetBlob)
mux.HandleFunc(pat.Post("/:type/:name"), config.SaveBlob) mux.HandleFunc(pat.Post("/:type/:name"), server.SaveBlob)
mux.HandleFunc(pat.Post("/:repo/:type/:name"), config.SaveBlob) mux.HandleFunc(pat.Post("/:repo/:type/:name"), server.SaveBlob)
mux.HandleFunc(pat.Delete("/:type/:name"), config.DeleteBlob) mux.HandleFunc(pat.Delete("/:type/:name"), server.DeleteBlob)
mux.HandleFunc(pat.Delete("/:repo/:type/:name"), config.DeleteBlob) mux.HandleFunc(pat.Delete("/:repo/:type/:name"), server.DeleteBlob)
mux.HandleFunc(pat.Post("/"), config.CreateRepo) mux.HandleFunc(pat.Post("/"), server.CreateRepo)
mux.HandleFunc(pat.Post("/:repo"), config.CreateRepo) mux.HandleFunc(pat.Post("/:repo"), server.CreateRepo)
mux.HandleFunc(pat.Post("/:repo/"), config.CreateRepo) mux.HandleFunc(pat.Post("/:repo/"), server.CreateRepo)
return mux return mux
} }