summaryrefslogtreecommitdiffstats
path: root/lib/xdsconfig/data.go
diff options
context:
space:
mode:
authorSebastien Douheret <sebastien.douheret@iot.bzh>2017-10-06 17:53:51 +0200
committerSebastien Douheret <sebastien.douheret@iot.bzh>2017-11-06 15:57:03 +0100
commit0e72ccd733207877bd8edca55fd6aed0877139e5 (patch)
tree948fd6eebea259c8a09b313427e0112433418d30 /lib/xdsconfig/data.go
parentac9e80f7f32a1c04c171a4d208f0ab7d3a5ca154 (diff)
Cleanup and improvements
- Save server data into file - FolderType is now a string - cleanup useless code Signed-off-by: Sebastien Douheret <sebastien.douheret@iot.bzh>
Diffstat (limited to 'lib/xdsconfig/data.go')
-rw-r--r--lib/xdsconfig/data.go87
1 files changed, 87 insertions, 0 deletions
diff --git a/lib/xdsconfig/data.go b/lib/xdsconfig/data.go
new file mode 100644
index 0000000..65e0fc6
--- /dev/null
+++ b/lib/xdsconfig/data.go
@@ -0,0 +1,87 @@
+package xdsconfig
+
+import (
+ "encoding/xml"
+ "fmt"
+ "os"
+
+ common "github.com/iotbzh/xds-common/golib"
+ uuid "github.com/satori/go.uuid"
+ "github.com/syncthing/syncthing/lib/sync"
+)
+
+// xmlServerData contains persistent data stored/loaded by server
+type xmlServerData struct {
+ XMLName xml.Name `xml:"XDS-Server"`
+ Version string `xml:"version,attr"`
+ Data ServerData `xml:"server-data"`
+}
+
+type ServerData struct {
+ ID string `xml:"id"`
+}
+
+var sdMutex = sync.NewMutex()
+
+// ServerIDGet
+func ServerIDGet() (string, error) {
+ var f string
+ var err error
+
+ d := ServerData{}
+ if f, err = ServerDataFilenameGet(); err != nil {
+ return "", err
+ }
+ if err = serverDataRead(f, &d); err != nil || d.ID == "" {
+ // Create a new uuid when not found
+ d.ID = uuid.NewV1().String()
+ if err := serverDataWrite(f, d); err != nil {
+ return "", err
+ }
+ }
+ return d.ID, nil
+}
+
+// serverDataRead reads data saved on disk
+func serverDataRead(file string, data *ServerData) error {
+ if !common.Exists(file) {
+ return fmt.Errorf("No folder config file found (%s)", file)
+ }
+
+ sdMutex.Lock()
+ defer sdMutex.Unlock()
+
+ fd, err := os.Open(file)
+ defer fd.Close()
+ if err != nil {
+ return err
+ }
+
+ xsd := xmlServerData{}
+ err = xml.NewDecoder(fd).Decode(&xsd)
+ if err == nil {
+ *data = xsd.Data
+ }
+ return err
+}
+
+// serverDataWrite writes persistant data to disk
+func serverDataWrite(file string, data ServerData) error {
+ sdMutex.Lock()
+ defer sdMutex.Unlock()
+
+ fd, err := os.OpenFile(file, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
+ defer fd.Close()
+ if err != nil {
+ return err
+ }
+
+ xsd := &xmlServerData{
+ Version: "1",
+ Data: data,
+ }
+
+ enc := xml.NewEncoder(fd)
+ enc.Indent("", " ")
+ return enc.Encode(xsd)
+}