| 144 | } |
| 145 | |
| 146 | func (p *Plugin) run(rule cpmtypes.CustomRule) (exitStatus cpmtypes.Status, output string) { |
| 147 | var ctx context.Context |
| 148 | var cancel context.CancelFunc |
| 149 | |
| 150 | if rule.Timeout != nil && *rule.Timeout < *p.config.PluginGlobalConfig.Timeout { |
| 151 | ctx, cancel = context.WithTimeout(context.Background(), *rule.Timeout) |
| 152 | } else { |
| 153 | ctx, cancel = context.WithTimeout(context.Background(), *p.config.PluginGlobalConfig.Timeout) |
| 154 | } |
| 155 | defer cancel() |
| 156 | |
| 157 | cmd := util.Exec(ctx, rule.Path, rule.Args...) |
| 158 | |
| 159 | stdoutPipe, err := cmd.StdoutPipe() |
| 160 | if err != nil { |
| 161 | klog.Errorf("Error creating stdout pipe for plugin %q: error - %v", rule.Path, err) |
| 162 | return cpmtypes.Unknown, "Error creating stdout pipe for plugin. Please check the error log" |
| 163 | } |
| 164 | stderrPipe, err := cmd.StderrPipe() |
| 165 | if err != nil { |
| 166 | klog.Errorf("Error creating stderr pipe for plugin %q: error - %v", rule.Path, err) |
| 167 | return cpmtypes.Unknown, "Error creating stderr pipe for plugin. Please check the error log" |
| 168 | } |
| 169 | if err := cmd.Start(); err != nil { |
| 170 | klog.Errorf("Error in starting plugin %q: error - %v", rule.Path, err) |
| 171 | return cpmtypes.Unknown, "Error in starting plugin. Please check the error log" |
| 172 | } |
| 173 | |
| 174 | waitChan := make(chan struct{}) |
| 175 | defer close(waitChan) |
| 176 | |
| 177 | var m sync.Mutex |
| 178 | timeout := false |
| 179 | |
| 180 | go func() { |
| 181 | select { |
| 182 | case <-ctx.Done(): |
| 183 | if ctx.Err() == context.Canceled { |
| 184 | return |
| 185 | } |
| 186 | klog.Errorf("Error in running plugin timeout %q", rule.Path) |
| 187 | if cmd.Process == nil || cmd.Process.Pid == 0 { |
| 188 | klog.Errorf("Error in cmd.Process check %q", rule.Path) |
| 189 | break |
| 190 | } |
| 191 | |
| 192 | m.Lock() |
| 193 | timeout = true |
| 194 | m.Unlock() |
| 195 | |
| 196 | err := util.Kill(cmd) |
| 197 | if err != nil { |
| 198 | klog.Errorf("Error in kill process %d, %v", cmd.Process.Pid, err) |
| 199 | } |
| 200 | case <-waitChan: |
| 201 | return |
| 202 | } |
| 203 | }() |