/
os.go
377 lines (342 loc) · 12.8 KB
/
os.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/*
* Copyright (C) 2020-2022 Arm Limited or its affiliates and Contributors. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package platform
import (
"errors"
"fmt"
"os"
"regexp"
"runtime"
"strings"
"time"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/shirou/gopsutil/v3/host"
"github.com/shirou/gopsutil/v3/mem"
"github.com/ARM-software/golang-utils/utils/commonerrors"
)
var (
errNotSupportedByWindows = errors.New("not supported by windows")
// https://learn.microsoft.com/en-us/previous-versions/troubleshoot/winautomation/product-documentation/best-practices/variables/percentage-character-usage-in-notations
// https://ss64.com/nt/syntax-replace.html
windowsVariableExpansionRegexStr = `%(?P<variable>[^:=]*)(:(?P<StrToFind>.*)=(?P<NewString>.*))?%`
// UnixVariableNameRegexString defines the schema for variable names on Unix.
// See https://www.gnu.org/software/bash/manual/bash.html#index-name and https://mywiki.wooledge.org/BashFAQ/006
UnixVariableNameRegexString = "^[a-zA-Z_][a-zA-Z_0-9]*$"
// WindowsVariableNameRegexString defines the schema for variable names on Windows.
// See https://ss64.com/nt/syntax-variables.html
WindowsVariableNameRegexString = "^[A-Za-z#$'()*+,.?@\\[\\]_`{}~][A-Za-z0-9#$'()*+,.?@\\[\\]_`{}~\\s]*$"
errVariableNameInvalid = validation.NewError("validation_is_variable_name", "must be a valid variable name")
// IsWindowsVariableName defines a validation rule for variable names on Windows for use with github.com/go-ozzo/ozzo-validation
IsWindowsVariableName = validation.NewStringRuleWithError(isWindowsVarName, errVariableNameInvalid)
// IsUnixVariableName defines a validation rule for variable names on Unix for use with github.com/go-ozzo/ozzo-validation
IsUnixVariableName = validation.NewStringRuleWithError(isUnixVarName, errVariableNameInvalid)
// IsVariableName defines a validation rule for variable names for use with github.com/go-ozzo/ozzo-validation
IsVariableName = validation.NewStringRuleWithError(isVarName, errVariableNameInvalid)
)
func isWindowsVarName(value string) bool {
if validation.Required.Validate(value) != nil {
return false
}
regex := regexp.MustCompile(WindowsVariableNameRegexString)
return regex.MatchString(value)
}
func isUnixVarName(value string) bool {
if validation.Required.Validate(value) != nil {
return false
}
regex := regexp.MustCompile(UnixVariableNameRegexString)
return regex.MatchString(value)
}
func isVarName(value string) bool {
if IsWindows() {
return isWindowsVarName(value)
}
return isUnixVarName(value)
}
// ConvertError converts a platform error into a commonerrors
func ConvertError(err error) error {
switch {
case err == nil:
return err
case commonerrors.Any(err, commonerrors.ErrNotImplemented, commonerrors.ErrUnsupported):
return err
case IsWindows() && commonerrors.Any(err, errNotSupportedByWindows):
return fmt.Errorf("%w: %v", commonerrors.ErrUnsupported, err.Error())
case commonerrors.CorrespondTo(err, "not supported"):
return fmt.Errorf("%w: %v", commonerrors.ErrUnsupported, err.Error())
default:
return err
// TODO extend with more platform specific errors
}
}
// IsWindows checks whether we are running on Windows or not.
func IsWindows() bool {
return runtime.GOOS == "windows"
}
// LineSeparator returns the line separator.
func LineSeparator() string {
if IsWindows() {
return "\r\n"
}
return UnixLineSeparator()
}
// UnixLineSeparator returns the line separator on Unix platform.
func UnixLineSeparator() string {
return "\n"
}
// Hostname returns the hostname.
func Hostname() (string, error) {
return os.Hostname()
}
// UpTime returns system uptime.
func UpTime() (uptime time.Duration, err error) {
_uptime, err := host.Uptime()
if err != nil {
return
}
uptime = time.Duration(_uptime) * time.Second
return
}
// BootTime returns system uptime.
func BootTime() (bootime time.Time, err error) {
_bootime, err := host.BootTime()
if err != nil {
return
}
bootime = time.Unix(int64(_bootime), 0)
return
}
// NodeName returns the system node name (equivalent to uname -n).
func NodeName() (nodename string, err error) {
info, err := host.Info()
if err != nil {
return
}
nodename = fmt.Sprintf("%v (%v)", info.Hostname, info.HostID)
return
}
// PlatformInformation returns the platform information (equivalent to uname -s).
func PlatformInformation() (information string, err error) {
platform, family, version, err := host.PlatformInformation()
if err != nil {
return
}
information = fmt.Sprintf("%v (%v/%v)", platform, family, version)
return
}
// SystemInformation returns the system information (equivalent to uname -a)
func SystemInformation() (information string, err error) {
hostname, err := Hostname()
if err != nil {
return
}
nodename, err := NodeName()
if err != nil {
return
}
platform, err := PlatformInformation()
if err != nil {
return
}
uptime, err := UpTime()
if err != nil {
return
}
bootime, err := BootTime()
if err != nil {
return
}
information = fmt.Sprintf("Host: %v, Node: %v, Platform: %v, Up time: %v, Boot time: %v", hostname, nodename, platform, uptime, bootime)
return
}
func Uname() (string, error) {
return SystemInformation()
}
type RAM interface {
// GetTotal returns total amount of RAM on this system
GetTotal() uint64
// GetAvailable returns RAM available for programs to allocate
GetAvailable() uint64
// GetUsed returns RAM used by programs
GetUsed() uint64
// GetUsedPercent returns Percentage of RAM used by programs
GetUsedPercent() float64
// GetFree returns kernel's notion of free memory
GetFree() uint64
}
type VirtualMemory struct {
Total uint64
Available uint64
Used uint64
UsedPercent float64
Free uint64
}
func (m *VirtualMemory) GetTotal() uint64 { return m.Total }
func (m *VirtualMemory) GetAvailable() uint64 { return m.Available }
func (m *VirtualMemory) GetUsed() uint64 { return m.Used }
func (m *VirtualMemory) GetUsedPercent() float64 { return m.UsedPercent }
func (m *VirtualMemory) GetFree() uint64 { return m.Free }
func GetRAM() (ram RAM, err error) {
vm, err := mem.VirtualMemory()
if err != nil {
return
}
ram = &VirtualMemory{
Total: vm.Total,
Available: vm.Available,
Used: vm.Used,
UsedPercent: vm.UsedPercent,
Free: vm.Free,
}
return
}
// SubstituteParameter performs parameter substitution on all platforms.
// - the first element is the parameter to substitute
// - if find and replace is also wanted, pass the pattern and the replacement as following arguments in that order.
func SubstituteParameter(parameter ...string) string {
if IsWindows() {
return SubstituteParameterWindows(parameter...)
}
return SubstituteParameterUnix(parameter...)
}
// SubstituteParameterUnix performs Unix parameter substitution:
// See https://tldp.org/LDP/abs/html/parameter-substitution.html
// - the first element is the parameter to substitute
// - if find and replace is also wanted, pass the pattern and the replacement as following arguments in that order.
func SubstituteParameterUnix(parameter ...string) string {
if len(parameter) < 1 || !isUnixVarName(parameter[0]) {
return "${}"
}
if len(parameter) < 3 || parameter[1] == "" {
return fmt.Sprintf("${%v}", parameter[0])
}
return fmt.Sprintf("${%v//%v/%v}", parameter[0], parameter[1], parameter[2])
}
// SubstituteParameterWindows performs Windows parameter substitution:
// See https://ss64.com/nt/syntax-replace.html
// - the first element is the parameter to substitute
// - if find and replace is also wanted, pass the pattern and the replacement as following arguments in that order.
func SubstituteParameterWindows(parameter ...string) string {
if len(parameter) < 1 || !isWindowsVarName(parameter[0]) {
return "%%"
}
if len(parameter) < 3 || parameter[1] == "" {
return "%" + parameter[0] + "%"
}
return "%" + fmt.Sprintf("%v:%v=%v", parameter[0], parameter[1], parameter[2]) + "%"
}
// ExpandParameter expands a variable expressed in a string `s` with its value returned by the mapping function.
// If the mapping function returns a string with variables, it will expand them too if recursive is set to true.
func ExpandParameter(s string, mappingFunc func(string) (string, bool), recursive bool) string {
if IsWindows() {
return ExpandWindowsParameter(s, mappingFunc, recursive)
}
return ExpandUnixParameter(s, mappingFunc, recursive)
}
func newMappingFunc(recursive bool, mappingFunc func(string) (string, bool), expansionFunc func(s string, mappingFunc func(string) (string, bool)) string) func(string) (string, bool) {
if recursive {
return recursiveMapping(mappingFunc, expansionFunc)
}
return mappingFunc
}
func recursiveMapping(mappingFunc func(string) (string, bool), expansionFunc func(s string, mappingFunc func(string) (string, bool)) string) func(string) (string, bool) {
newMappingFunc := func(entry string) (string, bool) {
mappedEntry, found := mappingFunc(entry)
if !found {
return mappedEntry, found
}
newExpanded := expansionFunc(mappedEntry, mappingFunc)
if mappedEntry == newExpanded {
return newExpanded, true
}
return expansionFunc(newExpanded, mappingFunc), true
}
return newMappingFunc
}
// ExpandUnixParameter expands a ${param} or $param in `s` based on the mapping function
// See https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
// os.Expand is used under the bonnet and so, only basic parameter substitution is performed.
// TODO if os.Expand is not good enough, consider using other libraries such as https://github.com/ganbarodigital/go_shellexpand or https://github.com/mvdan/sh
func ExpandUnixParameter(s string, mappingFunc func(string) (string, bool), recursive bool) string {
mapping := newMappingFunc(recursive, mappingFunc, expandUnixParameter)
return expandUnixParameter(s, mapping)
}
func expandUnixParameter(s string, mappingFunc func(string) (string, bool)) string {
return os.Expand(s, func(variable string) string {
mapped, _ := mappingFunc(variable)
return mapped
})
}
// ExpandWindowsParameter expands a %param% in `s` based on the mapping function
// See https://learn.microsoft.com/en-us/previous-versions/troubleshoot/winautomation/product-documentation/best-practices/variables/percentage-character-usage-in-notations
// https://devblogs.microsoft.com/oldnewthing/20060823-00/?p=29993
// https://github.com/golang/go/issues/24848
// WARNING: currently the function only works with one parameter substitution in `s`.
func ExpandWindowsParameter(s string, mappingFunc func(string) (string, bool), recursive bool) string {
mapping := newMappingFunc(recursive, mappingFunc, expandWindowsParameter)
return expandWindowsParameter(s, mapping)
}
func expandWindowsParameter(s string, mappingFunc func(string) (string, bool)) string {
variableRegex := regexp.MustCompile(windowsVariableExpansionRegexStr)
if !variableRegex.MatchString(s) {
return s
}
allMatches := variableRegex.FindAllStringSubmatch(s, -1)
expandedString := s
for i := range allMatches {
old, newStr := expandedVariableWithEdit(allMatches[i], mappingFunc)
expandedString = strings.ReplaceAll(expandedString, old, newStr)
}
return expandedString
}
func expandedVariableWithoutEdit(match []string, mappingFunc func(string) (string, bool)) (string, string, bool) {
if len(match) < 1 {
return "", "", false
}
if len(match) < 2 {
return match[0], "", false
}
variable := match[1]
if len(strings.TrimSpace(variable)) == 0 {
return match[0], match[0], false
}
expandedVariable, found := mappingFunc(variable)
if found {
return match[0], expandedVariable, true
}
return match[0], match[0], false
}
func expandedVariableWithEdit(match []string, mappingFunc func(string) (string, bool)) (string, string) {
if len(match) != 5 {
s, expandedVariable, _ := expandedVariableWithoutEdit(match, mappingFunc)
return s, expandedVariable
}
strToFind := match[3]
newString := match[4]
s, expandedVariable, expanded := expandedVariableWithoutEdit(match, mappingFunc)
if !expanded {
return s, expandedVariable
}
return s, strings.ReplaceAll(expandedVariable, strToFind, newString)
}
// ExpandFromEnvironment expands a string containing variables with values from the environment.
// On unix, it is equivalent to os.ExpandEnv but differs on Windows due to the following issues:
// - https://learn.microsoft.com/en-gb/windows/win32/api/processenv/nf-processenv-expandenvironmentstringsa?redirectedfrom=MSDN
// - https://github.com/golang/go/issues/43763
// - https://github.com/golang/go/issues/24848
func ExpandFromEnvironment(s string, recursive bool) string {
if IsWindows() {
expanded := expandFromEnvironment(s)
if recursive {
newExpanded := expandFromEnvironment(expanded)
if expanded == newExpanded {
return expanded
}
return ExpandFromEnvironment(newExpanded, recursive)
}
return expanded
}
return ExpandUnixParameter(s, os.LookupEnv, recursive)
}