Skip to content

Commit

Permalink
Merge pull request #6 from Comcast/standUpMachine
Browse files Browse the repository at this point in the history
Fixed mux issues and webhook logic
  • Loading branch information
schmidtw authored Sep 29, 2017
2 parents 149b5ba + 404adb9 commit a822c25
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 80 deletions.
2 changes: 1 addition & 1 deletion src/tr1d1um/communication.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func (tr1 *Tr1SendAndHandle) Send(ch *ConversionHandler, resp http.ResponseWrite
return
}

fullPath := ch.targetURL + baseURI + "/" + version + "/" + wrpMsg.Destination
fullPath := ch.targetURL + baseURI + "/" + ch.serverVersion + "/" + wrpMsg.Destination
requestToServer, err := tr1.NewHTTPRequest(http.MethodPost, fullPath, bytes.NewBuffer(wrpPayload))

if err != nil {
Expand Down
16 changes: 9 additions & 7 deletions src/tr1d1um/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,21 @@ import (

//ConversionHandler wraps the main WDMP -> WRP conversion method
type ConversionHandler struct {
infoLogger log.Logger
errorLogger log.Logger
logger log.Logger
targetURL string
serverVersion string
wdmpConvert ConversionTool
sender SendAndHandle
encodingHelper EncodingTool
}

//ConversionHandler handles the different incoming tr1 requests
func (ch *ConversionHandler) ServeHTTP(origin http.ResponseWriter, req *http.Request) {
var err error
var wdmp interface{}
var urlVars = mux.Vars(req)
var (
err error
wdmp interface{}
urlVars = mux.Vars(req)
)

switch req.Method {
case http.MethodGet:
Expand All @@ -49,15 +51,15 @@ func (ch *ConversionHandler) ServeHTTP(origin http.ResponseWriter, req *http.Req

if err != nil {
origin.WriteHeader(http.StatusInternalServerError)
ch.errorLogger.Log(logging.MessageKey(), ErrUnsuccessfulDataParse, logging.ErrorKey(), err.Error())
logging.Error(ch.logger).Log(logging.MessageKey(), ErrUnsuccessfulDataParse, logging.ErrorKey(), err.Error())
return
}

wdmpPayload, err := ch.encodingHelper.EncodeJSON(wdmp)

if err != nil {
origin.WriteHeader(http.StatusInternalServerError)
ch.errorLogger.Log(logging.ErrorKey(), err.Error())
logging.Error(ch.logger).Log(logging.ErrorKey(), err.Error())
return
}

Expand Down
2 changes: 1 addition & 1 deletion src/tr1d1um/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ var (
wdmpConvert: mockConversion,
sender: mockSender,
encodingHelper: mockEncoding,
errorLogger: fakeLogger,
logger: fakeLogger,
}
)

Expand Down
50 changes: 19 additions & 31 deletions src/tr1d1um/tr1d1um.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
Expand Down Expand Up @@ -28,7 +29,6 @@ const (
applicationName = "tr1d1um"
DefaultKeyID = "current"
baseURI = "/api"
version = "v2" // TODO: Should these values change?
)

func tr1d1um(arguments []string) (exitCode int) {
Expand All @@ -50,9 +50,6 @@ func tr1d1um(arguments []string) (exitCode int) {

infoLogger.Log("configurationFile", v.ConfigFileUsed())

tConfig := new(Tr1d1umConfig)
err = v.Unmarshal(tConfig) //todo: decide best way to get current unexported fields from viper

if err != nil {
fmt.Fprintf(os.Stderr, "Unable to unmarshall config data into struct: %s\n", err.Error())
return 1
Expand All @@ -65,18 +62,18 @@ func tr1d1um(arguments []string) (exitCode int) {
return 1
}

conversionHandler := SetUpHandler(tConfig, logger)
conversionHandler := SetUpHandler(v, logger)

r := mux.NewRouter()

AddRoutes(r, preHandler, conversionHandler)
AddRoutes(r, preHandler, conversionHandler, v)

if exitCode = ConfigureWebHooks(r, preHandler, v, logger); exitCode != 0 {
return
}

var (
_, tr1d1umServer = webPA.Prepare(logger, nil, conversionHandler)
_, tr1d1umServer = webPA.Prepare(logger, nil, r)
signals = make(chan os.Signal, 1)
)

Expand Down Expand Up @@ -111,29 +108,25 @@ func ConfigureWebHooks(r *mux.Router, preHandler *alice.Chain, v *viper.Viper, l
webHookFactory.Initialize(r, selfURL, webHookHandler, logger, nil)
webHookFactory.PrepareAndStart()

startChan := make(chan webhook.Result, 1)
webHookFactory.Start.GetCurrentSystemsHooks(startChan)

if webHookStartResults := <-startChan; webHookStartResults.Error == nil {
webHookFactory.SetList(webhook.NewList(webHookStartResults.Hooks))
} else {
logging.Error(logger).Log(logging.ErrorKey(), webHookStartResults.Error)
}

return 0
}

//AddRoutes configures the paths and connection rules to TR1D1UM
func AddRoutes(r *mux.Router, preHandler *alice.Chain, conversionHandler *ConversionHandler) *mux.Router {
func AddRoutes(r *mux.Router, preHandler *alice.Chain, conversionHandler *ConversionHandler, v *viper.Viper) {
var BodyNonEmpty = func(request *http.Request, match *mux.RouteMatch) (accept bool) {
if request.Body != nil {
var tmp bytes.Buffer
p, err := ioutil.ReadAll(request.Body)
accept = err == nil && len(p) > 0
if accept = err == nil && len(p) > 0; accept {
//place back request's body
tmp.Write(p)
request.Body = ioutil.NopCloser(&tmp)
}
}
return
}

apiHandler := r.PathPrefix(fmt.Sprintf("%s/%s", baseURI, version)).Subrouter()
apiHandler := r.PathPrefix(fmt.Sprintf("%s/%s", baseURI, v.GetString("version"))).Subrouter()

apiHandler.Handle("/device/{deviceid}/{service}", preHandler.Then(conversionHandler)).
Methods(http.MethodGet)
Expand All @@ -146,27 +139,23 @@ func AddRoutes(r *mux.Router, preHandler *alice.Chain, conversionHandler *Conver

apiHandler.Handle("/device/{deviceid}/{service}/{parameter}", preHandler.Then(conversionHandler)).
Methods(http.MethodPut, http.MethodPost).MatcherFunc(BodyNonEmpty)

return r
}

//SetUpHandler prepares the main handler under TR1D1UM which is the ConversionHandler
func SetUpHandler(tConfig *Tr1d1umConfig, logger log.Logger) (cHandler *ConversionHandler) {
timeOut, err := time.ParseDuration(tConfig.HTTPTimeout)
func SetUpHandler(v *viper.Viper, logger log.Logger) (cHandler *ConversionHandler) {
timeOut, err := time.ParseDuration(v.GetString("requestTimeout"))
if err != nil {
timeOut = time.Second * 60 //default val
}

cHandler = &ConversionHandler{
wdmpConvert: &ConversionWDMP{&EncodingHelper{}},
sender: &Tr1SendAndHandle{log: logger, timedClient: &http.Client{Timeout: timeOut},
NewHTTPRequest: http.NewRequest},
wdmpConvert: &ConversionWDMP{&EncodingHelper{}},
sender: &Tr1SendAndHandle{log: logger, timedClient: &http.Client{Timeout: timeOut}, NewHTTPRequest: http.NewRequest},
encodingHelper: &EncodingHelper{},
logger: logger,
targetURL: v.GetString("targetURL"),
serverVersion: v.GetString("version"),
}
//pass loggers
cHandler.errorLogger = logging.Error(logger)
cHandler.infoLogger = logging.Info(logger)
cHandler.targetURL = tConfig.TargetURL
return
}

Expand Down Expand Up @@ -224,7 +213,6 @@ func GetValidator(v *viper.Viper) (validator secure.Validator, err error) {
)
}

// TODO: This should really be part of the unmarshalled validators somehow
basicAuth := v.GetStringSlice("authHeader")
for _, authValue := range basicAuth {
validators = append(
Expand Down
26 changes: 15 additions & 11 deletions src/tr1d1um/tr1d1um_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,36 +11,41 @@ import (
"github.com/Comcast/webpa-common/logging"
"github.com/gorilla/mux"
"github.com/justinas/alice"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
)

func TestSetUpHandler(t *testing.T) {
assert := assert.New(t)
tConfig := &Tr1d1umConfig{HTTPTimeout: "10s", TargetURL: "https://someCoolURL.com"}
v := viper.New()
v.Set("requestTimeout", "60s")
v.Set("targetURL", "https://someCoolURL.com")
logger := logging.DefaultLogger()

t.Run("NormalSetUp", func(t *testing.T) {
actualHandler := SetUpHandler(tConfig, logger)
AssertCommon(actualHandler, tConfig, assert)
actualHandler := SetUpHandler(v, logger)
AssertCommon(actualHandler, v, assert)
})

t.Run("IncompleteConfig", func(t *testing.T) {
tConfig.HTTPTimeout = "" //make config struct incomplete
v.Set("requestTimeOut", "") //make config incomplete

actualHandler := SetUpHandler(tConfig, logger)
actualHandler := SetUpHandler(v, logger)

realSender := actualHandler.sender.(*Tr1SendAndHandle)
assert.EqualValues(time.Second*60, realSender.timedClient.Timeout) //turn to default value
AssertCommon(actualHandler, tConfig, assert)
AssertCommon(actualHandler, v, assert)
})
}

func TestRouteConfigurations(t *testing.T) {
r := mux.NewRouter()
fakePreHandler := new(alice.Chain)
fakeHandler := &ConversionHandler{}
v := viper.New()
v.Set("version", "v2")

r = AddRoutes(r, fakePreHandler, fakeHandler)
AddRoutes(r, fakePreHandler, fakeHandler, v)

var nonEmpty bytes.Buffer
nonEmpty.WriteString(`{empty: false}`)
Expand Down Expand Up @@ -94,12 +99,11 @@ func AssertConfiguredRoutes(r *mux.Router, t *testing.T, testCases []RouteTestBu
}
}

func AssertCommon(actualHandler *ConversionHandler, tConfig *Tr1d1umConfig, assert *assert.Assertions) {
func AssertCommon(actualHandler *ConversionHandler, v *viper.Viper, assert *assert.Assertions) {
assert.NotNil(actualHandler.wdmpConvert)
assert.NotNil(actualHandler.encodingHelper)
assert.NotNil(actualHandler.errorLogger)
assert.NotNil(actualHandler.infoLogger)
assert.EqualValues(tConfig.TargetURL, actualHandler.targetURL)
assert.NotNil(actualHandler.logger)
assert.EqualValues(v.Get("targetURL"), actualHandler.targetURL)
assert.NotNil(actualHandler.sender)

realizedSender := actualHandler.sender.(*Tr1SendAndHandle)
Expand Down
31 changes: 2 additions & 29 deletions src/tr1d1um/tr1d1um_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,39 +5,12 @@ import (
"github.com/Comcast/webpa-common/secure/key"
)

//Tr1d1umConfig wraps all the config
type Tr1d1umConfig struct {
Addr string `json:"addr"`
PprofAddr string `json:"pprofaddr"`
Cert string `json:"cert"`
Key string `json:"key"`
AuthKey []string `json:"authKey"`
HandlerTimeout string `json:"handlerTimeout"`
HTTPTimeout string `json:"httpTimeout"`
HealthInterval string `json:"healthInterval"`
Version string `json:"version"`
MaxTCPConns int64 `json:"maxApiTcpConnections"`
MaxHealthTCPConns int64 `json:"maxHealthTcpConnections"`
ServiceList []string `json:"serviceList"`
WrpSource string `json:"wrpSource"`
TargetURL string `json:"targetURL"`

JWTValidators []struct {
// JWTKeys is used to create the key.Resolver for JWT verification keys
Keys key.ResolverFactory `json:"keys"`

// Custom is an optional configuration section that defines
// custom rules for validation over and above the standard RFC rules.
Custom secure.JWTValidatorFactory `json:"custom"`
} `json:"jwtValidators"`
}

//JWTValidator provides a convenient way to define jwt validator through config files
type JWTValidator struct {
// JWTKeys is used to create the key.Resolver for JWT verification keys
Keys key.ResolverFactory
Keys key.ResolverFactory `json:"keys"`

// Custom is an optional configuration section that defines
// custom rules for validation over and above the standard RFC rules.
Custom secure.JWTValidatorFactory
Custom secure.JWTValidatorFactory `json:"custom"`
}

0 comments on commit a822c25

Please sign in to comment.