Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make proxy disc generic #374

Merged
merged 7 commits into from
Jun 1, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions pkg/app/appdisc/discovery_updater.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"sync"
"time"

"github.com/SkycoinProject/skywire-mainnet/pkg/proxydisc"
"github.com/SkycoinProject/skywire-mainnet/pkg/servicedisc"
)

// Updater updates the associated app discovery
Expand All @@ -31,7 +31,7 @@ func (emptyUpdater) ChangeValue(name string, v []byte) error { return nil }

// proxyUpdater updates proxy-discovery entry of locally running skysocks App.
type proxyUpdater struct {
client *proxydisc.HTTPClient
client *servicedisc.HTTPClient
interval time.Duration

cancel context.CancelFunc
Expand Down Expand Up @@ -77,7 +77,7 @@ func (u *proxyUpdater) ChangeValue(name string, v []byte) error {
if err != nil {
return err
}
go u.client.UpdateStats(proxydisc.Stats{ConnectedClients: n})
go u.client.UpdateStats(servicedisc.Stats{ConnectedClients: n})
}
return nil
}
34 changes: 20 additions & 14 deletions pkg/app/appdisc/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"github.com/sirupsen/logrus"

"github.com/SkycoinProject/skywire-mainnet/pkg/app/appcommon"
"github.com/SkycoinProject/skywire-mainnet/pkg/proxydisc"
"github.com/SkycoinProject/skywire-mainnet/pkg/servicedisc"
"github.com/SkycoinProject/skywire-mainnet/pkg/skyenv"
)

