Skip to content

Commit

Permalink
Some more cleanups, remove commented out code (#489)
Browse files Browse the repository at this point in the history
* Don't check for non-zero length before ranging

Ranging over a nil/empty slice is alright and will do nothing.

* Reduce indentation in a few places

* Simplify a bunch of declarations

Mostly in coprocess code.

* Remove some commented out code

If we ever need it, it's in the history.
  • Loading branch information
mvdan authored and buger committed Feb 9, 2017
1 parent 70f6549 commit fd2b29a
Show file tree
Hide file tree
Showing 23 changed files with 104 additions and 604 deletions.
6 changes: 2 additions & 4 deletions analytics.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,10 +129,8 @@ func (a *AnalyticsRecord) NormalisePath() {
if config.AnalyticsConfig.NormaliseUrls.NormaliseNumbers {
a.Path = config.AnalyticsConfig.NormaliseUrls.compiledPatternSet.IDs.ReplaceAllString(a.Path, "/{id}")
}
if len(config.AnalyticsConfig.NormaliseUrls.compiledPatternSet.Custom) > 0 {
for _, r := range config.AnalyticsConfig.NormaliseUrls.compiledPatternSet.Custom {
a.Path = r.ReplaceAllString(a.Path, "{var}")
}
for _, r := range config.AnalyticsConfig.NormaliseUrls.compiledPatternSet.Custom {
a.Path = r.ReplaceAllString(a.Path, "{var}")
}
}

Expand Down
5 changes: 1 addition & 4 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -1462,9 +1462,7 @@ type NewClientRequest struct {
}

func createOauthClientStorageID(APIID string, clientID string) string {
// storageID := OAUTH_PREFIX + APIID + "." + CLIENT_PREFIX + clientID
storageID := CLIENT_PREFIX + clientID
return storageID
return CLIENT_PREFIX + clientID
}

func createOauthClient(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -1818,7 +1816,6 @@ func getOauthClients(APIID string) ([]byte, int) {
var err error
code := 200

// filterID := OAUTH_PREFIX + APIID + "." + CLIENT_PREFIX
filterID := CLIENT_PREFIX

apiSpec := GetSpecForApi(APIID)
Expand Down
15 changes: 2 additions & 13 deletions api_healthcheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,8 @@ func (h *DefaultHealthChecker) Init(storeType StorageHandler) {
}

func (h *DefaultHealthChecker) CreateKeyName(subKey HealthPrefix) string {
var newKey string
//now := time.Now().UnixNano()

// Key should be API-ID.SubKey.123456789
//newKey = strings.Join([]string{h.APIID, string(subKey), strconv.FormatInt(now, 10)}, ".")
newKey = strings.Join([]string{h.APIID, string(subKey)}, ".")

return newKey
return strings.Join([]string{h.APIID, string(subKey)}, ".")
}

// ReportHealthCheckValue is a shortcut we can use throughout the app to push a health check value
Expand All @@ -78,15 +72,11 @@ func (h *DefaultHealthChecker) StoreCounterVal(counterType HealthPrefix, value s
}

func (h *DefaultHealthChecker) getAvgCount(prefix HealthPrefix) float64 {
//searchStr := strings.Join([]string{h.APIID, string(prefix)}, ".")

searchStr := h.CreateKeyName(prefix)
log.Debug("Searching for: ", searchStr)

var count int
count, _ = h.storage.SetRollingWindow(searchStr, config.HealthCheck.HealthCheckValueTimeout, "-1")
count, _ := h.storage.SetRollingWindow(searchStr, config.HealthCheck.HealthCheckValueTimeout, "-1")
log.Debug("Count is: ", count)
//count = int64(len(keys))
divisor := float64(config.HealthCheck.HealthCheckValueTimeout)
if divisor == 0 {
log.Warning("The Health Check sample timeout is set to 0, samples will never be deleted!!!")
Expand Down Expand Up @@ -117,7 +107,6 @@ func (h *DefaultHealthChecker) GetApiHealthValues() (HealthCheckValues, error) {
// Get the micro latency graph, an average upstream latency
searchStr := strings.Join([]string{h.APIID, string(RequestLog)}, ".")
log.Debug("Searching KV for: ", searchStr)
//kv := h.storage.GetKeysAndValuesWithFilter(searchStr)
_, vals := h.storage.SetRollingWindow(searchStr, config.HealthCheck.HealthCheckValueTimeout, "-1")
log.Debug("Found: ", vals)
var runningTotal int
Expand Down
11 changes: 1 addition & 10 deletions api_loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,14 +152,9 @@ func processSpec(referenceSpec *APISpec,
}

// Initialise the auth and session managers (use Redis for now)
var authStore StorageHandler
var sessionStore StorageHandler
var orgStore StorageHandler
var authStore, sessionStore, orgStore StorageHandler

authStorageEngineToUse := referenceSpec.AuthProvider.StorageEngine
// if config.SlaveOptions.OverrideDefinitionStorageSettings {
// authStorageEngineToUse = RPCStorageEngine
// }

switch authStorageEngineToUse {
case DefaultStorageEngine:
Expand All @@ -182,9 +177,6 @@ func processSpec(referenceSpec *APISpec,
}

SessionStorageEngineToUse := referenceSpec.SessionProvider.StorageEngine
// if config.SlaveOptions.OverrideDefinitionStorageSettings {
// SessionStorageEngineToUse = RPCStorageEngine
// }

switch SessionStorageEngineToUse {
case DefaultStorageEngine:
Expand Down Expand Up @@ -276,7 +268,6 @@ func processSpec(referenceSpec *APISpec,
// Create the response processors
creeateResponseMiddlewareChain(referenceSpec)

//proxyHandler := http.HandlerFunc(ProxyHandler(proxy, referenceSpec))
tykMiddleware := &TykMiddleware{referenceSpec, proxy}
CheckCBEnabled(tykMiddleware)
CheckETEnabled(tykMiddleware)
Expand Down
1 change: 0 additions & 1 deletion auth_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ func (b *DefaultAuthorisationManager) IsKeyAuthorised(keyName string) (SessionSt
// IsKeyExpired checks if a key has expired, if the value of SessionState.Expires is 0, it will be ignored
func (b *DefaultAuthorisationManager) IsKeyExpired(newSession *SessionState) bool {
if newSession.Expires >= 1 {
//diff := newSession.Expires - time.Now().Unix()
return time.Now().After(time.Unix(newSession.Expires, 0))
}
return false
Expand Down
45 changes: 22 additions & 23 deletions blueprint.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,30 +140,29 @@ func (b *BluePrintAST) ConvertIntoApiVersion(asMock bool) (apidef.VersionInfo, e
newMetaData.MethodActions = make(map[string]apidef.EndpointMethodMeta)

for _, action := range resource.Actions {
if len(action.Examples) > 0 {
if len(action.Examples[0].Responses) > 0 {
endPointMethodMeta := apidef.EndpointMethodMeta{}
code, err := strconv.Atoi(action.Examples[0].Responses[0].Name)
if err != nil {
log.Warning("Could not genrate response code form Name field, using 200")
code = 200
}
endPointMethodMeta.Code = code

if asMock {
endPointMethodMeta.Action = apidef.Reply
} else {
endPointMethodMeta.Action = apidef.NoAction
}

for _, h := range action.Examples[0].Responses[0].Headers {
endPointMethodMeta.Headers = make(map[string]string)
endPointMethodMeta.Headers[h.Name] = h.Value
}
endPointMethodMeta.Data = action.Examples[0].Responses[0].Body
newMetaData.MethodActions[action.Method] = endPointMethodMeta
}
if len(action.Examples) == 0 || len(action.Examples[0].Responses) == 0 {
continue
}
endPointMethodMeta := apidef.EndpointMethodMeta{}
code, err := strconv.Atoi(action.Examples[0].Responses[0].Name)
if err != nil {
log.Warning("Could not genrate response code form Name field, using 200")
code = 200
}
endPointMethodMeta.Code = code

if asMock {
endPointMethodMeta.Action = apidef.Reply
} else {
endPointMethodMeta.Action = apidef.NoAction
}

for _, h := range action.Examples[0].Responses[0].Headers {
endPointMethodMeta.Headers = make(map[string]string)
endPointMethodMeta.Headers[h.Name] = h.Value
}
endPointMethodMeta.Data = action.Examples[0].Responses[0].Body
newMetaData.MethodActions[action.Method] = endPointMethodMeta
}

// Add it to the version
Expand Down
9 changes: 2 additions & 7 deletions coprocess.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,7 @@ func (c *CoProcessor) GetObjectFromRequest(r *http.Request) *coprocess.Object {
defer r.Body.Close()
originalBody, _ := ioutil.ReadAll(r.Body)

var object *coprocess.Object
var miniRequestObject *coprocess.MiniRequestObject

miniRequestObject = &coprocess.MiniRequestObject{
miniRequestObject := &coprocess.MiniRequestObject{
Headers: ProtoMap(r.Header),
SetHeaders: make(map[string]string, 0),
DeleteHeaders: make([]string, 0),
Expand All @@ -92,7 +89,7 @@ func (c *CoProcessor) GetObjectFromRequest(r *http.Request) *coprocess.Object {
},
}

object = &coprocess.Object{
object := &coprocess.Object{
Request: miniRequestObject,
HookName: c.Middleware.HookName,
}
Expand All @@ -107,8 +104,6 @@ func (c *CoProcessor) GetObjectFromRequest(r *http.Request) *coprocess.Object {
object.Metadata = make(map[string]string, 0)
object.Spec = make(map[string]string, 0)

// object.Session = SessionState{}

// Append spec data:
if c.Middleware != nil {
object.Spec = map[string]string{
Expand Down
6 changes: 2 additions & 4 deletions coprocess_events.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
package main

import (
"github.com/TykTechnologies/tyk/apidef"
// "fmt"
"encoding/json"

"github.com/TykTechnologies/tyk/apidef"
)

// Constant for event system.
Expand Down Expand Up @@ -41,9 +41,7 @@ func (l CoProcessEventHandler) New(handlerConf interface{}) (TykEventHandler, er
log.Error("Failed to marshal globals! ", err)
}

// handler.SpecJSON = string(gValAsJSON)
handler.SpecJSON = json.RawMessage(gValAsJSON)

return handler, nil
}

Expand Down
22 changes: 7 additions & 15 deletions coprocess_lua.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,18 +109,13 @@ type LuaDispatcher struct {

// Dispatch takes a CoProcessMessage and sends it to the CP.
func (d *LuaDispatcher) Dispatch(objectPtr unsafe.Pointer) unsafe.Pointer {
var object *C.struct_CoProcessMessage
object = (*C.struct_CoProcessMessage)(objectPtr)

var newObjectPtr *C.struct_CoProcessMessage
newObjectPtr = C.LuaDispatchHook(object)

object := (*C.struct_CoProcessMessage)(objectPtr)
newObjectPtr := C.LuaDispatchHook(object)
return unsafe.Pointer(newObjectPtr)
}

// Reload will perform a middleware reload when a hot reload is triggered.
func (d *LuaDispatcher) Reload() {
// modules, _ := ioutil.ReadDir(ModuleBasePath)
files, _ := ioutil.ReadDir(MiddlewareBasePath)

if d.MiddlewareCache == nil {
Expand Down Expand Up @@ -184,9 +179,8 @@ func (d *LuaDispatcher) LoadModules() {
//export LoadCachedModules
func LoadCachedModules(luaState unsafe.Pointer) {
for moduleName, moduleContents := range gModuleCache {
var cModuleName, cModuleContents *C.char
cModuleName = C.CString(moduleName)
cModuleContents = C.CString(moduleContents)
cModuleName := C.CString(moduleName)
cModuleContents := C.CString(moduleContents)
C.LoadMiddlewareIntoState((*C.struct_lua_State)(luaState), cModuleName, cModuleContents)
C.free(unsafe.Pointer(cModuleName))
C.free(unsafe.Pointer(cModuleContents))
Expand All @@ -197,9 +191,8 @@ func LoadCachedModules(luaState unsafe.Pointer) {
//export LoadCachedMiddleware
func LoadCachedMiddleware(luaState unsafe.Pointer) {
for middlewareName, middlewareContents := range gMiddlewareCache {
var cMiddlewareName, cMiddlewareContents *C.char
cMiddlewareName = C.CString(middlewareName)
cMiddlewareContents = C.CString(middlewareContents)
cMiddlewareName := C.CString(middlewareName)
cMiddlewareContents := C.CString(middlewareContents)
C.LoadMiddlewareIntoState((*C.struct_lua_State)(luaState), cMiddlewareName, cMiddlewareContents)
C.free(unsafe.Pointer(cMiddlewareName))
C.free(unsafe.Pointer(cMiddlewareContents))
Expand All @@ -208,8 +201,7 @@ func LoadCachedMiddleware(luaState unsafe.Pointer) {
}

func (d *LuaDispatcher) DispatchEvent(eventJSON []byte) {
var CEventJSON *C.char
CEventJSON = C.CString(string(eventJSON))
CEventJSON := C.CString(string(eventJSON))
C.LuaDispatchEvent(CEventJSON)
C.free(unsafe.Pointer(CEventJSON))
return
Expand Down
20 changes: 7 additions & 13 deletions coprocess_native.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,9 @@ import (
)

// Dispatch prepares a CoProcessMessage, sends it to the GlobalDispatcher and gets a reply.
func (c *CoProcessor) Dispatch(object *coprocess.Object) (newObject *coprocess.Object, err error) {
func (c *CoProcessor) Dispatch(object *coprocess.Object) (*coprocess.Object, error) {

var objectMsg []byte

if MessageType == coprocess.ProtobufMessage {
objectMsg, _ = proto.Marshal(object)
} else if MessageType == coprocess.JsonMessage {
Expand All @@ -41,22 +40,17 @@ func (c *CoProcessor) Dispatch(object *coprocess.Object) (newObject *coprocess.O

objectMsgStr := string(objectMsg)

var CObjectStr *C.char
CObjectStr = C.CString(objectMsgStr)

var objectPtr *C.struct_CoProcessMessage
CObjectStr := C.CString(objectMsgStr)

objectPtr = (*C.struct_CoProcessMessage)(C.malloc(C.size_t(unsafe.Sizeof(C.struct_CoProcessMessage{}))))
objectPtr := (*C.struct_CoProcessMessage)(C.malloc(C.size_t(unsafe.Sizeof(C.struct_CoProcessMessage{}))))
objectPtr.p_data = unsafe.Pointer(CObjectStr)
objectPtr.length = C.int(len(objectMsg))

var newObjectPtr *C.struct_CoProcessMessage
newObjectPtr = (*C.struct_CoProcessMessage)(GlobalDispatcher.Dispatch(unsafe.Pointer(objectPtr)))
newObjectPtr := (*C.struct_CoProcessMessage)(GlobalDispatcher.Dispatch(unsafe.Pointer(objectPtr)))

var newObjectBytes []byte
newObjectBytes = C.GoBytes(newObjectPtr.p_data, newObjectPtr.length)
newObjectBytes := C.GoBytes(newObjectPtr.p_data, newObjectPtr.length)

newObject = &coprocess.Object{}
newObject := &coprocess.Object{}

if MessageType == coprocess.ProtobufMessage {
proto.Unmarshal(newObjectBytes, newObject)
Expand All @@ -68,5 +62,5 @@ func (c *CoProcessor) Dispatch(object *coprocess.Object) (newObject *coprocess.O
C.free(unsafe.Pointer(objectPtr))
C.free(unsafe.Pointer(newObjectPtr))

return newObject, err
return newObject, nil
}
30 changes: 8 additions & 22 deletions coprocess_python.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,20 +193,14 @@ type PythonDispatcher struct {

// Dispatch takes a CoProcessMessage and sends it to the CP.
func (d *PythonDispatcher) Dispatch(objectPtr unsafe.Pointer) unsafe.Pointer {

var object *C.struct_CoProcessMessage
object = (*C.struct_CoProcessMessage)(objectPtr)

var newObjectPtr *C.struct_CoProcessMessage
newObjectPtr = C.Python_DispatchHook(object)

object := (*C.struct_CoProcessMessage)(objectPtr)
newObjectPtr := C.Python_DispatchHook(object)
return unsafe.Pointer(newObjectPtr)
}

// DispatchEvent dispatches a Tyk event.
func (d *PythonDispatcher) DispatchEvent(eventJSON []byte) {
var CEventJSON *C.char
CEventJSON = C.CString(string(eventJSON))
CEventJSON := C.CString(string(eventJSON))
C.Python_DispatchEvent(CEventJSON)
C.free(unsafe.Pointer(CEventJSON))
return
Expand All @@ -219,8 +213,7 @@ func (d *PythonDispatcher) Reload() {

// HandleMiddlewareCache isn't used by Python.
func (d *PythonDispatcher) HandleMiddlewareCache(b *apidef.BundleManifest, basePath string) {
var CBundlePath *C.char
CBundlePath = C.CString(basePath)
CBundlePath := C.CString(basePath)
C.Python_HandleMiddlewareCache(CBundlePath)
return
}
Expand All @@ -245,14 +238,9 @@ func PythonLoadDispatcher() (err error) {

// PythonNewDispatcher creates an instance of TykDispatcher.
func PythonNewDispatcher(middlewarePath string, eventHandlerPath string, bundlePaths []string) (dispatcher coprocess.Dispatcher, err error) {
var CMiddlewarePath *C.char
CMiddlewarePath = C.CString(middlewarePath)

var CEventHandlerPath *C.char
CEventHandlerPath = C.CString(eventHandlerPath)

var CBundlePaths *C.char
CBundlePaths = C.CString(strings.Join(bundlePaths, ":"))
CMiddlewarePath := C.CString(middlewarePath)
CEventHandlerPath := C.CString(eventHandlerPath)
CBundlePaths := C.CString(strings.Join(bundlePaths, ":"))

result := C.Python_NewDispatcher(CMiddlewarePath, CEventHandlerPath, CBundlePaths)

Expand All @@ -270,10 +258,8 @@ func PythonNewDispatcher(middlewarePath string, eventHandlerPath string, bundleP

// PythonSetEnv sets PYTHONPATH, it's called before initializing the interpreter.
func PythonSetEnv(pythonPaths ...string) {
var CPythonPath *C.char
CPythonPath = C.CString(strings.Join(pythonPaths, ":"))
CPythonPath := C.CString(strings.Join(pythonPaths, ":"))
C.Python_SetEnv(CPythonPath)

C.free(unsafe.Pointer(CPythonPath))
}

Expand Down
Loading

0 comments on commit fd2b29a

Please sign in to comment.