2 * Copyright (C) 2017-2018 "IoT.bzh"
3 * Author Sebastien Douheret <sebastien@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
26 common "gerrit.automotivelinux.org/gerrit/src/xds/xds-common.git/golib"
27 uuid "github.com/satori/go.uuid"
28 "github.com/syncthing/syncthing/lib/sync"
31 // xmlServerData contains persistent data stored/loaded by server
32 type xmlServerData struct {
33 XMLName xml.Name `xml:"XDS-Server"`
34 Version string `xml:"version,attr"`
35 Data ServerData `xml:"server-data"`
38 // ServerData Hold server data saved in ServerData file
39 type ServerData struct {
43 var sdMutex = sync.NewMutex()
45 // ServerIDGet Get Server unique ID
46 func ServerIDGet() (string, error) {
51 if f, err = ServerDataFilenameGet(); err != nil {
54 if err = serverDataRead(f, &d); err != nil || d.ID == "" {
55 // Create a new uuid when not found
56 d.ID = uuid.NewV1().String()
57 if err := serverDataWrite(f, d); err != nil {
64 // serverDataRead reads data saved on disk
65 func serverDataRead(file string, data *ServerData) error {
66 if !common.Exists(file) {
67 return fmt.Errorf("No folder config file found (%s)", file)
71 defer sdMutex.Unlock()
73 fd, err := os.Open(file)
79 xsd := xmlServerData{}
80 err = xml.NewDecoder(fd).Decode(&xsd)
87 // serverDataWrite writes persistant data to disk
88 func serverDataWrite(file string, data ServerData) error {
90 defer sdMutex.Unlock()
92 dir := filepath.Dir(file)
93 if !common.Exists(dir) {
94 if err := os.MkdirAll(dir, 0755); err != nil {
95 return fmt.Errorf("Cannot create server data directory: %s", dir)
99 fd, err := os.OpenFile(file, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
105 xsd := &xmlServerData{
110 enc := xml.NewEncoder(fd)
112 return enc.Encode(xsd)