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

91 lines
1.3 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)
2023-02-13 16:24:28 +00:00
return
2019-02-04 02:56:43 +00:00
}
2023-02-13 16:24:28 +00:00
resp.WriteEntity(true)
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)
2023-02-13 16:24:28 +00:00
if err != nil {
if os.IsNotExist(err) {
// nothing to backup
} else {
return // real error
}
} else {
err = backupCurrentConfig(in)
2023-02-13 16:24:28 +00:00
if err != nil {
return
}
}
err = os.Rename(out.Name(), cfgPath)
2023-02-07 20:29:19 +00:00
updateState()
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
}