| 1 |
package ami |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"context" |
| 6 |
"fmt" |
| 7 |
"net" |
| 8 |
"regexp" |
| 9 |
"sync/atomic" |
| 10 |
"time" |
| 11 |
|
| 12 |
"github.com/hashicorp/go-multierror" |
| 13 |
"github.com/pkg/errors" |
| 14 |
"github.com/wenerme/astgo/ami/amimodels" |
| 15 |
"go.uber.org/zap" |
| 16 |
"golang.org/x/sync/errgroup" |
| 17 |
) |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
type CustomDialer interface { |
| 22 |
Dial(network, address string) (net.Conn, error) |
| 23 |
} |
| 24 |
|
| 25 |
type ConnErrHandler func(*Conn, error) |
| 26 |
type ConnHandler func(*Conn) |
| 27 |
|
| 28 |
type ConnectOptions struct { |
| 29 |
Context context.Context |
| 30 |
Timeout time.Duration |
| 31 |
AllowReconnect bool |
| 32 |
Username string |
| 33 |
Secret string |
| 34 |
Logger *zap.Logger |
| 35 |
Dialer CustomDialer |
| 36 |
OnConnectErr ConnErrHandler |
| 37 |
OnConnected ConnHandler |
| 38 |
subscribers []struct { |
| 39 |
sub SubscribeFunc |
| 40 |
opts []SubscribeOption |
| 41 |
} |
| 42 |
} |
| 43 |
type ConnectOption func(c *ConnectOptions) error |
| 44 |
|
| 45 |
func WithAuth(username string, secret string) ConnectOption { |
| 46 |
return func(c *ConnectOptions) error { |
| 47 |
c.Username = username |
| 48 |
c.Secret = secret |
| 49 |
return nil |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
func WithSubscribe(cb SubscribeFunc, opts ...SubscribeOption) ConnectOption { |
| 54 |
return func(c *ConnectOptions) error { |
| 55 |
c.subscribers = append(c.subscribers, struct { |
| 56 |
sub SubscribeFunc |
| 57 |
opts []SubscribeOption |
| 58 |
}{sub: cb, opts: opts}) |
| 59 |
return nil |
| 60 |
} |
| 61 |
} |
| 62 |
func Connect(addr string, opts ...ConnectOption) (conn *Conn, err error) { |
| 63 |
opt := &ConnectOptions{ |
| 64 |
Timeout: 10 * time.Second, |
| 65 |
Context: context.Background(), |
| 66 |
Logger: zap.L(), |
| 67 |
} |
| 68 |
|
| 69 |
for _, v := range opts { |
| 70 |
if err = v(opt); err != nil { |
| 71 |
return nil, err |
| 72 |
} |
| 73 |
} |
| 74 |
if opt.Dialer == nil { |
| 75 |
opt.Dialer = &net.Dialer{ |
| 76 |
Timeout: opt.Timeout, |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
var id uint64 |
| 81 |
conn = &Conn{ |
| 82 |
ctx: opt.Context, |
| 83 |
conf: opt, |
| 84 |
logger: opt.Logger, |
| 85 |
recv: make(chan *Message, 4096), |
| 86 |
pending: make(chan *asyncMsg, 100), |
| 87 |
nextID: func() string { |
| 88 |
return fmt.Sprint(atomic.AddUint64(&id, 1)) |
| 89 |
}, |
| 90 |
} |
| 91 |
for _, sub := range opt.subscribers { |
| 92 |
_, err = conn.Subscribe(sub.sub, sub.opts...) |
| 93 |
if err != nil { |
| 94 |
return nil, err |
| 95 |
} |
| 96 |
} |
| 97 |
return conn, conn.dial(addr) |
| 98 |
} |
| 99 |
|
| 100 |
func (c *Conn) Close() error { |
| 101 |
if c.closer != nil { |
| 102 |
c.closed = true |
| 103 |
c.closer() |
| 104 |
c.closer = nil |
| 105 |
err := c.g.Wait() |
| 106 |
if errors.Is(err, errClose) { |
| 107 |
return nil |
| 108 |
} |
| 109 |
return err |
| 110 |
} |
| 111 |
if c.closed { |
| 112 |
return nil |
| 113 |
} |
| 114 |
return errors.New("not init") |
| 115 |
} |
| 116 |
|
| 117 |
func (c *Conn) dial(addr string) (err error) { |
| 118 |
conf := c.conf |
| 119 |
|
| 120 |
if conf.AllowReconnect { |
| 121 |
|
| 122 |
go func() { |
| 123 |
log := c.logger |
| 124 |
onErr := conf.OnConnectErr |
| 125 |
if onErr == nil { |
| 126 |
onErr = func(conn *Conn, err error) { |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
var err error |
| 131 |
for !c.closed { |
| 132 |
err = c.dialOnce(addr) |
| 133 |
if err != nil { |
| 134 |
log.Sugar().With("err", err).Warn("ami.Conn: dial") |
| 135 |
|
| 136 |
onErr(c, err) |
| 137 |
|
| 138 |
<-time.NewTimer(time.Second).C |
| 139 |
continue |
| 140 |
} |
| 141 |
if conf.OnConnected != nil { |
| 142 |
conf.OnConnected(c) |
| 143 |
log.Sugar().Info("ami.Conn: connected") |
| 144 |
} |
| 145 |
err = c.g.Wait() |
| 146 |
if err != nil { |
| 147 |
log.Sugar().With("err", err).Warn("ami.Conn: error") |
| 148 |
onErr(c, err) |
| 149 |
} |
| 150 |
c.g = nil |
| 151 |
} |
| 152 |
log.Sugar().Info("ami.Conn: stop reconnect, conn closed") |
| 153 |
}() |
| 154 |
return nil |
| 155 |
} |
| 156 |
return c.dialOnce(addr) |
| 157 |
} |
| 158 |
|
| 159 |
func (c *Conn) dialOnce(addr string) (err error) { |
| 160 |
conf := c.conf |
| 161 |
conn, err := conf.Dialer.Dial("tcp", addr) |
| 162 |
if err != nil { |
| 163 |
return err |
| 164 |
} |
| 165 |
defer func() { |
| 166 |
if err != nil { |
| 167 |
if e := conn.Close(); e != nil { |
| 168 |
err = multierror.Append(err, e) |
| 169 |
} |
| 170 |
} |
| 171 |
}() |
| 172 |
return c.connect(conn) |
| 173 |
} |
| 174 |
|
| 175 |
var errClose = errors.New("Close") |
| 176 |
|
| 177 |
func (c *Conn) connect(conn net.Conn) (err error) { |
| 178 |
log := c.logger |
| 179 |
r := bufio.NewReader(conn) |
| 180 |
c.reader = r |
| 181 |
c.conn = conn |
| 182 |
|
| 183 |
line, err := r.ReadString('\n') |
| 184 |
if err != nil { |
| 185 |
return errors.Wrap(err, "scan ami initial line") |
| 186 |
} |
| 187 |
|
| 188 |
|
| 189 |
match := regexp.MustCompile("Asterisk Call Manager/([0-9.]+)").FindStringSubmatch(line) |
| 190 |
if len(match) > 1 { |
| 191 |
c.version = match[1] |
| 192 |
log.Sugar().With("version", c.version).Debug("AMI Version") |
| 193 |
} else { |
| 194 |
err = errors.Errorf("Invalid server header: %q", line) |
| 195 |
return |
| 196 |
} |
| 197 |
|
| 198 |
ctx := c.ctx |
| 199 |
if ctx == nil { |
| 200 |
ctx = context.Background() |
| 201 |
} |
| 202 |
c.g, ctx = errgroup.WithContext(ctx) |
| 203 |
c.g.Go(func() error { |
| 204 |
return c.read(ctx) |
| 205 |
}) |
| 206 |
c.g.Go(func() error { |
| 207 |
return c.loop(ctx) |
| 208 |
}) |
| 209 |
|
| 210 |
waitCtx, closer := context.WithCancel(ctx) |
| 211 |
c.g.Go(func() error { |
| 212 |
<-ctx.Done() |
| 213 |
closer() |
| 214 |
return conn.Close() |
| 215 |
}) |
| 216 |
c.g.Go(func() error { |
| 217 |
<-waitCtx.Done() |
| 218 |
return errClose |
| 219 |
}) |
| 220 |
c.closer = closer |
| 221 |
|
| 222 |
conf := c.conf |
| 223 |
if conf.Username != "" { |
| 224 |
var resp *Message |
| 225 |
resp, err = c.Request(amimodels.LoginAction{ |
| 226 |
UserName: conf.Username, |
| 227 |
Secret: conf.Secret, |
| 228 |
}, RequestTimeout(2*time.Second)) |
| 229 |
|
| 230 |
if err != nil { |
| 231 |
err = errors.Wrap(err, "request login") |
| 232 |
} else if !resp.Success() { |
| 233 |
err = errors.Wrap(resp.Error(), "login") |
| 234 |
} |
| 235 |
if err != nil { |
| 236 |
log.Sugar().With("err", err).Info("login failed") |
| 237 |
return err |
| 238 |
} |
| 239 |
log.Info("login success") |
| 240 |
} |
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
return |
| 247 |
} |