local-server/cmd/dkl-local-server/ws-configs.go

79 lines
1.2 KiB
Go
Raw Normal View History

2019-02-04 02:56:43 +00:00
package main
import (
"compress/gzip"
"io"
"io/ioutil"
"os"
"path/filepath"
restful "github.com/emicklei/go-restful"
)
func wsUploadConfig(req *restful.Request, resp *restful.Response) {
2019-02-04 03:39:37 +00:00
body := req.Request.Body
2019-02-04 02:56:43 +00:00
2019-02-04 03:39:37 +00:00
err := writeNewConfig(body)
body.Close()
2019-02-04 02:56:43 +00:00
2019-02-04 03:39:37 +00:00
if err != nil {
wsError(resp, err)
2019-02-04 02:56:43 +00:00
}
2019-02-04 03:39:37 +00:00
}
2019-02-04 02:56:43 +00:00
2019-02-04 03:39:37 +00:00
func writeNewConfig(reader io.Reader) (err error) {
2019-02-04 02:56:43 +00:00
out, err := ioutil.TempFile(*dataDir, ".config-upload")
if err != nil {
return
}
defer os.Remove(out.Name())
2019-02-04 03:41:51 +00:00
_, err = io.Copy(out, reader)
2019-02-04 02:56:43 +00:00
out.Close()
if err != nil {
return
}
cfgPath := configFilePath()
in, err := os.Open(cfgPath)
if err == nil {
err = backupCurrentConfig(in)
} else if !os.IsNotExist(err) {
return
}
err = os.Rename(out.Name(), cfgPath)
return
}
func backupCurrentConfig(in io.ReadCloser) (err error) {
archivesPath := filepath.Join(*dataDir, "archives")
2019-02-04 02:56:43 +00:00
err = os.MkdirAll(archivesPath, 0700)
if err != nil {
return
}
2019-02-04 03:39:37 +00:00
backupPath := filepath.Join(archivesPath, "config."+ulid()+".yaml.gz")
2019-02-04 02:56:43 +00:00
2019-02-04 03:39:37 +00:00
bck, err := os.Create(backupPath)
if err != nil {
return
}
2019-02-04 02:56:43 +00:00
2019-02-04 03:39:37 +00:00
defer bck.Close()
2019-02-04 02:56:43 +00:00
2019-02-04 03:39:37 +00:00
gz, err := gzip.NewWriterLevel(bck, 2)
2019-02-04 02:56:43 +00:00
if err != nil {
return
}
2019-02-04 03:39:37 +00:00
_, err = io.Copy(gz, in)
gz.Close()
in.Close()
return
2019-02-04 02:56:43 +00:00
}