7c912c42b9730486897da391a8b157510f3eed42
[src/xds/xds-server.git] / lib / xdsserver / sdk.go
1 /*
2  * Copyright (C) 2017-2018 "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         "encoding/json"
22         "fmt"
23         "os/exec"
24         "path"
25         "strconv"
26         "strings"
27         "time"
28
29         common "gerrit.automotivelinux.org/gerrit/src/xds/xds-common.git/golib"
30         "gerrit.automotivelinux.org/gerrit/src/xds/xds-common.git/golib/eows"
31         "gerrit.automotivelinux.org/gerrit/src/xds/xds-server/lib/xsapiv1"
32         "github.com/Sirupsen/logrus"
33         uuid "github.com/satori/go.uuid"
34 )
35
36 // Definition of scripts used to managed SDKs
37 const (
38         scriptAdd          = "add"
39         scriptDbDump       = "db-dump"
40         scriptDbUpdate     = "db-update"
41         scriptGetFamConfig = "get-family-config"
42         scriptGetSdkInfo   = "get-sdk-info"
43         scriptRemove       = "remove"
44 )
45
46 var scriptsAll = []string{
47         scriptAdd,
48         scriptDbDump,
49         scriptDbUpdate,
50         scriptGetFamConfig,
51         scriptGetSdkInfo,
52         scriptRemove,
53 }
54
55 var sdkCmdID = 0
56
57 // CrossSDK Hold SDK config
58 type CrossSDK struct {
59         *Context
60         sdk        xsapiv1.SDK
61         scripts    map[string]string
62         installCmd *eows.ExecOverWS
63         removeCmd  *eows.ExecOverWS
64 }
65
66 // ListCrossSDK List all available and installed SDK  (call "db-dump" script)
67 func ListCrossSDK(scriptDir string, update bool, log *logrus.Logger) ([]xsapiv1.SDK, error) {
68         sdksList := []xsapiv1.SDK{}
69
70         // First update sdk DB when requested
71         if update {
72                 out, err := UpdateSDKDb(scriptDir, log)
73                 if err != nil {
74                         log.Errorf("SDK DB update failure (%v): %v", err, out)
75                         return sdksList, fmt.Errorf("Error while updating SDK DB (%v)", err)
76                 }
77         }
78
79         // Retrieve SDKs list and info
80         cmd := exec.Command(path.Join(scriptDir, scriptDbDump))
81         stdout, err := cmd.CombinedOutput()
82         if err != nil {
83                 return sdksList, fmt.Errorf("Cannot get sdks list: %v", err)
84         }
85
86         if err = json.Unmarshal(stdout, &sdksList); err != nil {
87                 log.Errorf("SDK %s script output:\n%v\n", scriptDbDump, string(stdout))
88                 return sdksList, fmt.Errorf("Cannot decode sdk list %v", err)
89         }
90
91         return sdksList, nil
92 }
93
94 // GetSDKInfo Used get-sdk-info script to extract SDK get info from a SDK file/tarball
95 func GetSDKInfo(scriptDir, url, filename, md5sum string, log *logrus.Logger) (xsapiv1.SDK, error) {
96         sdk := xsapiv1.SDK{}
97
98         args := []string{}
99         if url != "" {
100                 args = append(args, "--url", url)
101         } else if filename != "" {
102                 args = append(args, "--file", filename)
103                 if md5sum != "" {
104                         args = append(args, "--md5", md5sum)
105                 }
106         } else {
107                 return sdk, fmt.Errorf("url of filename must be set")
108         }
109
110         cmd := exec.Command(path.Join(scriptDir, scriptGetSdkInfo), args...)
111         stdout, err := cmd.CombinedOutput()
112         if err != nil {
113                 return sdk, fmt.Errorf("%v %v", string(stdout), err)
114         }
115
116         if err = json.Unmarshal(stdout, &sdk); err != nil {
117                 log.Errorf("SDK %s script output:\n%v\n", scriptGetSdkInfo, string(stdout))
118                 return sdk, fmt.Errorf("Cannot decode sdk info %v", err)
119         }
120         return sdk, nil
121 }
122
123 // UpdateSDKDb Used db-update script to update SDK database
124 func UpdateSDKDb(scriptDir string, log *logrus.Logger) (string, error) {
125         args := []string{}
126         cmd := exec.Command(path.Join(scriptDir, scriptDbUpdate), args...)
127         stdout, err := cmd.CombinedOutput()
128
129         return string(stdout), err
130 }
131
132 // NewCrossSDK creates a new instance of CrossSDK
133 func NewCrossSDK(ctx *Context, sdk xsapiv1.SDK, scriptDir string) (*CrossSDK, error) {
134         s := CrossSDK{
135                 Context: ctx,
136                 sdk:     sdk,
137                 scripts: make(map[string]string),
138         }
139
140         // Execute get-config script to retrieve SDK configuration
141         getConfFile := path.Join(scriptDir, scriptGetFamConfig)
142         if !common.Exists(getConfFile) {
143                 return &s, fmt.Errorf("'%s' script file not found in %s", scriptGetFamConfig, scriptDir)
144         }
145
146         cmd := exec.Command(getConfFile)
147         stdout, err := cmd.CombinedOutput()
148         if err != nil {
149                 return &s, fmt.Errorf("Cannot get sdk config using %s: %v", getConfFile, err)
150         }
151
152         err = json.Unmarshal(stdout, &s.sdk.FamilyConf)
153         if err != nil {
154                 s.Log.Errorf("SDK config script output:\n%v\n", string(stdout))
155                 return &s, fmt.Errorf("Cannot decode sdk config %v", err)
156         }
157         famName := s.sdk.FamilyConf.FamilyName
158
159         // Sanity check
160         if s.sdk.FamilyConf.RootDir == "" {
161                 return &s, fmt.Errorf("SDK config not valid (rootDir not set)")
162         }
163         if s.sdk.FamilyConf.EnvSetupFile == "" {
164                 return &s, fmt.Errorf("SDK config not valid (envSetupFile not set)")
165         }
166
167         // Check that other mandatory scripts are present
168         for _, scr := range scriptsAll {
169                 s.scripts[scr] = path.Join(scriptDir, scr)
170                 if !common.Exists(s.scripts[scr]) {
171                         return &s, fmt.Errorf("Script named '%s' missing in SDK family '%s'", scr, famName)
172                 }
173         }
174
175         // Fixed default fields value
176         sdk.LastError = ""
177         if sdk.Status == "" {
178                 sdk.Status = xsapiv1.SdkStatusNotInstalled
179         }
180
181         // Sanity check
182         errMsg := "Invalid SDK definition "
183         if sdk.Name == "" {
184                 return &s, fmt.Errorf(errMsg + "(name not set)")
185         } else if sdk.Profile == "" {
186                 return &s, fmt.Errorf(errMsg + "(profile not set)")
187         } else if sdk.Version == "" {
188                 return &s, fmt.Errorf(errMsg + "(version not set)")
189         } else if sdk.Arch == "" {
190                 return &s, fmt.Errorf(errMsg + "(arch not set)")
191         }
192         if sdk.Status == xsapiv1.SdkStatusInstalled {
193                 if sdk.SetupFile == "" {
194                         return &s, fmt.Errorf(errMsg + "(setupFile not set)")
195                 } else if !common.Exists(sdk.SetupFile) {
196                         return &s, fmt.Errorf(errMsg + "(setupFile not accessible)")
197                 }
198                 if sdk.Path == "" {
199                         return &s, fmt.Errorf(errMsg + "(path not set)")
200                 } else if !common.Exists(sdk.Path) {
201                         return &s, fmt.Errorf(errMsg + "(path not accessible)")
202                 }
203         }
204
205         // Use V3 to ensure that we get same uuid on restart
206         nm := s.sdk.Name
207         if nm == "" {
208                 nm = s.sdk.Profile + "_" + s.sdk.Arch + "_" + s.sdk.Version
209         }
210         s.sdk.ID = uuid.NewV3(uuid.FromStringOrNil("sdks"), nm).String()
211
212         s.LogSillyf("New SDK: ID=%v, Family=%s, Name=%v", s.sdk.ID[:8], s.sdk.FamilyConf.FamilyName, s.sdk.Name)
213
214         return &s, nil
215 }
216
217 // Install a SDK (non blocking command, IOW run in background)
218 func (s *CrossSDK) Install(file string, force bool, timeout int, args []string, sess *ClientSession) error {
219
220         if s.sdk.Status == xsapiv1.SdkStatusInstalled {
221                 return fmt.Errorf("already installed")
222         }
223         if s.sdk.Status == xsapiv1.SdkStatusInstalling {
224                 return fmt.Errorf("installation in progress")
225         }
226
227         // Compute command args
228         cmdArgs := []string{}
229         if file != "" {
230                 cmdArgs = append(cmdArgs, "--file", file)
231         } else {
232                 cmdArgs = append(cmdArgs, "--url", s.sdk.URL)
233         }
234         if force {
235                 cmdArgs = append(cmdArgs, "--force")
236         }
237
238         // Append additional args (passthrough arguments)
239         if len(args) > 0 {
240                 cmdArgs = append(cmdArgs, args...)
241         }
242
243         // Unique command id
244         sdkCmdID++
245         cmdID := "sdk-install-" + strconv.Itoa(sdkCmdID)
246
247         // Create new instance to execute command and sent output over WS
248         s.installCmd = eows.New(s.scripts[scriptAdd], cmdArgs, sess.IOSocket, sess.ID, cmdID)
249         s.installCmd.Log = s.Log
250         // TODO: enable Term s.installCmd.PtyMode = true
251         s.installCmd.LineTimeSpan = 500 * time.Millisecond.Nanoseconds()
252         if timeout > 0 {
253                 s.installCmd.CmdExecTimeout = timeout
254         } else {
255                 s.installCmd.CmdExecTimeout = 30 * 60 // default 30min
256         }
257
258         // Define callback for output (stdout+stderr)
259         s.installCmd.OutputCB = func(e *eows.ExecOverWS, bStdout, bStderr []byte) {
260
261                 stdout := string(bStdout)
262                 stderr := string(bStderr)
263
264                 // paranoia
265                 data := e.UserData
266                 sdkID := (*data)["SDKID"].(string)
267                 if sdkID != s.sdk.ID {
268                         s.Log.Errorln("BUG: sdk ID differs: %v != %v", sdkID, s.sdk.ID)
269                 }
270
271                 // IO socket can be nil when disconnected
272                 so := s.sessions.IOSocketGet(e.Sid)
273                 if so == nil {
274                         s.Log.Infof("%s not emitted: WS closed (sid:%s, msgid:%s)", xsapiv1.EVTSDKManagement, e.Sid, e.CmdID)
275                         return
276                 }
277
278                 if s.LogLevelSilly {
279                         s.Log.Debugf("%s emitted - WS sid[4:] %s - id:%s - SDK ID:%s:", xsapiv1.EVTSDKManagement, e.Sid[4:], e.CmdID, sdkID[:16])
280                         if stdout != "" {
281                                 s.Log.Debugf("STDOUT <<%v>>", strings.Replace(stdout, "\n", "\\n", -1))
282                         }
283                         if stderr != "" {
284                                 s.Log.Debugf("STDERR <<%v>>", strings.Replace(stderr, "\n", "\\n", -1))
285                         }
286                 }
287
288                 err := (*so).Emit(xsapiv1.EVTSDKManagement, xsapiv1.SDKManagementMsg{
289                         CmdID:     e.CmdID,
290                         Timestamp: time.Now().String(),
291                         Action:    xsapiv1.SdkMgtActionInstall,
292                         Sdk:       s.sdk,
293                         Progress:  0, // TODO add progress
294                         Exited:    false,
295                         Stdout:    stdout,
296                         Stderr:    stderr,
297                 })
298                 if err != nil {
299                         s.Log.Errorf("WS Emit : %v", err)
300                 }
301         }
302
303         // Define callback for output
304         s.installCmd.ExitCB = func(e *eows.ExecOverWS, code int, exitError error) {
305                 // paranoia
306                 data := e.UserData
307                 sdkID := (*data)["SDKID"].(string)
308                 if sdkID != s.sdk.ID {
309                         s.Log.Errorln("BUG: sdk ID differs: %v != %v", sdkID, s.sdk.ID)
310                 }
311
312                 s.Log.Infof("Command SDK ID %s [Cmd ID %s]  exited: code %d, exitError: %v", sdkID[:16], e.CmdID, code, exitError)
313
314                 // IO socket can be nil when disconnected
315                 so := s.sessions.IOSocketGet(e.Sid)
316                 if so == nil {
317                         s.Log.Infof("%s (exit) not emitted - WS closed (id:%s)", xsapiv1.EVTSDKManagement, e.CmdID)
318                         return
319                 }
320
321                 // Update SDK status
322                 if code == 0 && exitError == nil {
323                         s.sdk.LastError = ""
324                         s.sdk.Status = xsapiv1.SdkStatusInstalled
325
326                         // FIXME: better update it using monitoring install dir (inotify)
327                         // (see sdks.go / monitorSDKInstallation )
328                         // Update SetupFile when n
329                         if s.sdk.SetupFile == "" {
330                                 sdkDef, err := GetSDKInfo(s.sdk.FamilyConf.ScriptsDir, s.sdk.URL, "", "", s.Log)
331                                 if err != nil || sdkDef.SetupFile == "" {
332                                         s.Log.Errorf("GetSDKInfo error: %v", err)
333                                         code = 1
334                                         s.sdk.LastError = "Installation failed (cannot init SetupFile path)"
335                                         s.sdk.Status = xsapiv1.SdkStatusNotInstalled
336                                 } else {
337                                         s.sdk.SetupFile = sdkDef.SetupFile
338                                 }
339                         }
340
341                 } else {
342                         s.sdk.LastError = "Installation failed (code " + strconv.Itoa(code) +
343                                 ")"
344                         if exitError != nil {
345                                 s.sdk.LastError = ". Error: " + exitError.Error()
346                         }
347                         s.sdk.Status = xsapiv1.SdkStatusNotInstalled
348                 }
349
350                 emitErr := ""
351                 if exitError != nil {
352                         emitErr = exitError.Error()
353                 }
354                 if emitErr == "" && s.sdk.LastError != "" {
355                         emitErr = s.sdk.LastError
356                 }
357
358                 // Emit event
359                 errSoEmit := (*so).Emit(xsapiv1.EVTSDKManagement, xsapiv1.SDKManagementMsg{
360                         CmdID:     e.CmdID,
361                         Timestamp: time.Now().String(),
362                         Action:    xsapiv1.SdkMgtActionInstall,
363                         Sdk:       s.sdk,
364                         Progress:  100,
365                         Exited:    true,
366                         Code:      code,
367                         Error:     emitErr,
368                 })
369                 if errSoEmit != nil {
370                         s.Log.Errorf("WS Emit EVTSDKManagement : %v", errSoEmit)
371                 }
372
373                 errSoEmit = s.events.Emit(xsapiv1.EVTSDKStateChange, s.sdk, e.Sid)
374                 if errSoEmit != nil {
375                         s.Log.Errorf("WS Emit EVTSDKStateChange : %v", errSoEmit)
376                 }
377
378                 // Cleanup command for the next time
379                 s.installCmd = nil
380         }
381
382         // User data (used within callbacks)
383         data := make(map[string]interface{})
384         data["SDKID"] = s.sdk.ID
385         s.installCmd.UserData = &data
386
387         // Start command execution
388         s.Log.Infof("Install SDK %s: cmdID=%v, cmd=%v, args=%v", s.sdk.Name, s.installCmd.CmdID, s.installCmd.Cmd, s.installCmd.Args)
389
390         s.sdk.Status = xsapiv1.SdkStatusInstalling
391         s.sdk.LastError = ""
392
393         err := s.installCmd.Start()
394
395         return err
396 }
397
398 // AbortInstallRemove abort an install or remove command
399 func (s *CrossSDK) AbortInstallRemove(timeout int) error {
400
401         if s.installCmd == nil {
402                 return fmt.Errorf("no installation in progress for this sdk")
403         }
404
405         s.sdk.Status = xsapiv1.SdkStatusNotInstalled
406         return s.installCmd.Signal("SIGKILL")
407 }
408
409 // Remove Used to remove/uninstall a SDK
410 func (s *CrossSDK) Remove(timeout int, sess *ClientSession) error {
411
412         if s.sdk.Status != xsapiv1.SdkStatusInstalled {
413                 return fmt.Errorf("this sdk is not installed")
414         }
415
416         // IO socket can be nil when disconnected
417         so := s.sessions.IOSocketGet(sess.ID)
418         if so == nil {
419                 return fmt.Errorf("Cannot retrieve socket ")
420         }
421
422         s.sdk.Status = xsapiv1.SdkStatusUninstalling
423
424         // Notify state change
425         if err := s.events.Emit(xsapiv1.EVTSDKStateChange, s.sdk, sess.ID); err != nil {
426                 s.Log.Warningf("Cannot notify SDK remove: %v", err)
427         }
428
429         script := s.scripts[scriptRemove]
430         args := s.sdk.Path
431         s.Log.Infof("Uninstall SDK %s: script=%v args=%v", s.sdk.Name, script, args)
432
433         // Notify start removing
434         evData := xsapiv1.SDKManagementMsg{
435                 Timestamp: time.Now().String(),
436                 Action:    xsapiv1.SdkMgtActionRemove,
437                 Sdk:       s.sdk,
438                 Progress:  0,
439                 Exited:    false,
440                 Code:      0,
441                 Error:     "",
442         }
443         if errEmit := (*so).Emit(xsapiv1.EVTSDKManagement, evData); errEmit != nil {
444                 s.Log.Warningf("Cannot notify EVTSDKManagement end: %v", errEmit)
445         }
446
447         // Run command to remove SDK
448         cmd := exec.Command(script, args)
449         stdout, err := cmd.CombinedOutput()
450
451         s.sdk.Status = xsapiv1.SdkStatusNotInstalled
452         s.Log.Debugf("SDK uninstall err %v, output:\n %v", err, string(stdout))
453
454         // Emit end of removing process
455         evData = xsapiv1.SDKManagementMsg{
456                 Timestamp: time.Now().String(),
457                 Action:    xsapiv1.SdkMgtActionRemove,
458                 Sdk:       s.sdk,
459                 Progress:  100,
460                 Exited:    true,
461                 Code:      0,
462                 Error:     "",
463         }
464
465         // Update error code on error
466         if err != nil {
467                 evData.Code = 1
468                 evData.Error = err.Error()
469         }
470
471         if errEmit := (*so).Emit(xsapiv1.EVTSDKManagement, evData); errEmit != nil {
472                 s.Log.Warningf("Cannot notify EVTSDKManagement end: %v", errEmit)
473         }
474
475         // Notify state change
476         if errEmit := s.events.Emit(xsapiv1.EVTSDKStateChange, s.sdk, sess.ID); errEmit != nil {
477                 s.Log.Warningf("Cannot notify EVTSDKStateChange end: %v", errEmit)
478         }
479
480         if err != nil {
481                 return fmt.Errorf("Error while uninstalling sdk: %v", err)
482         }
483         return nil
484 }
485
486 // Get Return SDK definition
487 func (s *CrossSDK) Get() *xsapiv1.SDK {
488         return &s.sdk
489 }
490
491 // GetEnvCmd returns the command used to initialized the environment
492 func (s *CrossSDK) GetEnvCmd() []string {
493         if s.sdk.SetupFile == "" {
494                 return []string{}
495         }
496         return []string{"source", s.sdk.SetupFile}
497
498 }