This repository has been archived by the owner on Dec 2, 2021. It is now read-only.
forked from istio/istio
-
Notifications
You must be signed in to change notification settings - Fork 1
/
commonUtils.go
192 lines (177 loc) · 4.95 KB
/
commonUtils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// Copyright 2017 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package util
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/golang/glog"
)
const (
testSrcDir = "TEST_SRCDIR"
pathPrefix = "io_istio_istio"
runfilesSuffix = ".runfiles"
)
// CreateTempfile creates a tempfile string.
func CreateTempfile(tmpDir, prefix, suffix string) (string, error) {
f, err := ioutil.TempFile(tmpDir, prefix)
if err != nil {
return "", err
}
var tmpName string
if tmpName, err = filepath.Abs(f.Name()); err != nil {
return "", err
}
if err = f.Close(); err != nil {
return "", err
}
if err = os.Remove(tmpName); err != nil {
glog.Errorf("CreateTempfile unable to remove %s", tmpName)
return "", err
}
return tmpName + suffix, nil
}
// WriteTempfile creates a tempfile with the specified contents.
func WriteTempfile(tmpDir, prefix, suffix, contents string) (string, error) {
fname, err := CreateTempfile(tmpDir, prefix, suffix)
if err != nil {
return "", err
}
if err := ioutil.WriteFile(fname, []byte(contents), 0644); err != nil {
return "", err
}
return fname, nil
}
// Shell run command on shell and get back output and error if get one
func Shell(format string, args ...interface{}) (string, error) {
return sh(format, true, args...)
}
// ShellMuteOutput run command on shell and get back output and error if get one
// without logging the output
func ShellMuteOutput(format string, args ...interface{}) (string, error) {
return sh(format, false, args...)
}
func sh(format string, logOutput bool, args ...interface{}) (string, error) {
command := fmt.Sprintf(format, args...)
glog.V(2).Infof("Running command %s", command)
c := exec.Command("sh", "-c", command) // #nosec
bytes, err := c.CombinedOutput()
if logOutput {
glog.V(2).Infof("Command output: \n %s, err: %v", string(bytes[:]), err)
}
if err != nil {
return string(bytes), fmt.Errorf("command failed: %q %v", string(bytes), err)
}
return string(bytes), nil
}
// RunBackground starts a background process and return the Process if succeed
func RunBackground(format string, args ...interface{}) (*os.Process, error) {
command := fmt.Sprintf(format, args...)
glog.Info("RunBackground: ", command)
parts := strings.Split(command, " ")
c := exec.Command(parts[0], parts[1:]...) // #nosec
err := c.Start()
if err != nil {
glog.Errorf("%s, command failed!", command)
return nil, err
}
return c.Process, nil
}
// Record run command and record output into a file
func Record(command, record string) error {
resp, err := Shell(command)
if err != nil {
return err
}
err = ioutil.WriteFile(record, []byte(resp), 0600)
return err
}
// HTTPDownload download from src(url) and store into dst(local file)
func HTTPDownload(dst string, src string) error {
glog.Infof("Start downloading from %s to %s ...\n", src, dst)
var err error
var out *os.File
var resp *http.Response
out, err = os.Create(dst)
if err != nil {
return err
}
defer func() {
if err = out.Close(); err != nil {
glog.Errorf("Error: close file %s, %s", dst, err)
}
}()
resp, err = http.Get(src)
if err != nil {
return err
}
defer func() {
if err = resp.Body.Close(); err != nil {
glog.Errorf("Error: close downloaded file from %s, %s", src, err)
}
}()
if resp.StatusCode != 200 {
return fmt.Errorf("http get request, received unexpected response status: %s", resp.Status)
}
if _, err = io.Copy(out, resp.Body); err != nil {
return err
}
glog.Info("Download successfully!")
return err
}
// CopyFile create a new file to src based on dst
func CopyFile(src, dst string) error {
var in, out *os.File
var err error
in, err = os.Open(src)
if err != nil {
return err
}
defer func() {
if err = in.Close(); err != nil {
glog.Errorf("Error: close file from %s, %s", src, err)
}
}()
out, err = os.Create(dst)
if err != nil {
return err
}
defer func() {
if err = out.Close(); err != nil {
glog.Errorf("Error: close file from %s, %s", dst, err)
}
}()
if _, err = io.Copy(out, in); err != nil {
return err
}
err = out.Sync()
return err
}
// GetResourcePath give "path from WORKSPACE", return absolute path at runtime
func GetResourcePath(p string) string {
if dir, exists := os.LookupEnv(testSrcDir); exists {
return filepath.Join(dir, "workspace", p)
}
binPath, err := os.Executable()
if err != nil {
glog.Warning("Cannot find excutable path")
return p
}
return filepath.Join(binPath+runfilesSuffix, pathPrefix, p)
}