-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
plugin.go
90 lines (84 loc) · 2.01 KB
/
plugin.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
package plugin
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
log "github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/util/retry"
"github.com/argoproj/argo-workflows/v3/util/errors"
)
type Client struct {
Address string
client http.Client
invalid map[string]bool
backoff wait.Backoff
}
func New(address string, timeout time.Duration, backoff wait.Backoff) Client {
return Client{
Address: address,
client: http.Client{
Timeout: timeout,
},
invalid: map[string]bool{},
backoff: backoff,
}
}
func (p *Client) Call(ctx context.Context, method string, args interface{}, reply interface{}) error {
if p.invalid[method] {
return nil
}
log := log.WithField("address", p.Address).WithField("method", method)
body, err := json.Marshal(args)
if err != nil {
return err
}
return retry.OnError(p.backoff, func(err error) bool {
log.WithError(err).Debug("Plugin returned error")
switch e := err.(type) {
case interface{ Temporary() bool }:
if e.Temporary() {
return true
}
}
return strings.Contains(err.Error(), "connection refused")
}, func() error {
log.Debug("Calling plugin")
req, err := http.NewRequestWithContext(ctx, "POST", fmt.Sprintf("%s/api/v1/%s", p.Address, method), bytes.NewBuffer(body))
if err != nil {
return err
}
resp, err := p.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
log.WithField("statusCode", resp.StatusCode).Debug("Called plugin")
switch resp.StatusCode {
case 200:
return json.NewDecoder(resp.Body).Decode(reply)
case 404:
log.Info("method not found, not calling again")
p.invalid[method] = true
_, err := io.Copy(io.Discard, resp.Body)
return err
case 503:
data, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
return errors.NewErrTransient(string(data))
default:
data, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
return fmt.Errorf("%s: %s", resp.Status, string(data))
}
})
}