8711df25b9f1988cc247924ec06b3ca9909ac467
[src/xds/xds-server.git] / lib / folder / folder-pathmap.go
1 package folder
2
3 import (
4         "fmt"
5         "io/ioutil"
6         "os"
7         "path/filepath"
8
9         common "github.com/iotbzh/xds-common/golib"
10 )
11
12 // IFOLDER interface implementation for native/path mapping folders
13
14 // PathMap .
15 type PathMap struct {
16         config FolderConfig
17 }
18
19 // NewFolderPathMap Create a new instance of PathMap
20 func NewFolderPathMap() *PathMap {
21         f := PathMap{}
22         return &f
23 }
24
25 // Add a new folder
26 func (f *PathMap) Add(cfg FolderConfig) (*FolderConfig, error) {
27         if cfg.DataPathMap.ServerPath == "" {
28                 return nil, fmt.Errorf("ServerPath must be set")
29         }
30
31         // Sanity check
32         dir := cfg.DataPathMap.ServerPath
33         if !common.Exists(dir) {
34                 // try to create if not existing
35                 if err := os.MkdirAll(dir, 0755); err != nil {
36                         return nil, fmt.Errorf("Cannot create ServerPath directory: %s", dir)
37                 }
38         }
39         if !common.Exists(dir) {
40                 return nil, fmt.Errorf("ServerPath directory is not accessible: %s", dir)
41         }
42         file, err := ioutil.TempFile(dir, "xds_pathmap_check")
43         if err != nil {
44                 return nil, fmt.Errorf("ServerPath sanity check error: %s", err.Error())
45         }
46         defer os.Remove(file.Name())
47
48         msg := "sanity check PathMap Add folder"
49         n, err := file.Write([]byte(msg))
50         if err != nil || n != len(msg) {
51                 return nil, fmt.Errorf("ServerPath sanity check error: %s", err.Error())
52         }
53
54         f.config = cfg
55         f.config.RootPath = cfg.DataPathMap.ServerPath
56         f.config.Status = StatusEnable
57
58         return &f.config, nil
59 }
60
61 // GetConfig Get public part of folder config
62 func (f *PathMap) GetConfig() FolderConfig {
63         return f.config
64 }
65
66 // GetFullPath returns the full path
67 func (f *PathMap) GetFullPath(dir string) string {
68         if &dir == nil {
69                 return f.config.DataPathMap.ServerPath
70         }
71         return filepath.Join(f.config.DataPathMap.ServerPath, dir)
72 }
73
74 // Remove a folder
75 func (f *PathMap) Remove() error {
76         // nothing to do
77         return nil
78 }
79
80 // Sync Force folder files synchronization
81 func (f *PathMap) Sync() error {
82         return nil
83 }
84
85 // IsInSync Check if folder files are in-sync
86 func (f *PathMap) IsInSync() (bool, error) {
87         return true, nil
88 }