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.
28 st "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent/lib/syncthing"
29 "gerrit.automotivelinux.org/gerrit/src/xds/xds-server.git/lib/xsapiv1"
31 "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent/lib/xaapiv1"
32 common "gerrit.automotivelinux.org/gerrit/src/xds/xds-common.git/golib"
33 "github.com/franciscocpg/reflectme"
34 "github.com/syncthing/syncthing/lib/sync"
37 // Projects Represent a an XDS Projects
38 type Projects struct {
41 projects map[string]*IPROJECT
44 // Mutex to make add/delete atomic
45 var pjMutex = sync.NewMutex()
47 // NewProjects Create a new instance of Project Model
48 func NewProjects(ctx *Context, st *st.SyncThing) *Projects {
52 projects: make(map[string]*IPROJECT),
56 // Init Load Projects configuration
57 func (p *Projects) Init(server *XdsServer) error {
59 svrList := make(map[string]*XdsServer)
60 // If server not set, load for all servers
62 svrList = p.xdsServers
64 svrList[server.ID] = server
67 for _, svr := range svrList {
71 xFlds := []xsapiv1.FolderConfig{}
72 if err := svr.GetFolders(&xFlds); err != nil {
73 errMsg += fmt.Sprintf("Cannot retrieve folders config of XDS server ID %s : %v \n", svr.ID, err.Error())
76 p.Log.Debugf("Connected to XDS Server %s, %d projects detected", svr.ID, len(xFlds))
77 for _, prj := range xFlds {
78 newP := svr.FolderToProject(prj)
79 if _, err := p.createUpdate(newP, false, true); err != nil {
80 // Don't consider that as an error (allow support config without CloudSync support)
81 if p.Context.SThg == nil && strings.Contains(err.Error(), "Server doesn't support project type CloudSync") {
85 errMsg += "Error while creating project id " + prj.ID + ": " + err.Error() + "\n "
91 p.Log.Infof("Number of loaded Projects: %d", len(p.projects))
94 return fmt.Errorf(errMsg)
99 // ResolveID Complete a Project ID (helper for user that can use partial ID value)
100 func (p *Projects) ResolveID(id string) (string, error) {
106 for iid := range p.projects {
107 if strings.HasPrefix(iid, id) {
108 match = append(match, iid)
114 } else if len(match) == 0 {
115 return id, fmt.Errorf("Unknown id")
117 return id, fmt.Errorf("Multiple IDs found with provided prefix: " + id)
120 // Get returns the folder config or nil if not existing
121 func (p *Projects) Get(id string) *IPROJECT {
125 fc, exist := p.projects[id]
132 // GetProjectArr returns the config of all folders as an array
133 func (p *Projects) GetProjectArr() []xaapiv1.ProjectConfig {
135 defer pjMutex.Unlock()
137 return p.GetProjectArrUnsafe()
140 // GetProjectArrUnsafe Same as GetProjectArr without mutex protection
141 func (p *Projects) GetProjectArrUnsafe() []xaapiv1.ProjectConfig {
142 conf := []xaapiv1.ProjectConfig{}
143 for _, v := range p.projects {
144 prj := (*v).GetProject()
145 conf = append(conf, *prj)
150 // Add adds a new folder
151 func (p *Projects) Add(newP xaapiv1.ProjectConfig, fromSid, requestURL string) (*xaapiv1.ProjectConfig, error) {
152 prj, err := p.createUpdate(newP, true, false)
157 // Create xds-project.conf file
158 prjConfFile := filepath.Join(prj.ClientPath, "xds-project.conf")
159 if !common.Exists(prjConfFile) {
160 fd, err := os.OpenFile(prjConfFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
162 return prj, fmt.Errorf("Cannot create xds-project.conf: %v", err.Error())
164 fd.WriteString("# XDS project settings\n")
165 fd.WriteString("export XDS_AGENT_URL=" + requestURL + "\n")
166 fd.WriteString("export XDS_PROJECT_ID=" + prj.ID + "\n")
167 if prj.DefaultSdk != "" {
168 fd.WriteString("export XDS_SDK_ID=" + prj.DefaultSdk + "\n")
170 fd.WriteString("#export XDS_SDK_ID=???\n")
172 fd.WriteString("\n# Only disable reset of LD_LIBRARY_PATH if you are absolutely know what you are doing!\n")
173 fd.WriteString("export LD_LIBRARY_PATH=''\n")
177 // Notify client with event
178 if err := p.events.Emit(xaapiv1.EVTProjectAdd, *prj, fromSid); err != nil {
179 p.Log.Warningf("Cannot notify project deletion: %v", err)
185 // CreateUpdate creates or update a folder
186 func (p *Projects) createUpdate(newF xaapiv1.ProjectConfig, create bool, initial bool) (*xaapiv1.ProjectConfig, error) {
190 defer pjMutex.Unlock()
193 if _, exist := p.projects[newF.ID]; create && exist {
194 return nil, fmt.Errorf("ID already exists")
196 if newF.ClientPath == "" {
197 return nil, fmt.Errorf("ClientPath must be set")
199 if newF.ServerID == "" {
200 return nil, fmt.Errorf("Server ID must be set")
204 if svr, exist = p.xdsServers[newF.ServerID]; !exist {
205 return nil, fmt.Errorf("Unknown Server ID %s", newF.ServerID)
208 // Check type supported
209 b, exist := svr.ServerConfig.SupportedSharing[string(newF.Type)]
211 return nil, fmt.Errorf("Server doesn't support project type %s", newF.Type)
214 // Create a new folder object
218 case xaapiv1.TypeCloudSync:
220 fld = NewProjectST(p.Context, svr)
222 return nil, fmt.Errorf("Cloud Sync project not supported")
226 case xaapiv1.TypePathMap:
227 fld = NewProjectPathMap(p.Context, svr)
229 return nil, fmt.Errorf("Unsupported folder type")
232 var newPrj *xaapiv1.ProjectConfig
234 // Add project on server
235 if newPrj, err = fld.Add(newF); err != nil {
236 newF.Status = xaapiv1.StatusErrorConfig
237 log.Printf("ERROR Adding project: %v\n", err)
241 // Just update project config
242 if newPrj, err = fld.Setup(newF); err != nil {
243 newF.Status = xaapiv1.StatusErrorConfig
244 log.Printf("ERROR Updating project: %v\n", err)
251 log.Printf("ERROR project ID empty: %v", newF)
252 return newPrj, fmt.Errorf("Project ID empty")
255 // Add to folders list
256 p.projects[newPrj.ID] = &fld
258 // Force sync to get an initial sync status
259 // (need to defer to be sure that WS events will arrive after HTTP creation reply)
261 time.Sleep(time.Millisecond * 500)
268 // Delete deletes a specific folder
269 func (p *Projects) Delete(id, fromSid string) (xaapiv1.ProjectConfig, error) {
273 defer pjMutex.Unlock()
275 fld := xaapiv1.ProjectConfig{}
276 fc, exist := p.projects[id]
278 return fld, fmt.Errorf("Unknown id")
281 prj := (*fc).GetProject()
283 if err = (*fc).Delete(); err != nil {
287 delete(p.projects, id)
289 // Notify client with event
290 if err := p.events.Emit(xaapiv1.EVTProjectDelete, *prj, fromSid); err != nil {
291 p.Log.Warningf("Cannot notify project deletion: %v", err)
297 // ForceSync Force the synchronization of a folder
298 func (p *Projects) ForceSync(id string) error {
301 return fmt.Errorf("Unknown id")
306 // IsProjectInSync Returns true when folder is in sync
307 func (p *Projects) IsProjectInSync(id string) (bool, error) {
310 return false, fmt.Errorf("Unknown id")
312 return (*fc).IsInSync()
315 // Update Update some field of a project
316 func (p *Projects) Update(id string, prj xaapiv1.ProjectConfig, fromSid string) (*xaapiv1.ProjectConfig, error) {
319 defer pjMutex.Unlock()
321 fc, exist := p.projects[id]
323 return nil, fmt.Errorf("Unknown id")
326 // Copy current in a new object to change nothing in case of an error rises
327 newFld := xaapiv1.ProjectConfig{}
328 reflectme.Copy((*fc).GetProject(), &newFld)
330 // Only update some fields
332 for _, fieldName := range xaapiv1.ProjectConfigUpdatableFields {
333 valNew, err := reflectme.GetField(prj, fieldName)
335 valCur, err := reflectme.GetField(newFld, fieldName)
336 if err == nil && valNew != valCur {
337 err = reflectme.SetField(&newFld, fieldName, valNew)
350 upPrj, err := (*fc).Update(newFld)
355 // Notify client with event
356 if err := p.events.Emit(xaapiv1.EVTProjectChange, *upPrj, fromSid); err != nil {
357 p.Log.Warningf("Cannot notify project change: %v", err)