Added SDKs management support.
[src/xds/xds-server.git] / lib / xdsserver / sdks.go
1 /*
2  * Copyright (C) 2017 "IoT.bzh"
3  * Author Sebastien Douheret <sebastien@iot.bzh>
4  *
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
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  */
17
18 package xdsserver
19
20 import (
21         "fmt"
22         "path"
23         "path/filepath"
24         "strings"
25         "sync"
26
27         common "github.com/iotbzh/xds-common/golib"
28         "github.com/iotbzh/xds-server/lib/xsapiv1"
29         uuid "github.com/satori/go.uuid"
30 )
31
32 // SDKs List of installed SDK
33 type SDKs struct {
34         *Context
35         Sdks map[string]*CrossSDK
36
37         mutex sync.Mutex
38         stop  chan struct{} // signals intentional stop
39 }
40
41 // NewSDKs creates a new instance of SDKs
42 func NewSDKs(ctx *Context) (*SDKs, error) {
43         s := SDKs{
44                 Context: ctx,
45                 Sdks:    make(map[string]*CrossSDK),
46                 stop:    make(chan struct{}),
47         }
48
49         scriptsDir := ctx.Config.FileConf.SdkScriptsDir
50         if !common.Exists(scriptsDir) {
51                 // allow to use scripts/sdk in debug mode
52                 scriptsDir = filepath.Join(filepath.Dir(ctx.Config.FileConf.SdkScriptsDir), "scripts", "sdks")
53                 if !common.Exists(scriptsDir) {
54                         return &s, fmt.Errorf("scripts directory doesn't exist (%v)", scriptsDir)
55                 }
56         }
57         s.Log.Infof("SDK scripts dir: %s", scriptsDir)
58
59         dirs, err := filepath.Glob(path.Join(scriptsDir, "*"))
60         if err != nil {
61                 s.Log.Errorf("Error while retrieving SDK scripts: dir=%s, error=%s", scriptsDir, err.Error())
62                 return &s, err
63         }
64
65         s.mutex.Lock()
66         defer s.mutex.Unlock()
67
68         // Foreach directories in scripts/sdk
69         nbInstalled := 0
70         monSdksPath := make(map[string]*xsapiv1.SDKFamilyConfig)
71         for _, d := range dirs {
72                 if !common.IsDir(d) {
73                         continue
74                 }
75
76                 sdksList, err := ListCrossSDK(d, s.Log)
77                 if err != nil {
78                         return &s, err
79                 }
80                 s.LogSillyf("'%s' SDKs list: %v", d, sdksList)
81
82                 for _, sdk := range sdksList {
83                         cSdk, err := NewCrossSDK(ctx, sdk, d)
84                         if err != nil {
85                                 s.Log.Debugf("Error while processing SDK sdk=%v\n err=%s", sdk, err.Error())
86                                 continue
87                         }
88                         if _, exist := s.Sdks[cSdk.sdk.ID]; exist {
89                                 s.Log.Warningf("Duplicate SDK ID : %v", cSdk.sdk.ID)
90                                 cSdk.sdk.ID += "_DUPLICATE_" + uuid.NewV1().String()
91                         }
92                         s.Sdks[cSdk.sdk.ID] = cSdk
93                         if cSdk.sdk.Status == xsapiv1.SdkStatusInstalled {
94                                 nbInstalled++
95                         }
96
97                         monSdksPath[cSdk.sdk.FamilyConf.RootDir] = &cSdk.sdk.FamilyConf
98                 }
99         }
100
101         ctx.Log.Debugf("Cross SDKs: %d defined, %d installed", len(s.Sdks), nbInstalled)
102
103         // Start monitor thread to detect new SDKs
104         if len(monSdksPath) == 0 {
105                 s.Log.Warningf("No cross SDKs definition found")
106         }
107
108         return &s, nil
109 }
110
111 // Stop SDKs management
112 func (s *SDKs) Stop() {
113         close(s.stop)
114 }
115
116 // monitorSDKInstallation
117 /* TODO: cleanup
118 func (s *SDKs) monitorSDKInstallation(monSDKs map[string]*xsapiv1.SDKFamilyConfig) {
119
120         // Set up a watchpoint listening for inotify-specific events
121         c := make(chan notify.EventInfo, 1)
122
123         addWatcher := func(rootDir string) error {
124                 s.Log.Debugf("SDK Register watcher: rootDir=%s", rootDir)
125
126                 if err := notify.Watch(rootDir+"/...", c, notify.Create, notify.Remove); err != nil {
127                         return fmt.Errorf("SDK monitor: rootDir=%v err=%v", rootDir, err)
128                 }
129                 return nil
130         }
131
132         // Add directory watchers
133         for dir := range monSDKs {
134                 if err := addWatcher(dir); err != nil {
135                         s.Log.Errorln(err.Error())
136                 }
137         }
138
139         // Wait inotify or stop events
140         for {
141                 select {
142                 case <-s.stop:
143                         s.Log.Debugln("Stop monitorSDKInstallation")
144                         notify.Stop(c)
145                         return
146                 case ei := <-c:
147                         s.LogSillyf("monitorSDKInstallation SDKs event %v, path %v\n", ei.Event(), ei.Path())
148
149                         // Filter out all event that doesn't match environment file
150                         if !strings.Contains(ei.Path(), "environment-setup-") {
151                                 continue
152                         }
153                         dir := path.Dir(ei.Path())
154
155                         sdk, err := s.GetByPath(dir)
156                         if err != nil {
157                                 s.Log.Warningf("Cannot find SDK path to notify creation")
158                                 s.LogSillyf("event: %v", ei.Event())
159                                 continue
160                         }
161
162                         switch ei.Event() {
163                         case notify.Create:
164                                 // Emit Folder state change event
165                                 if err := s.events.Emit(xsapiv1.EVTSDKInstall, sdk, ""); err != nil {
166                                         s.Log.Warningf("Cannot notify SDK install: %v", err)
167                                 }
168
169                         case notify.Remove, notify.InMovedFrom:
170                                 // Emit Folder state change event
171                                 if err := s.events.Emit(xsapiv1.EVTSDKRemove, sdk, ""); err != nil {
172                                         s.Log.Warningf("Cannot notify SDK remove: %v", err)
173                                 }
174                         }
175                 }
176         }
177 }
178 */
179
180 // ResolveID Complete an SDK ID (helper for user that can use partial ID value)
181 func (s *SDKs) ResolveID(id string) (string, error) {
182         if id == "" {
183                 return "", nil
184         }
185
186         match := []string{}
187         for iid := range s.Sdks {
188                 if strings.HasPrefix(iid, id) {
189                         match = append(match, iid)
190                 }
191         }
192
193         if len(match) == 1 {
194                 return match[0], nil
195         } else if len(match) == 0 {
196                 return id, fmt.Errorf("Unknown sdk id")
197         }
198         return id, fmt.Errorf("Multiple sdk IDs found with provided prefix: " + id)
199 }
200
201 // Get returns an SDK from id
202 func (s *SDKs) Get(id string) *xsapiv1.SDK {
203         s.mutex.Lock()
204         defer s.mutex.Unlock()
205
206         sc, exist := s.Sdks[id]
207         if !exist {
208                 return nil
209         }
210         return (*sc).Get()
211 }
212
213 // GetByPath Find a SDK from path
214 func (s *SDKs) GetByPath(path string) (*xsapiv1.SDK, error) {
215         if path == "" {
216                 return nil, fmt.Errorf("can't found sdk (empty path)")
217         }
218         for _, ss := range s.Sdks {
219                 if ss.sdk.Path == path {
220                         return ss.Get(), nil
221                 }
222         }
223         return nil, fmt.Errorf("not found")
224 }
225
226 // GetAll returns all existing SDKs
227 func (s *SDKs) GetAll() []xsapiv1.SDK {
228         s.mutex.Lock()
229         defer s.mutex.Unlock()
230         res := []xsapiv1.SDK{}
231         for _, v := range s.Sdks {
232                 res = append(res, *(*v).Get())
233         }
234         return res
235 }
236
237 // GetEnvCmd returns the command used to initialized the environment for an SDK
238 func (s *SDKs) GetEnvCmd(id string, defaultID string) []string {
239         if id == "" && defaultID == "" {
240                 // no env cmd
241                 return []string{}
242         }
243
244         s.mutex.Lock()
245         defer s.mutex.Unlock()
246
247         if iid, err := s.ResolveID(id); err == nil {
248                 if sdk, exist := s.Sdks[iid]; exist {
249                         return sdk.GetEnvCmd()
250                 }
251         }
252
253         if sdk, exist := s.Sdks[defaultID]; defaultID != "" && exist {
254                 return sdk.GetEnvCmd()
255         }
256
257         // Return default env that may be empty
258         return []string{}
259 }
260
261 // Install Used to install a new SDK
262 func (s *SDKs) Install(id, filepath string, force bool, timeout int, sess *ClientSession) (*xsapiv1.SDK, error) {
263         var cSdk *CrossSDK
264         if id != "" && filepath != "" {
265                 return nil, fmt.Errorf("invalid parameter, both id and filepath are set")
266         }
267         if id != "" {
268                 var exist bool
269                 cSdk, exist = s.Sdks[id]
270                 if !exist {
271                         return nil, fmt.Errorf("unknown id")
272                 }
273         } else if filepath != "" {
274                 // TODO check that file is accessible
275
276         } else {
277                 return nil, fmt.Errorf("invalid parameter, id or filepath must be set")
278         }
279
280         s.mutex.Lock()
281         defer s.mutex.Unlock()
282
283         // Launch script to install
284         // (note that add event will be generated by monitoring thread)
285         if err := cSdk.Install(filepath, force, timeout, sess); err != nil {
286                 return &cSdk.sdk, err
287         }
288
289         return &cSdk.sdk, nil
290 }
291
292 // AbortInstall Used to abort SDK installation
293 func (s *SDKs) AbortInstall(id string, timeout int) (*xsapiv1.SDK, error) {
294
295         if id == "" {
296                 return nil, fmt.Errorf("invalid parameter")
297         }
298         cSdk, exist := s.Sdks[id]
299         if !exist {
300                 return nil, fmt.Errorf("unknown id")
301         }
302
303         s.mutex.Lock()
304         defer s.mutex.Unlock()
305
306         err := cSdk.AbortInstallRemove(timeout)
307
308         return &cSdk.sdk, err
309 }
310
311 // Remove Used to uninstall a SDK
312 func (s *SDKs) Remove(id string) (*xsapiv1.SDK, error) {
313         s.mutex.Lock()
314         defer s.mutex.Unlock()
315
316         cSdk, exist := s.Sdks[id]
317         if !exist {
318                 return nil, fmt.Errorf("unknown id")
319         }
320
321         s.mutex.Lock()
322         defer s.mutex.Unlock()
323
324         // Launch script to remove/uninstall
325         // (note that remove event will be generated by monitoring thread)
326         if err := cSdk.Remove(); err != nil {
327                 return &cSdk.sdk, err
328         }
329
330         sdk := cSdk.sdk
331
332         // Don't delete it from s.Sdks
333         // (always keep sdk reference to allow for example re-install)
334
335         return &sdk, nil
336 }