8ea4d4057a9cca0f38db8696620b6e7272c0a895
[ric-plt/appmgr.git] / pkg / util / util.go
1 /*
2 ==================================================================================
3   Copyright (c) 2019 AT&T Intellectual Property.
4   Copyright (c) 2019 Nokia
5
6    Licensed under the Apache License, Version 2.0 (the "License");
7    you may not use this file except in compliance with the License.
8    You may obtain a copy of the License at
9
10        http://www.apache.org/licenses/LICENSE-2.0
11
12    Unless required by applicable law or agreed to in writing, software
13    distributed under the License is distributed on an "AS IS" BASIS,
14    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15    See the License for the specific language governing permissions and
16    limitations under the License.
17 ==================================================================================
18 */
19
20 package util
21
22 import (
23         "bytes"
24         "errors"
25         "github.com/spf13/viper"
26         "os"
27         "os/exec"
28         "strings"
29         "time"
30
31         "gerrit.oran-osc.org/r/ric-plt/appmgr/pkg/appmgr"
32 )
33
34 var execCommand = exec.Command
35
36 func Exec(args string) (out []byte, err error) {
37         cmd := execCommand("/bin/sh", "-c", args)
38
39         var stdout bytes.Buffer
40         var stderr bytes.Buffer
41         cmd.Stdout = &stdout
42         cmd.Stderr = &stderr
43
44         appmgr.Logger.Info("Running command: %s ", cmd.Args)
45         for i := 0; i < viper.GetInt("helm.retry"); i++ {
46                 if err = cmd.Run(); err != nil {
47                         appmgr.Logger.Error("Command failed: %v - %s, retrying", err.Error(), stderr.String())
48                         time.Sleep(time.Duration(2) * time.Second)
49                         continue
50                 }
51                 break
52         }
53
54         if err == nil && !strings.HasSuffix(os.Args[0], ".test") {
55                 appmgr.Logger.Info("command success: %s", stdout.String())
56                 return stdout.Bytes(), nil
57         }
58
59         return stdout.Bytes(), errors.New(stderr.String())
60 }
61
62 var HelmExec = func(args string) (out []byte, err error) {
63         return Exec(strings.Join([]string{"helm", args}, " "))
64 }
65
66 var KubectlExec = func(args string) (out []byte, err error) {
67         return Exec(strings.Join([]string{"kubectl", args}, " "))
68 }