Expand All @@ -36,32 +36,38 @@ func (f *Factory) setDefaults() {

// Updater obtains an updater based on the app name and configuration.
func (f *Factory) Updater(conf appcommon.ProcConfig) (Updater, bool) {

// Always return empty updater if keys are not set.
if f.setDefaults(); f.PK.Null() || f.SK.Null() {
return &emptyUpdater{}, false
}

log := f.Log.WithField("appName", conf.AppName)

switch conf.AppName {
case "skysocks":
// Do not update in proxy discovery if passcode-protected.
if containsFlag(conf.ProcArgs, "passcode") {
return &emptyUpdater{}, false
}

// Do not update in proxy discovery if passcode-protected.
if containsFlag(conf.ProcArgs, "passcode") {
return &emptyUpdater{}, false
getServiceDiscConf := func(conf appcommon.ProcConfig, sType string) servicedisc.Config {
return servicedisc.Config{
Type: sType,
PK: f.PK,
SK: f.SK,
Port: uint16(conf.RoutingPort),
DiscAddr: f.ProxyDisc,
}
}

switch conf.AppName {
case skyenv.SkysocksName:
return &proxyUpdater{
client: proxydisc.NewClient(log, proxydisc.Config{
PK: f.PK,
SK: f.SK,
Port: uint16(conf.RoutingPort),
DiscAddr: f.ProxyDisc,
}),
client: servicedisc.NewClient(log, getServiceDiscConf(conf, servicedisc.ServiceTypeProxy)),
interval: f.UpdateInterval,
}, true

case skyenv.VPNServerName:
return &proxyUpdater{
client: servicedisc.NewClient(log, getServiceDiscConf(conf, servicedisc.ServiceTypeVPN)),
}, true
default:
return &emptyUpdater{}, false
}
Expand Down
42 changes: 25 additions & 17 deletions pkg/proxydisc/client.go → pkg/servicedisc/client.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package proxydisc
package servicedisc

import (
"bytes"
Expand All @@ -16,17 +16,18 @@ import (

// Config configures the HTTPClient.
type Config struct {
Type string
PK cipher.PubKey
SK cipher.SecKey
Port uint16
DiscAddr string
}

// HTTPClient is responsible for interacting with the proxy-discovery
// HTTPClient is responsible for interacting with the service-discovery
type HTTPClient struct {
log logrus.FieldLogger
conf Config
entry Proxy
entry Service
entryMx sync.Mutex // only used if UpdateLoop && UpdateStats functions are used.
auth *httpauth.Client
client http.Client
Expand All @@ -37,16 +38,23 @@ func NewClient(log logrus.FieldLogger, conf Config) *HTTPClient {
return &HTTPClient{
log: log,
conf: conf,
entry: Proxy{
entry: Service{
Addr: NewSWAddr(conf.PK, conf.Port),
Stats: &Stats{ConnectedClients: 0},
Type: conf.Type,
},
client: http.Client{},
}
}

func (c *HTTPClient) addr(path string) string {
return c.conf.DiscAddr + path
func (c *HTTPClient) addr(path string, sType string) string {
addr := c.conf.DiscAddr + path

if sType != "" {
addr += "?type=" + sType
}

return addr
}

// Auth returns the internal httpauth.Client
Expand All @@ -62,9 +70,9 @@ func (c *HTTPClient) Auth(ctx context.Context) (*httpauth.Client, error) {
return auth, nil
}

// Proxies calls 'GET /api/proxies'.
func (c *HTTPClient) Proxies(ctx context.Context) (out []Proxy, err error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.addr("/api/proxies"), nil)
// Services calls 'GET /api/services'.
func (c *HTTPClient) Services(ctx context.Context) (out []Service, err error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.addr("/api/services", c.entry.Type), nil)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -92,8 +100,8 @@ func (c *HTTPClient) Proxies(ctx context.Context) (out []Proxy, err error) {
return
}

// UpdateEntry calls 'POST /api/proxies'.
func (c *HTTPClient) UpdateEntry(ctx context.Context) (*Proxy, error) {
// UpdateEntry calls 'POST /api/services'.
func (c *HTTPClient) UpdateEntry(ctx context.Context) (*Service, error) {
auth, err := c.Auth(ctx)
if err != nil {
return nil, err
Expand All @@ -105,7 +113,7 @@ func (c *HTTPClient) UpdateEntry(ctx context.Context) (*Proxy, error) {
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.addr("/api/proxies"), bytes.NewReader(raw))
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.addr("/api/services", ""), bytes.NewReader(raw))
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -134,14 +142,14 @@ func (c *HTTPClient) UpdateEntry(ctx context.Context) (*Proxy, error) {
return &c.entry, err
}

// DeleteEntry calls 'DELETE /api/proxies/{entry_addr}'.
// DeleteEntry calls 'DELETE /api/services/{entry_addr}'.
func (c *HTTPClient) DeleteEntry(ctx context.Context) (err error) {
auth, err := c.Auth(ctx)
if err != nil {
return err
}

req, err := http.NewRequestWithContext(ctx, http.MethodDelete, c.addr("/api/proxies/"+c.entry.Addr.String()), nil)
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, c.addr("/api/services/"+c.entry.Addr.String(), c.entry.Type), nil)
if err != nil {
return err
}
Expand All @@ -168,7 +176,7 @@ func (c *HTTPClient) DeleteEntry(ctx context.Context) (err error) {
return nil
}

// UpdateLoop repetitively calls 'POST /api/proxies' to update entry.
// UpdateLoop repetitively calls 'POST /api/services' to update entry.
func (c *HTTPClient) UpdateLoop(ctx context.Context, updateInterval time.Duration) {
defer func() { _ = c.DeleteEntry(context.Background()) }() //nolint:errcheck

Expand All @@ -179,7 +187,7 @@ func (c *HTTPClient) UpdateLoop(ctx context.Context, updateInterval time.Duratio
c.entryMx.Unlock()

if err != nil {
c.log.WithError(err).Warn("Failed to update proxy entry in discovery. Retrying...")
c.log.WithError(err).Warn("Failed to update service entry in discovery. Retrying...")
time.Sleep(time.Second * 10) // TODO(evanlinjin): Exponential backoff.
continue
}
Expand Down Expand Up @@ -212,7 +220,7 @@ func (c *HTTPClient) UpdateLoop(ctx context.Context, updateInterval time.Duratio
}
}

// UpdateStats updates the stats field of the internal proxy entry state.
// UpdateStats updates the stats field of the internal service entry state.
func (c *HTTPClient) UpdateStats(stats Stats) {
c.entryMx.Lock()
c.entry.Stats = &stats
Expand Down
2 changes: 1 addition & 1 deletion pkg/proxydisc/error.go → pkg/servicedisc/error.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package proxydisc
package servicedisc

import (
"fmt"
Expand Down
10 changes: 5 additions & 5 deletions pkg/proxydisc/query.go → pkg/servicedisc/query.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package proxydisc
package servicedisc

import (
"fmt"
Expand Down Expand Up @@ -71,14 +71,14 @@ func (q *GeoQuery) Fill(v url.Values) error {
return nil
}

// ProxiesQuery represents query values for a proxies call.
type ProxiesQuery struct {
// ServicesQuery represents query values for a proxies call.
type ServicesQuery struct {
Count int64 // <=0 : no limit
Cursor uint64 // <=0 : 0 offset
}

// Fill fills ProxiesQuery with query values.
func (q *ProxiesQuery) Fill(v url.Values) error {
// Fill fills ServicesQuery with query values.
func (q *ServicesQuery) Fill(v url.Values) error {
if countS := v.Get("count"); countS != "" {
count, err := strconv.ParseInt(countS, 10, 64)
if err != nil {
Expand Down
24 changes: 16 additions & 8 deletions pkg/proxydisc/types.go → pkg/servicedisc/types.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package proxydisc
package servicedisc

import (
"bytes"
Expand All @@ -10,7 +10,14 @@ import (
"github.com/SkycoinProject/dmsg/cipher"
)

// Errors associated with proxy discovery types.
const (
// ServiceTypeProxy stands for the proxy discovery.
ServiceTypeProxy = "proxy"
// ServiceTypeVPN stands for the VPN discovery.
ServiceTypeVPN = "vpn"
)

// Errors associated with service discovery types.
var (
ErrInvalidSWAddr = errors.New("invalid skywire address")
)
Expand Down Expand Up @@ -88,30 +95,31 @@ type GeoLocation struct {
Region string `json:"region,omitempty"`
}

// Stats provides various statistics on the proxy-discovery service.
// Stats provides various statistics on the service-discovery service.
type Stats struct {
ConnectedClients int `json:"connected_clients"`
}

// Proxy represents a proxy entry in proxy-discovery.
type Proxy struct {
// Service represents a service entry in service-discovery.
type Service struct {
Addr SWAddr `json:"address"`
Type string `json:"type"`
Stats *Stats `json:"stats,omitempty"` // TODO: Have this implemented.
Geo *GeoLocation `json:"geo,omitempty"`
}

// MarshalBinary implements encoding.BinaryMarshaller
func (p *Proxy) MarshalBinary() ([]byte, error) {
func (p *Service) MarshalBinary() ([]byte, error) {
return json.Marshal(p)
}

// UnmarshalBinary implements encoding.BinaryUnmarshaler
func (p *Proxy) UnmarshalBinary(data []byte) error {
func (p *Service) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, p)
}

// Check ensures fields are valid.
func (p Proxy) Check() error {
func (p Service) Check() error {
if p.Addr.PubKey().Null() {
return errors.New("public key cannot be null in address")
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/proxydisc/types_test.go → pkg/servicedisc/types_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package proxydisc
package servicedisc

import (
"fmt"
Expand All @@ -15,7 +15,7 @@ func TestProxy_MarshalBinary(t *testing.T) {
addr := NewSWAddr(pk, 23)
fmt.Println("ADDR:", addr.String())

ps := Proxy{
ps := Service{
Addr: addr,
}

Expand Down