2 * Copyright (C) 2017 "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.
28 "github.com/franciscocpg/reflectme"
29 "github.com/iotbzh/xds-agent/lib/syncthing"
30 "github.com/iotbzh/xds-agent/lib/xaapiv1"
31 common "github.com/iotbzh/xds-common/golib"
32 "github.com/iotbzh/xds-server/lib/xsapiv1"
33 "github.com/syncthing/syncthing/lib/sync"
36 // Projects Represent a an XDS Projects
37 type Projects struct {
40 projects map[string]*IPROJECT
43 // Mutex to make add/delete atomic
44 var pjMutex = sync.NewMutex()
46 // NewProjects Create a new instance of Project Model
47 func NewProjects(ctx *Context, st *st.SyncThing) *Projects {
51 projects: make(map[string]*IPROJECT),
55 // Init Load Projects configuration
56 func (p *Projects) Init(server *XdsServer) error {
57 svrList := make(map[string]*XdsServer)
58 // If server not set, load for all servers
60 svrList = p.xdsServers
62 svrList[server.ID] = server
65 for _, svr := range svrList {
69 xFlds := []xsapiv1.FolderConfig{}
70 if err := svr.GetFolders(&xFlds); err != nil {
71 errMsg += fmt.Sprintf("Cannot retrieve folders config of XDS server ID %s : %v \n", svr.ID, err.Error())
74 p.Log.Debugf("Connected to XDS Server %s, %d projects detected", svr.ID, len(xFlds))
75 for _, prj := range xFlds {
76 newP := svr.FolderToProject(prj)
77 if _, err := p.createUpdate(newP, false, true); err != nil {
78 // Don't consider that as an error (allow support config without CloudSync support)
79 if p.Context.SThg == nil && strings.Contains(err.Error(), "Server doesn't support project type CloudSync") {
83 errMsg += "Error while creating project id " + prj.ID + ": " + err.Error() + "\n "
89 p.Log.Infof("Number of loaded Projects: %d", len(p.projects))
92 return fmt.Errorf(errMsg)
97 // ResolveID Complete a Project ID (helper for user that can use partial ID value)
98 func (p *Projects) ResolveID(id string) (string, error) {
104 for iid := range p.projects {
105 if strings.HasPrefix(iid, id) {
106 match = append(match, iid)
112 } else if len(match) == 0 {
113 return id, fmt.Errorf("Unknown id")
115 return id, fmt.Errorf("Multiple IDs found with provided prefix: " + id)
118 // Get returns the folder config or nil if not existing
119 func (p *Projects) Get(id string) *IPROJECT {
123 fc, exist := p.projects[id]
130 // GetProjectArr returns the config of all folders as an array
131 func (p *Projects) GetProjectArr() []xaapiv1.ProjectConfig {
133 defer pjMutex.Unlock()
135 return p.GetProjectArrUnsafe()
138 // GetProjectArrUnsafe Same as GetProjectArr without mutex protection
139 func (p *Projects) GetProjectArrUnsafe() []xaapiv1.ProjectConfig {
140 conf := []xaapiv1.ProjectConfig{}
141 for _, v := range p.projects {
142 prj := (*v).GetProject()
143 conf = append(conf, *prj)
148 // Add adds a new folder
149 func (p *Projects) Add(newP xaapiv1.ProjectConfig, fromSid, requestURL string) (*xaapiv1.ProjectConfig, error) {
150 prj, err := p.createUpdate(newP, true, false)
155 // Create xds-project.conf file
156 prjConfFile := filepath.Join(prj.ClientPath, "xds-project.conf")
157 if !common.Exists(prjConfFile) {
158 fd, err := os.OpenFile(prjConfFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
160 return prj, fmt.Errorf("Cannot create xds-project.conf: %v", err.Error())
162 fd.WriteString("# XDS project settings\n")
163 fd.WriteString("export XDS_AGENT_URL=" + requestURL + "\n")
164 fd.WriteString("export XDS_PROJECT_ID=" + prj.ID + "\n")
165 if prj.DefaultSdk != "" {
166 fd.WriteString("export XDS_SDK_ID=" + prj.DefaultSdk + "\n")
168 fd.WriteString("#export XDS_SDK_ID=???\n")
173 // Notify client with event
174 if err := p.events.Emit(xaapiv1.EVTProjectAdd, *prj, fromSid); err != nil {
175 p.Log.Warningf("Cannot notify project deletion: %v", err)
181 // CreateUpdate creates or update a folder
182 func (p *Projects) createUpdate(newF xaapiv1.ProjectConfig, create bool, initial bool) (*xaapiv1.ProjectConfig, error) {
186 defer pjMutex.Unlock()
189 if _, exist := p.projects[newF.ID]; create && exist {
190 return nil, fmt.Errorf("ID already exists")
192 if newF.ClientPath == "" {
193 return nil, fmt.Errorf("ClientPath must be set")
195 if newF.ServerID == "" {
196 return nil, fmt.Errorf("Server ID must be set")
200 if svr, exist = p.xdsServers[newF.ServerID]; !exist {
201 return nil, fmt.Errorf("Unknown Server ID %s", newF.ServerID)
204 // Check type supported
205 b, exist := svr.ServerConfig.SupportedSharing[string(newF.Type)]
207 return nil, fmt.Errorf("Server doesn't support project type %s", newF.Type)
210 // Create a new folder object
214 case xaapiv1.TypeCloudSync:
216 fld = NewProjectST(p.Context, svr)
218 return nil, fmt.Errorf("Cloud Sync project not supported")
222 case xaapiv1.TypePathMap:
223 fld = NewProjectPathMap(p.Context, svr)
225 return nil, fmt.Errorf("Unsupported folder type")
228 var newPrj *xaapiv1.ProjectConfig
230 // Add project on server
231 if newPrj, err = fld.Add(newF); err != nil {
232 newF.Status = xaapiv1.StatusErrorConfig
233 log.Printf("ERROR Adding project: %v\n", err)
237 // Just update project config
238 if newPrj, err = fld.Setup(newF); err != nil {
239 newF.Status = xaapiv1.StatusErrorConfig
240 log.Printf("ERROR Updating project: %v\n", err)
247 log.Printf("ERROR project ID empty: %v", newF)
248 return newPrj, fmt.Errorf("Project ID empty")
251 // Add to folders list
252 p.projects[newPrj.ID] = &fld
254 // Force sync to get an initial sync status
255 // (need to defer to be sure that WS events will arrive after HTTP creation reply)
257 time.Sleep(time.Millisecond * 500)
264 // Delete deletes a specific folder
265 func (p *Projects) Delete(id, fromSid string) (xaapiv1.ProjectConfig, error) {
269 defer pjMutex.Unlock()
271 fld := xaapiv1.ProjectConfig{}
272 fc, exist := p.projects[id]
274 return fld, fmt.Errorf("Unknown id")
277 prj := (*fc).GetProject()
279 if err = (*fc).Delete(); err != nil {
283 delete(p.projects, id)
285 // Notify client with event
286 if err := p.events.Emit(xaapiv1.EVTProjectDelete, *prj, fromSid); err != nil {
287 p.Log.Warningf("Cannot notify project deletion: %v", err)
293 // ForceSync Force the synchronization of a folder
294 func (p *Projects) ForceSync(id string) error {
297 return fmt.Errorf("Unknown id")
302 // IsProjectInSync Returns true when folder is in sync
303 func (p *Projects) IsProjectInSync(id string) (bool, error) {
306 return false, fmt.Errorf("Unknown id")
308 return (*fc).IsInSync()
311 // Update Update some field of a project
312 func (p *Projects) Update(id string, prj xaapiv1.ProjectConfig, fromSid string) (*xaapiv1.ProjectConfig, error) {
315 defer pjMutex.Unlock()
317 fc, exist := p.projects[id]
319 return nil, fmt.Errorf("Unknown id")
322 // Copy current in a new object to change nothing in case of an error rises
323 newFld := xaapiv1.ProjectConfig{}
324 reflectme.Copy((*fc).GetProject(), &newFld)
326 // Only update some fields
328 for _, fieldName := range xaapiv1.ProjectConfigUpdatableFields {
329 valNew, err := reflectme.GetField(prj, fieldName)
331 valCur, err := reflectme.GetField(newFld, fieldName)
332 if err == nil && valNew != valCur {
333 err = reflectme.SetField(&newFld, fieldName, valNew)
346 upPrj, err := (*fc).Update(newFld)
351 // Notify client with event
352 if err := p.events.Emit(xaapiv1.EVTProjectChange, *upPrj, fromSid); err != nil {
353 p.Log.Warningf("Cannot notify project change: %v", err)