forked from chaosblade-io/chaosblade-exec-os
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_append.go
261 lines (231 loc) · 7.94 KB
/
file_append.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
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* 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 file
import (
"context"
"encoding/base64"
"fmt"
"github.com/chaosblade-io/chaosblade-spec-go/log"
"github.com/deepsola/chaosblade-exec-os/exec"
"math/rand"
"regexp"
"strconv"
"strings"
"time"
"github.com/chaosblade-io/chaosblade-spec-go/spec"
"github.com/deepsola/chaosblade-exec-os/exec/category"
)
const AppendFileBin = "chaos_appendfile"
type FileAppendActionSpec struct {
spec.BaseExpActionCommandSpec
}
func NewFileAppendActionSpec() spec.ExpActionCommandSpec {
return &FileAppendActionSpec{
spec.BaseExpActionCommandSpec{
ActionMatchers: fileCommFlags,
ActionFlags: []spec.ExpFlagSpec{
&spec.ExpFlag{
Name: "content",
Desc: "append content",
Required: true,
},
&spec.ExpFlag{
Name: "count",
Desc: "the number of append count, must be a positive integer, default 1",
},
&spec.ExpFlag{
Name: "interval",
Desc: "append interval, must be a positive integer",
},
&spec.ExpFlag{
Name: "escape",
Desc: "symbols to escape, use --escape, at this --count is invalid",
NoArgs: true,
},
&spec.ExpFlag{
Name: "enable-base64",
Desc: "append content enable base64 encoding",
NoArgs: true,
},
&spec.ExpFlag{
Name: "cgroup-root",
Desc: "cgroup root path, default value /sys/fs/cgroup",
NoArgs: false,
Required: false,
Default: "/sys/fs/cgroup",
},
},
ActionExecutor: &FileAppendActionExecutor{},
ActionExample: `
# Appends the content "HELLO WORLD" to the /home/logs/nginx.log file
blade create file append --filepath=/home/logs/nginx.log --content="HELL WORLD"
# Appends the content "HELLO WORLD" to the /home/logs/nginx.log file, interval 10 seconds
blade create file append --filepath=/home/logs/nginx.log --content="HELL WORLD" --interval 10
# Appends the content "HELLO WORLD" to the /home/logs/nginx.log file, enable base64 encoding
blade create file append --filepath=/home/logs/nginx.log --content=SEVMTE8gV09STEQ=
# mock interface timeout exception
blade create file append --filepath=/home/logs/nginx.log --content="@{DATE:+%Y-%m-%d %H:%M:%S} ERROR invoke getUser timeout [@{RANDOM:100-200}]ms abc mock exception"
`,
ActionPrograms: []string{AppendFileBin},
ActionCategories: []string{category.SystemFile},
ActionProcessHang: true,
},
}
}
func (*FileAppendActionSpec) Name() string {
return "append"
}
func (*FileAppendActionSpec) Aliases() []string {
return []string{}
}
func (*FileAppendActionSpec) ShortDesc() string {
return "File content append"
}
func (f *FileAppendActionSpec) LongDesc() string {
return "File content append. "
}
type FileAppendActionExecutor struct {
channel spec.Channel
}
func (*FileAppendActionExecutor) Name() string {
return "append"
}
func (f *FileAppendActionExecutor) Exec(uid string, ctx context.Context, model *spec.ExpModel) *spec.Response {
commands := []string{"echo", "kill"}
if response, ok := f.channel.IsAllCommandsAvailable(ctx, commands); !ok {
return response
}
filepath := model.ActionFlags["filepath"]
if _, ok := spec.IsDestroy(ctx); ok {
return f.stop(filepath, ctx)
}
if !exec.CheckFilepathExists(ctx, f.channel, filepath) {
log.Errorf(ctx, "`%s`: file does not exist", filepath)
return spec.ResponseFailWithFlags(spec.ParameterInvalid, "filepath", filepath, "the file does not exist")
}
// default 1
count := 1
// default 0
interval := 0
content := model.ActionFlags["content"]
countStr := model.ActionFlags["count"]
intervalStr := model.ActionFlags["interval"]
if countStr != "" {
var err error
count, err = strconv.Atoi(countStr)
if err != nil || count < 1 {
log.Errorf(ctx, "`%s` value must be a positive integer", "count")
return spec.ResponseFailWithFlags(spec.ParameterIllegal, "count", count, "it must be a positive integer")
}
}
if intervalStr != "" {
var err error
interval, err = strconv.Atoi(intervalStr)
if err != nil || interval < 1 {
log.Errorf(ctx, "`%s` value must be a positive integer", "interval")
return spec.ResponseFailWithFlags(spec.ParameterIllegal, "interval", interval, "it must be a positive integer")
}
}
escape := model.ActionFlags["escape"] == "true"
enableBase64 := model.ActionFlags["enable-base64"] == "true"
return f.start(filepath, content, count, interval, escape, enableBase64, ctx)
}
func (f *FileAppendActionExecutor) start(filepath string, content string, count int, interval int, escape bool, enableBase64 bool, ctx context.Context) *spec.Response {
// first append
response := appendFile(f.channel, count, ctx, content, filepath, escape, enableBase64)
if !response.Success {
return response
}
// Without interval, it will not be executed regularly.
if interval < 1 {
return nil
}
ticker := time.NewTicker(time.Second * time.Duration(interval))
for range ticker.C {
response := appendFile(f.channel, count, ctx, content, filepath, escape, enableBase64)
if !response.Success {
return response
}
}
return nil
}
func (f *FileAppendActionExecutor) stop(filepath string, ctx context.Context) *spec.Response {
ctx = context.WithValue(ctx, "bin", AppendFileBin)
return exec.Destroy(ctx, f.channel, "file append")
}
func (f *FileAppendActionExecutor) SetChannel(channel spec.Channel) {
f.channel = channel
}
func appendFile(cl spec.Channel, count int, ctx context.Context, content string, filepath string, escape bool, enableBase64 bool) *spec.Response {
var response *spec.Response
if enableBase64 {
decodeBytes, err := base64.StdEncoding.DecodeString(content)
if err != nil {
return spec.ReturnFail(spec.OsCmdExecFailed, fmt.Sprintf("%s base64 decode err", content))
}
content = string(decodeBytes)
}
content = parseDate(content)
for i := 0; i < count; i++ {
response = parseRandom(content)
if !response.Success {
return response
}
content = response.Result.(string)
if escape {
response = cl.Run(ctx, "echo", fmt.Sprintf(`-e '%s' >> %s`, content, filepath))
} else {
response = cl.Run(ctx, "echo", fmt.Sprintf(`'%s' >> %s`, content, filepath))
}
}
return response
}
func parseDate(content string) string {
reg := regexp.MustCompile(`\\?@\{(?s:DATE\:([^(@{})]*[^\\]))\}`)
result := reg.FindAllStringSubmatch(content, -1)
for _, text := range result {
if strings.HasPrefix(text[0], "\\@") {
content = strings.Replace(content, text[0], strings.Replace(text[0], "\\", "", 1), 1)
continue
}
content = strings.Replace(content, text[0], "$(date \""+text[1]+"\")", 1)
}
return content
}
func parseRandom(content string) *spec.Response {
reg := regexp.MustCompile(`\\?@\{(?s:RANDOM\:([0-9]+\-[0-9]+))\}`)
result := reg.FindAllStringSubmatch(content, -1)
for _, text := range result {
if strings.HasPrefix(text[0], "\\@") {
content = strings.Replace(content, text[0], strings.Replace(text[0], "\\", "", 1), 1)
continue
}
split := strings.Split(text[1], "-")
begin, err := strconv.Atoi(split[0])
if err != nil {
return spec.ReturnFail(spec.ParameterIllegal, fmt.Sprintf("%s illegal parameter", begin))
}
end, err := strconv.Atoi(split[1])
if err != nil {
return spec.ReturnFail(spec.ParameterIllegal, fmt.Sprintf("%s illegal parameter", end))
}
if end <= begin {
return spec.ReturnFail(spec.ParameterIllegal, fmt.Sprintf("run append file %s failed, begin must < end"))
}
content = strings.Replace(content, text[0], strconv.Itoa(rand.Intn(end-begin)+begin), 1)
}
return spec.ReturnSuccess(content)
}