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 {
58 svrList := make(map[string]*XdsServer)
59 // If server not set, load for all servers
61 svrList = p.xdsServers
63 svrList[server.ID] = server
66 for _, svr := range svrList {
70 xFlds := []xsapiv1.FolderConfig{}
71 if err := svr.GetFolders(&xFlds); err != nil {
72 errMsg += fmt.Sprintf("Cannot retrieve folders config of XDS server ID %s : %v \n", svr.ID, err.Error())
75 p.Log.Debugf("Connected to XDS Server %s, %d projects detected", svr.ID, len(xFlds))
76 for _, prj := range xFlds {
77 newP := svr.FolderToProject(prj)
78 if _, err := p.createUpdate(newP, false, true); err != nil {
79 // Don't consider that as an error (allow support config without CloudSync support)
80 if p.Context.SThg == nil && strings.Contains(err.Error(), "Server doesn't support project type CloudSync") {
84 errMsg += "Error while creating project id " + prj.ID + ": " + err.Error() + "\n "
90 p.Log.Infof("Number of loaded Projects: %d", len(p.projects))
93 return fmt.Errorf(errMsg)
98 // ResolveID Complete a Project ID (helper for user that can use partial ID value)
99 func (p *Projects) ResolveID(id string) (string, error) {
105 for iid := range p.projects {
106 if strings.HasPrefix(iid, id) {
107 match = append(match, iid)
113 } else if len(match) == 0 {
114 return id, fmt.Errorf("Unknown id")
116 return id, fmt.Errorf("Multiple IDs found with provided prefix: " + id)
119 // Get returns the folder config or nil if not existing
120 func (p *Projects) Get(id string) *IPROJECT {
124 fc, exist := p.projects[id]
131 // GetProjectArr returns the config of all folders as an array
132 func (p *Projects) GetProjectArr() []xaapiv1.ProjectConfig {
134 defer pjMutex.Unlock()
136 return p.GetProjectArrUnsafe()
139 // GetProjectArrUnsafe Same as GetProjectArr without mutex protection
140 func (p *Projects) GetProjectArrUnsafe() []xaapiv1.ProjectConfig {
141 conf := []xaapiv1.ProjectConfig{}
142 for _, v := range p.projects {
143 prj := (*v).GetProject()
144 conf = append(conf, *prj)
149 // Add adds a new folder
150 func (p *Projects) Add(newP xaapiv1.ProjectConfig, fromSid, requestURL string) (*xaapiv1.ProjectConfig, error) {
151 prj, err := p.createUpdate(newP, true, false)
156 // Create xds-project.conf file
157 prjConfFile := filepath.Join(prj.ClientPath, "xds-project.conf")
158 if !common.Exists(prjConfFile) {
159 fd, err := os.OpenFile(prjConfFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
161 return prj, fmt.Errorf("Cannot create xds-project.conf: %v", err.Error())
163 fd.WriteString("# XDS project settings\n")
164 fd.WriteString("export XDS_AGENT_URL=" + requestURL + "\n")
165 fd.WriteString("export XDS_PROJECT_ID=" + prj.ID + "\n")
166 if prj.DefaultSdk != "" {
167 fd.WriteString("export XDS_SDK_ID=" + prj.DefaultSdk + "\n")
169 fd.WriteString("#export XDS_SDK_ID=???\n")
174 // Notify client with event
175 if err := p.events.Emit(xaapiv1.EVTProjectAdd, *prj, fromSid); err != nil {
176 p.Log.Warningf("Cannot notify project deletion: %v", err)
182 // CreateUpdate creates or update a folder
183 func (p *Projects) createUpdate(newF xaapiv1.ProjectConfig, create bool, initial bool) (*xaapiv1.ProjectConfig, error) {
187 defer pjMutex.Unlock()
190 if _, exist := p.projects[newF.ID]; create && exist {
191 return nil, fmt.Errorf("ID already exists")
193 if newF.ClientPath == "" {
194 return nil, fmt.Errorf("ClientPath must be set")
196 if newF.ServerID == "" {
197 return nil, fmt.Errorf("Server ID must be set")
201 if svr, exist = p.xdsServers[newF.ServerID]; !exist {
202 return nil, fmt.Errorf("Unknown Server ID %s", newF.ServerID)
205 // Check type supported
206 b, exist := svr.ServerConfig.SupportedSharing[string(newF.Type)]
208 return nil, fmt.Errorf("Server doesn't support project type %s", newF.Type)
211 // Create a new folder object
215 case xaapiv1.TypeCloudSync:
217 fld = NewProjectST(p.Context, svr)
219 return nil, fmt.Errorf("Cloud Sync project not supported")
223 case xaapiv1.TypePathMap:
224 fld = NewProjectPathMap(p.Context, svr)
226 return nil, fmt.Errorf("Unsupported folder type")
229 var newPrj *xaapiv1.ProjectConfig
231 // Add project on server
232 if newPrj, err = fld.Add(newF); err != nil {
233 newF.Status = xaapiv1.StatusErrorConfig
234 log.Printf("ERROR Adding project: %v\n", err)
238 // Just update project config
239 if newPrj, err = fld.Setup(newF); err != nil {
240 newF.Status = xaapiv1.StatusErrorConfig
241 log.Printf("ERROR Updating project: %v\n", err)
248 log.Printf("ERROR project ID empty: %v", newF)
249 return newPrj, fmt.Errorf("Project ID empty")
252 // Add to folders list
253 p.projects[newPrj.ID] = &fld
255 // Force sync to get an initial sync status
256 // (need to defer to be sure that WS events will arrive after HTTP creation reply)
258 time.Sleep(time.Millisecond * 500)
265 // Delete deletes a specific folder
266 func (p *Projects) Delete(id, fromSid string) (xaapiv1.ProjectConfig, error) {
270 defer pjMutex.Unlock()
272 fld := xaapiv1.ProjectConfig{}
273 fc, exist := p.projects[id]
275 return fld, fmt.Errorf("Unknown id")
278 prj := (*fc).GetProject()
280 if err = (*fc).Delete(); err != nil {
284 delete(p.projects, id)
286 // Notify client with event
287 if err := p.events.Emit(xaapiv1.EVTProjectDelete, *prj, fromSid); err != nil {
288 p.Log.Warningf("Cannot notify project deletion: %v", err)
294 // ForceSync Force the synchronization of a folder
295 func (p *Projects) ForceSync(id string) error {
298 return fmt.Errorf("Unknown id")
303 // IsProjectInSync Returns true when folder is in sync
304 func (p *Projects) IsProjectInSync(id string) (bool, error) {
307 return false, fmt.Errorf("Unknown id")
309 return (*fc).IsInSync()
312 // Update Update some field of a project
313 func (p *Projects) Update(id string, prj xaapiv1.ProjectConfig, fromSid string) (*xaapiv1.ProjectConfig, error) {
316 defer pjMutex.Unlock()
318 fc, exist := p.projects[id]
320 return nil, fmt.Errorf("Unknown id")
323 // Copy current in a new object to change nothing in case of an error rises
324 newFld := xaapiv1.ProjectConfig{}
325 reflectme.Copy((*fc).GetProject(), &newFld)
327 // Only update some fields
329 for _, fieldName := range xaapiv1.ProjectConfigUpdatableFields {
330 valNew, err := reflectme.GetField(prj, fieldName)
332 valCur, err := reflectme.GetField(newFld, fieldName)
333 if err == nil && valNew != valCur {
334 err = reflectme.SetField(&newFld, fieldName, valNew)
347 upPrj, err := (*fc).Update(newFld)
352 // Notify client with event
353 if err := p.events.Emit(xaapiv1.EVTProjectChange, *upPrj, fromSid); err != nil {
354 p.Log.Warningf("Cannot notify project change: %v", err)