github.com/dbernstein1/tyk@v2.9.0-beta9-dl-apic+incompatible/gateway/coprocess_api.go (about)

     1  // +build coprocess
     2  // +build !grpc
     3  
     4  package gateway
     5  
     6  /*
     7  #include <stdio.h>
     8  
     9  #include "../coprocess/api.h"
    10  
    11  #ifdef ENABLE_PYTHON
    12  #include "../coprocess/python/dispatcher.h"
    13  #include "../coprocess/python/binding.h"
    14  #endif
    15  */
    16  import "C"
    17  
    18  import (
    19  	"fmt"
    20  	"github.com/sirupsen/logrus"
    21  
    22  	"github.com/TykTechnologies/tyk/apidef"
    23  	"github.com/TykTechnologies/tyk/storage"
    24  )
    25  
    26  // CoProcessDefaultKeyPrefix is used as a key prefix for this CP.
    27  const CoProcessDefaultKeyPrefix = "coprocess-data:"
    28  
    29  // TODO: implement INCR, DECR?
    30  
    31  // TykStoreData is a CoProcess API function for storing data.
    32  //export TykStoreData
    33  func TykStoreData(CKey, CValue *C.char, CTTL C.int) {
    34  	key := C.GoString(CKey)
    35  	value := C.GoString(CValue)
    36  	ttl := int64(CTTL)
    37  
    38  	store := storage.RedisCluster{KeyPrefix: CoProcessDefaultKeyPrefix}
    39  	store.SetKey(key, value, ttl)
    40  }
    41  
    42  // TykGetData is a CoProcess API function for fetching data.
    43  //export TykGetData
    44  func TykGetData(CKey *C.char) *C.char {
    45  	key := C.GoString(CKey)
    46  
    47  	store := storage.RedisCluster{KeyPrefix: CoProcessDefaultKeyPrefix}
    48  	// TODO: return error
    49  	val, _ := store.GetKey(key)
    50  	return C.CString(val)
    51  }
    52  
    53  // TykTriggerEvent is a CoProcess API function for triggering Tyk system events.
    54  //export TykTriggerEvent
    55  func TykTriggerEvent(CEventName, CPayload *C.char) {
    56  	eventName := C.GoString(CEventName)
    57  	payload := C.GoString(CPayload)
    58  
    59  	FireSystemEvent(apidef.TykEvent(eventName), EventMetaDefault{
    60  		Message: payload,
    61  	})
    62  }
    63  
    64  // CoProcessLog is a bridge for using Tyk log from CP.
    65  //export CoProcessLog
    66  func CoProcessLog(CMessage, CLogLevel *C.char) {
    67  	message := C.GoString(CMessage)
    68  	logLevel := C.GoString(CLogLevel)
    69  	coProcessName := fmt.Sprintf("%v", CoProcessName)
    70  	switch logLevel {
    71  	case "debug":
    72  		log.WithFields(logrus.Fields{
    73  			"prefix": coProcessName,
    74  		}).Debug(message)
    75  	case "error":
    76  		log.WithFields(logrus.Fields{
    77  			"prefix": coProcessName,
    78  		}).Error(message)
    79  	case "warning":
    80  		log.WithFields(logrus.Fields{
    81  			"prefix": coProcessName,
    82  		}).Warning(message)
    83  	default:
    84  		log.WithFields(logrus.Fields{
    85  			"prefix": coProcessName,
    86  		}).Info(message)
    87  	}
    88  }