More reasonable shutdowns

This commit is contained in:
9seconds
2019-09-04 10:54:38 +03:00
parent 299a34252e
commit 701f62ed4c
8 changed files with 115 additions and 41 deletions
+6 -5
View File
@@ -2,6 +2,7 @@ package config
import (
"bytes"
"context"
"encoding/json"
"net"
"strconv"
@@ -140,14 +141,14 @@ func (c Config) String() string {
return string(data)
}
type ConfigOpt struct {
type Opt struct {
Option OptionType
Value interface{}
}
var C = Config{}
func Init(options ...ConfigOpt) error { // nolint: gocyclo
func Init(options ...Opt) error { // nolint: gocyclo
for _, opt := range options {
switch opt.Option {
case OptionTypeDebug:
@@ -222,7 +223,7 @@ func Init(options ...ConfigOpt) error { // nolint: gocyclo
return nil
}
func InitPublicAddress() error {
func InitPublicAddress(ctx context.Context) error {
if C.PublicIPv4Addr.Port == 0 {
C.PublicIPv4Addr.Port = C.ListenAddr.Port
}
@@ -232,7 +233,7 @@ func InitPublicAddress() error {
foundAddress := C.PublicIPv4Addr.IP != nil || C.PublicIPv6Addr.IP != nil
if C.PublicIPv4Addr.IP == nil {
ip, err := getGlobalIPv4()
ip, err := getGlobalIPv4(ctx)
if err != nil {
zap.S().Warnw("Cannot resolve public address", "error", err)
} else {
@@ -241,7 +242,7 @@ func InitPublicAddress() error {
}
}
if C.PublicIPv6Addr.IP == nil {
ip, err := getGlobalIPv6()
ip, err := getGlobalIPv6(ctx)
if err != nil {
zap.S().Warnw("Cannot resolve public address", "error", err)
} else {
+11 -6
View File
@@ -17,23 +17,23 @@ const (
ifconfigTimeout = 10 * time.Second
)
func getGlobalIPv4() (net.IP, error) {
ip, err := fetchIP("tcp4")
func getGlobalIPv4(ctx context.Context) (net.IP, error) {
ip, err := fetchIP(ctx, "tcp4")
if err != nil || ip.To4() == nil {
return nil, errors.Annotate(err, "Cannot find public ipv4 address")
}
return ip, nil
}
func getGlobalIPv6() (net.IP, error) {
ip, err := fetchIP("tcp6")
func getGlobalIPv6(ctx context.Context) (net.IP, error) {
ip, err := fetchIP(ctx, "tcp6")
if err != nil || ip.To4() != nil {
return nil, errors.Annotate(err, "Cannot find public ipv6 address")
}
return ip, nil
}
func fetchIP(network string) (net.IP, error) {
func fetchIP(ctx context.Context, network string) (net.IP, error) {
dialer := &net.Dialer{FallbackDelay: -1}
client := &http.Client{
Jar: nil,
@@ -45,7 +45,12 @@ func fetchIP(network string) (net.IP, error) {
},
}
resp, err := client.Get(ifconfigAddress)
req, err := http.NewRequest("GET", ifconfigAddress, nil)
if err != nil {
return nil, errors.Annotate(err, "Cannot create a request")
}
resp, err := client.Do(req.WithContext(ctx))
if err != nil {
if resp != nil {
io.Copy(ioutil.Discard, resp.Body) // nolint: errcheck