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.
27 common "github.com/iotbzh/xds-common/golib"
28 "github.com/iotbzh/xds-server/lib/xsapiv1"
29 uuid "github.com/satori/go.uuid"
32 // SDKs List of installed SDK
35 Sdks map[string]*CrossSDK
38 stop chan struct{} // signals intentional stop
41 // NewSDKs creates a new instance of SDKs
42 func NewSDKs(ctx *Context) (*SDKs, error) {
45 Sdks: make(map[string]*CrossSDK),
46 stop: make(chan struct{}),
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)
57 s.Log.Infof("SDK scripts dir: %s", scriptsDir)
59 dirs, err := filepath.Glob(path.Join(scriptsDir, "*"))
61 s.Log.Errorf("Error while retrieving SDK scripts: dir=%s, error=%s", scriptsDir, err.Error())
66 defer s.mutex.Unlock()
68 // Foreach directories in scripts/sdk
70 monSdksPath := make(map[string]*xsapiv1.SDKFamilyConfig)
71 for _, d := range dirs {
76 sdksList, err := ListCrossSDK(d, s.Log)
80 s.LogSillyf("'%s' SDKs list: %v", d, sdksList)
82 for _, sdk := range sdksList {
83 cSdk, err := NewCrossSDK(ctx, sdk, d)
85 s.Log.Debugf("Error while processing SDK sdk=%v\n err=%s", sdk, err.Error())
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()
92 s.Sdks[cSdk.sdk.ID] = cSdk
93 if cSdk.sdk.Status == xsapiv1.SdkStatusInstalled {
97 monSdksPath[cSdk.sdk.FamilyConf.RootDir] = &cSdk.sdk.FamilyConf
101 ctx.Log.Debugf("Cross SDKs: %d defined, %d installed", len(s.Sdks), nbInstalled)
103 // Start monitor thread to detect new SDKs
104 if len(monSdksPath) == 0 {
105 s.Log.Warningf("No cross SDKs definition found")
111 // Stop SDKs management
112 func (s *SDKs) Stop() {
116 // monitorSDKInstallation
118 func (s *SDKs) monitorSDKInstallation(monSDKs map[string]*xsapiv1.SDKFamilyConfig) {
120 // Set up a watchpoint listening for inotify-specific events
121 c := make(chan notify.EventInfo, 1)
123 addWatcher := func(rootDir string) error {
124 s.Log.Debugf("SDK Register watcher: rootDir=%s", rootDir)
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)
132 // Add directory watchers
133 for dir := range monSDKs {
134 if err := addWatcher(dir); err != nil {
135 s.Log.Errorln(err.Error())
139 // Wait inotify or stop events
143 s.Log.Debugln("Stop monitorSDKInstallation")
147 s.LogSillyf("monitorSDKInstallation SDKs event %v, path %v\n", ei.Event(), ei.Path())
149 // Filter out all event that doesn't match environment file
150 if !strings.Contains(ei.Path(), "environment-setup-") {
153 dir := path.Dir(ei.Path())
155 sdk, err := s.GetByPath(dir)
157 s.Log.Warningf("Cannot find SDK path to notify creation")
158 s.LogSillyf("event: %v", ei.Event())
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)
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)
180 // ResolveID Complete an SDK ID (helper for user that can use partial ID value)
181 func (s *SDKs) ResolveID(id string) (string, error) {
187 for iid := range s.Sdks {
188 if strings.HasPrefix(iid, id) {
189 match = append(match, iid)
195 } else if len(match) == 0 {
196 return id, fmt.Errorf("Unknown sdk id")
198 return id, fmt.Errorf("Multiple sdk IDs found with provided prefix: " + id)
201 // Get returns an SDK from id
202 func (s *SDKs) Get(id string) *xsapiv1.SDK {
204 defer s.mutex.Unlock()
206 sc, exist := s.Sdks[id]
213 // GetByPath Find a SDK from path
214 func (s *SDKs) GetByPath(path string) (*xsapiv1.SDK, error) {
216 return nil, fmt.Errorf("can't found sdk (empty path)")
218 for _, ss := range s.Sdks {
219 if ss.sdk.Path == path {
223 return nil, fmt.Errorf("not found")
226 // GetAll returns all existing SDKs
227 func (s *SDKs) GetAll() []xsapiv1.SDK {
229 defer s.mutex.Unlock()
230 res := []xsapiv1.SDK{}
231 for _, v := range s.Sdks {
232 res = append(res, *(*v).Get())
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 == "" {
245 defer s.mutex.Unlock()
247 if iid, err := s.ResolveID(id); err == nil {
248 if sdk, exist := s.Sdks[iid]; exist {
249 return sdk.GetEnvCmd()
253 if sdk, exist := s.Sdks[defaultID]; defaultID != "" && exist {
254 return sdk.GetEnvCmd()
257 // Return default env that may be empty
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) {
264 if id != "" && filepath != "" {
265 return nil, fmt.Errorf("invalid parameter, both id and filepath are set")
269 cSdk, exist = s.Sdks[id]
271 return nil, fmt.Errorf("unknown id")
273 } else if filepath != "" {
274 // TODO check that file is accessible
277 return nil, fmt.Errorf("invalid parameter, id or filepath must be set")
281 defer s.mutex.Unlock()
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
289 return &cSdk.sdk, nil
292 // AbortInstall Used to abort SDK installation
293 func (s *SDKs) AbortInstall(id string, timeout int) (*xsapiv1.SDK, error) {
296 return nil, fmt.Errorf("invalid parameter")
298 cSdk, exist := s.Sdks[id]
300 return nil, fmt.Errorf("unknown id")
304 defer s.mutex.Unlock()
306 err := cSdk.AbortInstallRemove(timeout)
308 return &cSdk.sdk, err
311 // Remove Used to uninstall a SDK
312 func (s *SDKs) Remove(id string) (*xsapiv1.SDK, error) {
314 defer s.mutex.Unlock()
316 cSdk, exist := s.Sdks[id]
318 return nil, fmt.Errorf("unknown id")
322 defer s.mutex.Unlock()
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
332 // Don't delete it from s.Sdks
333 // (always keep sdk reference to allow for example re-install)