From 72a972014f04e1f99115ee27c4d22fedab9ac2c6 Mon Sep 17 00:00:00 2001 From: wansuyoo Date: Tue, 9 Apr 2019 16:55:22 +0900 Subject: [PATCH] sync 20190409 --- .gitignore | 6 +- Makefile | 2 +- src/CMain/inc/orchestration.h | 76 ---------- src/CMain/inc/orchestration_server.h | 4 + src/CMain/src/main.c | 37 ++++- src/CMain/src/orchestration_server.c | 201 ++++++++++++++++++------- src/configuremgr/configuremgr_test.go | 7 +- src/configuremgr/edge_log.go | 10 -- src/configuremgr/mock/simulation.go | 16 +- src/configuremgr/watchConfPath.go | 17 ++- src/discoverymgr/README.md | 0 src/discoverymgr/discovery_execution.go | 4 +- src/discoverymgr/discovery_init.go | 3 +- src/discoverymgr/discoverymgr_test.go | 43 ++---- src/interface/main.go | 4 + src/libedge-orchestration/sample/main.c | 4 +- src/logmgr/logmgr.go | 4 +- src/logmgr/logmgr_test.go | 27 ++++ src/orchestrationapi/edge_log.go | 17 --- src/orchestrationapi/orchestration_api_test.go | 25 +-- src/orchestrationapi/orchstration_api.go | 5 +- src/scoringmgr/edge_log.go | 17 --- src/scoringmgr/handlers.go | 35 ++--- src/scoringmgr/lib_scoring_interface.go | 9 +- src/scoringmgr/mock/mock_lib_add.go | 12 +- src/scoringmgr/score.go | 4 +- src/scoringmgr/scoringmgr_test.go | 25 +-- src/securemgr/cipher.go | 8 - src/securemgr/cipher_test.go | 151 +++++++++++++++++++ 29 files changed, 475 insertions(+), 298 deletions(-) delete mode 100755 src/CMain/inc/orchestration.h mode change 100644 => 100755 src/configuremgr/configuremgr_test.go delete mode 100644 src/configuremgr/edge_log.go delete mode 100755 src/discoverymgr/README.md create mode 100755 src/logmgr/logmgr_test.go delete mode 100755 src/orchestrationapi/edge_log.go delete mode 100644 src/scoringmgr/edge_log.go mode change 100644 => 100755 src/scoringmgr/lib_scoring_interface.go create mode 100755 src/securemgr/cipher_test.go diff --git a/.gitignore b/.gitignore index 1df7e72..2b7f713 100755 --- a/.gitignore +++ b/.gitignore @@ -8,7 +8,11 @@ pkg/* vendor/src doc/generate-api/* 3rdparty/ - +src/CMain/bin/* +src/CMain/lib/* +src/GoMain/bin/* +src/libedge-orchestration/lib/* +src/libedge-orchestration/sample/orchestration_sample # Test binary, build with `go test -c` *.test diff --git a/Makefile b/Makefile index 0a0d6a0..0195057 100755 --- a/Makefile +++ b/Makefile @@ -11,7 +11,7 @@ GO_LDFLAGS := -ldflags '-extldflags "-static"' PKG_NAME := edge-orchestration EXEC_SRC_DIR := GoMain/src OBJ_SRC_DIR := interface -PKG_DIRS := devicemgr discoverymgr interface restapi/v1 servicemgr scoringmgr orchestrationapi configuremgr +PKG_DIRS := devicemgr discoverymgr interface restapi/v1 servicemgr scoringmgr orchestrationapi configuremgr logmgr SERVICE_FILE := $(PKG_NAME).service MANIFEST_FILE := $(PKG_NAME).manifest DBUS_SERVICE_FILE := org.tizen.orchestration.service diff --git a/src/CMain/inc/orchestration.h b/src/CMain/inc/orchestration.h deleted file mode 100755 index 66b27ac..0000000 --- a/src/CMain/inc/orchestration.h +++ /dev/null @@ -1,76 +0,0 @@ -/* Code generated by cmd/cgo; DO NOT EDIT. */ - -/* package interface */ - - -#line 1 "cgo-builtin-prolog" - -#include /* for ptrdiff_t below */ - -#ifndef GO_CGO_EXPORT_PROLOGUE_H -#define GO_CGO_EXPORT_PROLOGUE_H - -typedef struct { const char *p; ptrdiff_t n; } _GoString_; - -#endif - -/* Start of preamble from import "C" comments. */ - - - - -/* End of preamble from import "C" comments. */ - - -/* Start of boilerplate cgo prologue. */ -#line 1 "cgo-gcc-export-header-prolog" - -#ifndef GO_CGO_PROLOGUE_H -#define GO_CGO_PROLOGUE_H - -typedef signed char GoInt8; -typedef unsigned char GoUint8; -typedef short GoInt16; -typedef unsigned short GoUint16; -typedef int GoInt32; -typedef unsigned int GoUint32; -typedef long long GoInt64; -typedef unsigned long long GoUint64; -typedef GoInt64 GoInt; -typedef GoUint64 GoUint; -typedef __SIZE_TYPE__ GoUintptr; -typedef float GoFloat32; -typedef double GoFloat64; -typedef float _Complex GoComplex64; -typedef double _Complex GoComplex128; - -/* - static assertion to make sure the file is being used on architecture - at least with matching size of GoInt. -*/ -typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1]; - -typedef _GoString_ GoString; -typedef void *GoMap; -typedef void *GoChan; -typedef struct { void *t; void *v; } GoInterface; -typedef struct { void *data; GoInt len; GoInt cap; } GoSlice; - -#endif - -/* End of boilerplate cgo prologue. */ - -#ifdef __cplusplus -extern "C" { -#endif - - -extern int OrchestrationInit(); - -extern int OrchestrationRequestService(char* p0, char* p1); - -extern int PrintLog(char* p0); - -#ifdef __cplusplus -} -#endif diff --git a/src/CMain/inc/orchestration_server.h b/src/CMain/inc/orchestration_server.h index 318c096..957ec2f 100755 --- a/src/CMain/inc/orchestration_server.h +++ b/src/CMain/inc/orchestration_server.h @@ -6,6 +6,8 @@ extern "C" { #endif +#define DEBUG(format, ...) printLog("[%s:%d] "format, __FILE__, __LINE__, ##__VA_ARGS__); + typedef enum { ORCH_ERROR_NONE = 0, ORCH_ERROR_INVALID_PARAMETER, @@ -15,8 +17,10 @@ typedef enum { typedef void (*request_service_cb)(char* app_name, char* service_info); +void set_default_dbus_interface(void); int orchestration_server_initialize(request_service_cb cb); void orchestration_server_finish(void); +void printLog(const char *format, ...); #ifdef __cplusplus } diff --git a/src/CMain/src/main.c b/src/CMain/src/main.c index 8383303..92424b0 100755 --- a/src/CMain/src/main.c +++ b/src/CMain/src/main.c @@ -1,12 +1,20 @@ #include #include +#include +#include #include #include void request_cb(char* app_name, char* service_info){ - printf("app_name : %s\n", app_name); - printf("service_info : %s\n", service_info); + int result = ORCH_ERROR_FAULT; + + DEBUG("app_name : %s\n", app_name); + DEBUG("service_info : %s\n", service_info); + result = OrchestrationRequestService(app_name, service_info); + if (result != ORCH_ERROR_NONE) { + DEBUG("OrchestrationRequestService failed\n"); + } } int main(void){ @@ -14,14 +22,15 @@ int main(void){ GMainLoop *loop; + /* DEBUG for log can be used after OrchestrationInit */ printf("OrchestrationInit call"); OrchestrationInit(); - printf("orchestration_server_initialize call"); - PrintLog("orchestration_server_initialize call"); + set_default_dbus_interface(); + DEBUG("orchestration_server_initialize call"); result = orchestration_server_initialize(request_cb); if(result != ORCH_ERROR_NONE){ - printf("orchestration_server_initialize failed\n"); + DEBUG("orchestration_server_initialize failed\n"); orchestration_server_finish(); } @@ -34,3 +43,21 @@ int main(void){ return 0; } + +void printLog(const char *format, ...) { + int buf_size; + char *buffer = NULL; + va_list args; + + va_start(args, format); + buf_size = vsnprintf(0, 0, format, args); + va_end(args); + + buffer = malloc(buf_size + 1); + + va_start(args, format); + vsnprintf(buffer, buf_size + 1, format, args); + PrintLog(buffer); + if (buffer != NULL) free(buffer); + va_end(args); +} diff --git a/src/CMain/src/orchestration_server.c b/src/CMain/src/orchestration_server.c index db1d482..6bc1dc0 100755 --- a/src/CMain/src/orchestration_server.c +++ b/src/CMain/src/orchestration_server.c @@ -2,9 +2,57 @@ #include #include +#include #include /* ---------------------------------------------------------------------------------------------------- */ +typedef GDBusConnection *(*_g_bus_get_sync)(GBusType bus_type, GCancellable *cancellable, GError **error); +typedef guint (*_g_bus_own_name)(GBusType bus_type, + const gchar *name, + GBusNameOwnerFlags flags, + GBusAcquiredCallback bus_acquired_handler, + GBusNameAcquiredCallback name_acquired_handler, + GBusNameLostCallback name_lost_handler, + gpointer user_data, + GDestroyNotify user_data_free_func); +typedef void (*_g_bus_unown_name)(guint owner_id); +typedef GDBusNodeInfo *(*_g_dbus_node_info_new_for_xml)(const gchar *xml_data, + GError **error); +typedef void (*_g_dbus_node_info_unref)(GDBusNodeInfo *info); +typedef guint (*_g_dbus_connection_register_object)(GDBusConnection *connection, + const gchar *object_path, + GDBusInterfaceInfo *interface_info, + const GDBusInterfaceVTable *vtable, + gpointer user_data, + GDestroyNotify user_data_free_func, + GError **error); +typedef GError *(*_g_error_new)(GQuark domain, + gint code, + const gchar *format, + ...); +typedef void (*_g_error_free)(GError *error); +typedef void (*_g_dbus_method_invocation_return_value)(GDBusMethodInvocation *invocation, + GVariant *parameters); +typedef void (*_g_dbus_method_invocation_return_gerror)(GDBusMethodInvocation *invocation, + const GError *error); +/* ---------------------------------------------------------------------------------------------------- */ + +typedef struct +{ + _g_bus_get_sync get_sync; + _g_bus_own_name own_name; + _g_bus_unown_name unown_name; + _g_dbus_node_info_new_for_xml node_info_new_for_xml; + _g_dbus_node_info_unref node_info_unref; + _g_dbus_connection_register_object connection_register_object; + _g_error_new error_new; + _g_error_free error_free; + _g_dbus_method_invocation_return_value invocation_return_value; + _g_dbus_method_invocation_return_gerror invocation_return_gerror; +} _gdbus_interface; + +static _gdbus_interface _gdbus; + static guint owner_id; static GDBusConnection *_gdbus_conn; static GDBusNodeInfo *introspection_data = NULL; @@ -18,6 +66,7 @@ request_service_cb _request_service_cb = NULL; GDBusErrorEntry _orchestration_svc_errors[] = { {ORCH_ERROR_NONE, "NoError"}, {ORCH_ERROR_INVALID_PARAMETER, "Invalid parameter"}, + {ORCH_ERROR_DBUS_FAILURE, "dbus failure"}, {ORCH_ERROR_FAULT, "Orchestration Failed"}, }; @@ -33,6 +82,20 @@ static gchar introspection_xml[] = " "; /* ---------------------------------------------------------------------------------------------------- */ +void set_default_dbus_interface(void) +{ + _gdbus.get_sync = g_bus_get_sync; + _gdbus.own_name = g_bus_own_name; + _gdbus.unown_name = g_bus_unown_name; + _gdbus.node_info_new_for_xml = g_dbus_node_info_new_for_xml; + _gdbus.node_info_unref = g_dbus_node_info_unref; + _gdbus.connection_register_object = g_dbus_connection_register_object; + _gdbus.error_new = g_error_new; + _gdbus.error_free = g_error_free; + _gdbus.invocation_return_value = g_dbus_method_invocation_return_value; + _gdbus.invocation_return_gerror = g_dbus_method_invocation_return_gerror; +} + static GQuark _ORCHESTRATION_ERROR_quark(void) { static volatile gsize quark_volatile = 0; @@ -51,8 +114,6 @@ static int _request_service(GVariant *parameters, GVariant **reply_body) if (app_name == NULL) return ORCH_ERROR_INVALID_PARAMETER; - if (service_info == NULL) - return ORCH_ERROR_INVALID_PARAMETER; _request_service_cb(app_name, service_info); @@ -76,97 +137,131 @@ static void _handle_method_call( { ret = _request_service(parameters, &reply_body); } + if (ret == ORCH_ERROR_NONE) { - printf("Orchestration service Success, method name : %s\n", method_name); + DEBUG("Orchestration service Success, method name : %s", method_name); g_dbus_method_invocation_return_value(invocation, reply_body); } else { - printf("Orchestration service fail, method name : %s\n", method_name); + DEBUG("Orchestration service fail, method name : %s", method_name); - GError *error = g_error_new(_ORCHESTRATION_ERROR_quark(), ret, "request service failed"); - g_dbus_method_invocation_return_gerror(invocation, error); + GError *error = _gdbus.error_new(_ORCHESTRATION_ERROR_quark(), ret, "orchestration failed"); + _gdbus.invocation_return_gerror(invocation, error); g_error_free(error); } } static const GDBusInterfaceVTable _interface_vtable = -{ + { _handle_method_call, NULL, - NULL -}; + NULL}; -static int _dbus_init(void) +static int _get_sync(void) { GError *error = NULL; - if (_gdbus_conn == NULL) { - _gdbus_conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error); + _gdbus_conn = _gdbus.get_sync(G_BUS_TYPE_SYSTEM, NULL, &error); if (_gdbus_conn == NULL) { if (error != NULL) { - printf("Failed to get dbus [%s]", error->message); - g_error_free(error); + DEBUG("Failed to get dbus [%s]", error->message); + _gdbus.error_free(error); } return ORCH_ERROR_DBUS_FAILURE; } } - return ORCH_ERROR_NONE; } -static int orch_dbus_initialize() +static int _own_name(void) { - int result; - guint orch_registration_id; - - GError *error = NULL; - - result = _dbus_init(); - if (result != ORCH_ERROR_NONE) - { - printf("Failed to _dbus_init"); - goto out; - } - owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM, - _ORCHESTRATION_BUS_NAME, - G_BUS_NAME_OWNER_FLAGS_NONE, - NULL, - NULL, - NULL, - NULL, NULL); + int result = ORCH_ERROR_NONE; + + owner_id = _gdbus.own_name(G_BUS_TYPE_SYSTEM, + _ORCHESTRATION_BUS_NAME, + G_BUS_NAME_OWNER_FLAGS_NONE, + NULL, + NULL, + NULL, + NULL, NULL); if (!owner_id) { - printf("Failed to own name"); + DEBUG("Failed to own name"); result = ORCH_ERROR_DBUS_FAILURE; - goto out; } + return result; +} + +static int _set_node_info_new_for_xml(void) +{ + int result = ORCH_ERROR_NONE; + GError *error = NULL; - introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, &error); + introspection_data = _gdbus.node_info_new_for_xml(introspection_xml, &error); if (!introspection_data) { - printf("g_dbus_node_info_new_for_xml is failed."); + DEBUG("g_dbus_node_info_new_for_xml is failed"); if (error != NULL) { - printf("g_dbus_node_info_new_for_xml err [%s]", error->message); - g_error_free(error); + DEBUG("g_dbus_node_info_new_for_xml err [%s]", error->message); + _gdbus.error_free(error); } result = ORCH_ERROR_DBUS_FAILURE; - goto out; } + return result; +} - orch_registration_id = g_dbus_connection_register_object(_gdbus_conn, +static int _connection_register_object(void) +{ + int result = ORCH_ERROR_NONE; + guint orch_registration_id; + + orch_registration_id = _gdbus.connection_register_object(_gdbus_conn, _ORCHESTRATION_OBJECT_PATH, introspection_data->interfaces[0], &_interface_vtable, NULL, NULL, NULL); if (orch_registration_id == 0) { - printf("Failed to g_dbus_connection_register_object"); + DEBUG("Failed to g_dbus_connection_register_object"); result = ORCH_ERROR_DBUS_FAILURE; + } + return result; +} + +static int orch_dbus_initialize(void) +{ + int result; + + result = _get_sync(); + if (result != ORCH_ERROR_NONE) + { + DEBUG("Failed to _dbus_init"); + goto out; + } + + result = _own_name(); + if (result != ORCH_ERROR_NONE) + { + DEBUG("Failed to _dbus_own_name"); + goto out; + } + + result = _set_node_info_new_for_xml(); + if (result != ORCH_ERROR_NONE) + { + DEBUG("Failed to _set_node_info_new_for_xml"); + goto out; + } + + result = _connection_register_object(); + if (result != ORCH_ERROR_NONE) + { + DEBUG("Failed to _connection_register_object"); goto out; } @@ -174,24 +269,26 @@ out: return result; } - int orchestration_server_initialize(request_service_cb cb) { - int result; + int result = ORCH_ERROR_NONE; if (cb == NULL) { result = ORCH_ERROR_INVALID_PARAMETER; - printf("request_service_cb is null."); + DEBUG("request_service_cb is null"); goto out; } _request_service_cb = cb; - result = orch_dbus_initialize(); - if(result != ORCH_ERROR_NONE) + if (!owner_id) { - printf("orch_dbus_initialize is failed"); - goto out; + result = orch_dbus_initialize(); + if (result != ORCH_ERROR_NONE) + { + DEBUG("orch_dbus_initialize is failed"); + goto out; + } } out: @@ -202,10 +299,10 @@ void orchestration_server_finish(void) { if (owner_id) { - g_bus_unown_name(owner_id); + _gdbus.unown_name(owner_id); } if (introspection_data) { - g_dbus_node_info_unref(introspection_data); + _gdbus.node_info_unref(introspection_data); } } diff --git a/src/configuremgr/configuremgr_test.go b/src/configuremgr/configuremgr_test.go old mode 100644 new mode 100755 index 8c35dd6..80b1aca --- a/src/configuremgr/configuremgr_test.go +++ b/src/configuremgr/configuremgr_test.go @@ -2,6 +2,7 @@ package configuremgr_test import ( "fmt" + "log" "os/exec" "testing" "time" @@ -42,11 +43,11 @@ func TestBasicMockConfigureMgr(t *testing.T) { } func execCommand(command string) { - configuremgr.DLog.Println(command) + log.Println(command) cmd := exec.Command("sh", "-c", command) stdoutStderr, err := cmd.CombinedOutput() - configuremgr.DLog.Printf("%s", stdoutStderr) + log.Printf("%s", stdoutStderr) if err != nil { - configuremgr.ELog.Fatal(err) + log.Fatal(err) } } diff --git a/src/configuremgr/edge_log.go b/src/configuremgr/edge_log.go deleted file mode 100644 index a0f42b3..0000000 --- a/src/configuremgr/edge_log.go +++ /dev/null @@ -1,10 +0,0 @@ -package configuremgr - -import ( - "log" - "os" -) - -var ILog *log.Logger = log.New(os.Stdout, "[configuremgr] INFO : ", log.LstdFlags) -var ELog *log.Logger = log.New(os.Stdout, "[configuremgr] ERROR : ", log.LstdFlags) -var DLog *log.Logger = log.New(os.Stdout, "[configuremgr] DEBUG : ", log.LstdFlags) diff --git a/src/configuremgr/mock/simulation.go b/src/configuremgr/mock/simulation.go index ad51685..d1e1118 100755 --- a/src/configuremgr/mock/simulation.go +++ b/src/configuremgr/mock/simulation.go @@ -1,25 +1,25 @@ package mockconfiguremgr import ( - configuremgr "configuremgr" confdescription "configuremgr/description" + "log" ) func PushConfPathDiscoveryDeviceMock(doc *confdescription.Doc) (err error) { - configuremgr.ILog.Println("pushConfPathDiscoveryDeviceMock") - configuremgr.ILog.Println(*doc) + log.Println("[mockconfiguremgr] pushConfPathDiscoveryDeviceMock") + log.Println(*doc) return } func PushConfPathAppExecuteMock(doc *confdescription.Doc) (err error) { - configuremgr.ILog.Println("pushConfPathAppExecuteMock") - configuremgr.ILog.Println(*doc) + log.Println("[mockconfiguremgr] pushConfPathAppExecuteMock") + log.Println(*doc) return } func PushLibPathScoringAppMock(libPath string, doc *confdescription.Doc, handlersCh chan<- interface{}) (err error) { - configuremgr.ILog.Println("pushLibPathScoringAppMock") - configuremgr.ILog.Println(libPath) - configuremgr.ILog.Println(doc) + log.Println("[mockconfiguremgr] pushLibPathScoringAppMock", "mockconfiguremgr") + log.Println(libPath) + log.Println(doc) return } diff --git a/src/configuremgr/watchConfPath.go b/src/configuremgr/watchConfPath.go index f4d64d5..62133c7 100755 --- a/src/configuremgr/watchConfPath.go +++ b/src/configuremgr/watchConfPath.go @@ -2,6 +2,7 @@ package configuremgr import ( "io/ioutil" + "log" "os" "path/filepath" "strings" @@ -82,8 +83,8 @@ func (cfgMgr *ConfigureMgr) getdirname(path string) (libPath, confPath string) { libPath = path + "/" + "lib" + dirname + ".so" confPath = path + "/" + dirname + ".conf" - DLog.Println("libPath : " + libPath) - DLog.Println("confPath : " + confPath) + log.Println("[configuremgr] libPath : " + libPath) + log.Println("[configuremgr] confPath : " + confPath) return @@ -93,7 +94,7 @@ func (cfgMgr *ConfigureMgr) Watch(path string) { // logic for already installed configuration files, err := ioutil.ReadDir(path) if err != nil { - ELog.Fatal(err) + log.Fatal(err) } for _, f := range files { @@ -102,7 +103,7 @@ func (cfgMgr *ConfigureMgr) Watch(path string) { watcher, err := fsnotify.NewWatcher() if err != nil { - ELog.Fatal(err) + log.Fatal(err) } defer watcher.Close() @@ -115,7 +116,7 @@ func (cfgMgr *ConfigureMgr) Watch(path string) { return } - ILog.Println("log event:", event) + log.Println("log event:", event) switch event.Op { case fsnotify.Create: // case fsnotify.Chmod: @@ -127,7 +128,7 @@ func (cfgMgr *ConfigureMgr) Watch(path string) { if !ok { return } - ELog.Println("error:", err) + log.Println("error:", err) } //selecte end } //for end @@ -135,10 +136,10 @@ func (cfgMgr *ConfigureMgr) Watch(path string) { err = watcher.Add(path) if err != nil { - ELog.Fatal(err) + log.Fatal(err) } <-cfgMgr.Done - ILog.Println("configuremgr watch end") + log.Println("configuremgr watch end") } diff --git a/src/discoverymgr/README.md b/src/discoverymgr/README.md deleted file mode 100755 index e69de29..0000000 diff --git a/src/discoverymgr/discovery_execution.go b/src/discoverymgr/discovery_execution.go index 615c72b..ce52b19 100755 --- a/src/discoverymgr/discovery_execution.go +++ b/src/discoverymgr/discovery_execution.go @@ -32,14 +32,12 @@ func GetDeviceListWithService(target string) ([]string, error) { } var ret []string for key, value := range data { - //서비스명으로검색 for _, val := range value { if val == target { ret = append(ret, key) } } } - //return nothing인 경우? return ret, nil } @@ -52,7 +50,7 @@ func discoverDevice() (map[string][]string, error) { return nil, err } - var data = make(map[string][]string) //data[deviceIP][[]ServiceNames] + var data = make(map[string][]string) //data[deviceIP][]ServiceNames entries := make(chan *zeroconf.ServiceEntry) go func(results <-chan *zeroconf.ServiceEntry) { for entry := range results { diff --git a/src/discoverymgr/discovery_init.go b/src/discoverymgr/discovery_init.go index 34db915..a37e635 100755 --- a/src/discoverymgr/discovery_init.go +++ b/src/discoverymgr/discovery_init.go @@ -3,7 +3,6 @@ package discoverymgr import ( "common" "errors" - "fmt" "log" "net" "strings" @@ -50,7 +49,7 @@ func registerDevice(AppNames []string, ret chan error) { select { case exit := <-ExitChan: if exit == 1 { - fmt.Println("Orchestration Agent has been terminated") + log.Printf("[%s] Orchestration Agent has been terminated", logPrefix) } } } diff --git a/src/discoverymgr/discoverymgr_test.go b/src/discoverymgr/discoverymgr_test.go index 6c6c9b3..ecaa25a 100755 --- a/src/discoverymgr/discoverymgr_test.go +++ b/src/discoverymgr/discoverymgr_test.go @@ -1,37 +1,13 @@ package discoverymgr import ( - "net" - "os" + "common" "testing" "time" confdescription "configuremgr/description" ) -//@Todo os dependency check -func getIP() string { - addrs, err := net.InterfaceAddrs() - if err != nil { - os.Stderr.WriteString("Oops: " + err.Error() + "\n") - os.Exit(1) - } - var ipv4 string - for _, a := range addrs { - if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { - if ipnet.IP.To4() != nil { - if ipnet.IP.String()[:2] == "10" { - os.Stdout.WriteString(ipnet.IP.String() + "\n") - ipv4 = ipnet.IP.String() - break - } - - } - } - } - return ipv4 -} - func closeDiscovery() { time.Sleep(time.Millisecond * 1) ExitChan <- 1 @@ -54,8 +30,15 @@ func TestGetDeviceListWithService(t *testing.T) { closeDiscovery() t.Fatal() } - - ipv4 := getIP() + if len(ret) == 0 { + closeDiscovery() + t.Fatal() + } + ipv4, err := common.GetOutboundIP() + if err != nil { + closeDiscovery() + t.Fatal() + } isSuccess := false for _, v := range ret { if v == ipv4 { @@ -81,7 +64,11 @@ func TestGetDeviceList(t *testing.T) { t.Fatal() } - ipv4 := getIP() + ipv4, err := common.GetOutboundIP() + if err != nil { + closeDiscovery() + t.Fatal() + } isExist := false for i, v := range ret { if v.DeviceIP == ipv4 { diff --git a/src/interface/main.go b/src/interface/main.go index 68d98aa..4d1f6d5 100755 --- a/src/interface/main.go +++ b/src/interface/main.go @@ -14,6 +14,7 @@ import "C" import ( "log" "logmgr" + "securemgr" "strings" "sync" @@ -24,6 +25,8 @@ import ( servicemgr "servicemgr" ) +var keyFilePath string = "/etc/edge-orchestration/key.txt" + //export OrchestrationInit func OrchestrationInit() (errCode C.int) { logmgr.Init() @@ -35,6 +38,7 @@ func OrchestrationInit() (errCode C.int) { orcheEngine.IConfiguremgr = configuremgr.Init() discoverymgr.InitDiscovery() servicemgr.Init() + securemgr.Init(keyFilePath) orcheEngine.IScoringmgr.IRunningScore = scoringmgr.LoadScoringGeneralInterface orcheEngine.IScoringmgr.IGetScore = scoringmgr.GetScore diff --git a/src/libedge-orchestration/sample/main.c b/src/libedge-orchestration/sample/main.c index d5e9c36..29a2500 100755 --- a/src/libedge-orchestration/sample/main.c +++ b/src/libedge-orchestration/sample/main.c @@ -8,7 +8,7 @@ void status_cb(orchestration_service_status_e staus, void* user_data) int main() { orchestration_service_info_s service_info; - service_info.exec_parameter = "param"; - orchestration_request_service("app_name12312313", service_info, status_cb, NULL); + service_info.exec_parameter = "-al"; + orchestration_request_service("ls", service_info, status_cb, NULL); return 0; } \ No newline at end of file diff --git a/src/logmgr/logmgr.go b/src/logmgr/logmgr.go index 9e85c47..3cd98e8 100755 --- a/src/logmgr/logmgr.go +++ b/src/logmgr/logmgr.go @@ -6,8 +6,8 @@ import ( "github.com/leemcloughlin/logfile" ) -const logFilePath = "/var/log" -const logFileName = "orchestration.log" +var logFilePath = "/var/log" +var logFileName = "orchestration.log" // Init for initializing logmgr func Init() { diff --git a/src/logmgr/logmgr_test.go b/src/logmgr/logmgr_test.go new file mode 100755 index 0000000..a96ee44 --- /dev/null +++ b/src/logmgr/logmgr_test.go @@ -0,0 +1,27 @@ +package logmgr + +import ( + "log" + "os" + "testing" +) + +func TestInit(t *testing.T) { + + logFilePath, _ = os.Getwd() + log.Printf("FilePath = %s", logFilePath) + logFileName = "TestlogFile.log" + + Init() + + TestFile := logFilePath + "/" + logFileName + + if _, err := os.Stat(TestFile); os.IsNotExist(err) { + t.Error(err.Error()) + } + + err := os.Remove(TestFile) + if err != nil { + t.Error(err.Error()) + } +} diff --git a/src/orchestrationapi/edge_log.go b/src/orchestrationapi/edge_log.go deleted file mode 100755 index 326918a..0000000 --- a/src/orchestrationapi/edge_log.go +++ /dev/null @@ -1,17 +0,0 @@ -package orchestrationapi - -import ( - "log" - "os" -) - -var ( - // ILog inforamton level log - ILog = log.New(os.Stdout, "[scoringmgr] INFO : ", log.LstdFlags) - - // ELog Error level log - ELog = log.New(os.Stdout, "[scoringmgr] ERROR : ", log.LstdFlags) - - // DLog Debug level log - DLog = log.New(os.Stdout, "[scoringmgr] DEBUG : ", log.LstdFlags) -) diff --git a/src/orchestrationapi/orchestration_api_test.go b/src/orchestrationapi/orchestration_api_test.go index 955ea91..3097ff4 100755 --- a/src/orchestrationapi/orchestration_api_test.go +++ b/src/orchestrationapi/orchestration_api_test.go @@ -5,6 +5,7 @@ package orchestrationapi import ( "discoverymgr" "fmt" + "log" "os/exec" "testing" "time" @@ -397,36 +398,36 @@ func TestConfigureMgrDiscoveryMgrScoringMgrServiceMgr(t *testing.T) { } func PushConfPathDiscoveryDeviceMock(doc *confdescription.Doc) (err error) { - ILog.Println("pushConfPathDiscoveryDeviceMock") - ILog.Println(*doc) + log.Println("[orchestrationapi] pushConfPathDiscoveryDeviceMock") + log.Println(*doc) return } func PushLibPathScoringAppMock(libPath string, doc *confdescription.Doc, handlersCh chan<- interface{}) (err error) { - ILog.Println("pushLibPathScoringAppMock") - ILog.Println(libPath) + log.Println("[orchestrationapi] pushLibPathScoringAppMock") + log.Println(libPath) return } func GetEndpointDevicesMock(serviceName string) ([]string, error) { - DLog.Printf("GetEndpointDevicesMock serviceName: %s\n", serviceName) + log.Printf("[orchestrationapi] GetEndpointDevicesMock serviceName: %s\n", serviceName) return []string{"localhost"}, nil } func ExecuteAppMock(target string, name string, args []string, notiChan chan string) (serviceID uint64, err error) { - ILog.Println("ExecuteApp") - ILog.Println(target) - ILog.Println(name) - ILog.Println(args) + log.Println("[orchestrationapi] ExecuteApp") + log.Println(target) + log.Println(name) + log.Println(args) return } func execCommand(command string) { - configuremgr.DLog.Println(command) + log.Println(command) cmd := exec.Command("sh", "-c", command) stdoutStderr, err := cmd.CombinedOutput() - configuremgr.DLog.Printf("%s", stdoutStderr) + log.Printf("%s", stdoutStderr) if err != nil { - configuremgr.ELog.Fatal(err) + log.Fatal(err) } } diff --git a/src/orchestrationapi/orchstration_api.go b/src/orchestrationapi/orchstration_api.go index ff8eb11..a4c150d 100755 --- a/src/orchestrationapi/orchstration_api.go +++ b/src/orchestrationapi/orchstration_api.go @@ -1,6 +1,7 @@ package orchestrationapi import ( + "log" "sort" "sync/atomic" @@ -65,7 +66,7 @@ func RequestService(appName string, args []string) (handle int) { if len(deviceScores) > 0 { executeApp(deviceScores[0].endpoint, appName, args, serviceClient.notiChan) - ILog.Println(deviceScores) + log.Println("[orchestrationapi] ", deviceScores) } return @@ -78,7 +79,7 @@ func Close(handle uint64) { func (client *orcheClient) listenNotify() { select { case str := <-client.notiChan: - ILog.Printf("service status changed [appNames:%s][status:%s]\n", client.appName, str) + log.Printf("[orchestrationapi] service status changed [appNames:%s][status:%s]\n", client.appName, str) } } diff --git a/src/scoringmgr/edge_log.go b/src/scoringmgr/edge_log.go deleted file mode 100644 index cb072bf..0000000 --- a/src/scoringmgr/edge_log.go +++ /dev/null @@ -1,17 +0,0 @@ -package scoringmgr - -import ( - "log" - "os" -) - -var ( - // ILog inforamton level log - ILog = log.New(os.Stdout, "[scoringmgr] INFO : ", log.LstdFlags) - - // ELog Error level log - ELog = log.New(os.Stdout, "[scoringmgr] ERROR : ", log.LstdFlags) - - // DLog Debug level log - DLog = log.New(os.Stdout, "[scoringmgr] DEBUG : ", log.LstdFlags) -) diff --git a/src/scoringmgr/handlers.go b/src/scoringmgr/handlers.go index eddeada..9380b71 100755 --- a/src/scoringmgr/handlers.go +++ b/src/scoringmgr/handlers.go @@ -6,10 +6,11 @@ package scoringmgr #cgo LDFLAGS: -ldl */ import "C" -import "unsafe" - import ( + "fmt" + "log" "time" + "unsafe" confdescription "configuremgr/description" ) @@ -67,7 +68,7 @@ func Init() *Handlers { // PushLibPath is that pushing library path to channel // @TODO : async notify lib loading func PushLibPath(libPath string, doc *confdescription.Doc, handlersCh chan<- interface{}) (err error) { - ILog.Printf("input PushLibPath : %s", libPath) + log.Printf("[scoringmgr] input PushLibPath : %s", libPath) handlersCh <- pair{libPath, doc} return nil } @@ -77,12 +78,12 @@ func (handlers *Handlers) Listening() { go func() { - ILog.Println("listening started") + log.Println("[scoringmgr] listening started") for { select { case obj := <-handlers.Ch: - ILog.Printf("input handlers.Ch from configuremgr") + log.Printf("[scoringmgr] input handlers.Ch from configuremgr") handlers.makeHandler(obj.(pair)).runScoring() } //select end @@ -105,7 +106,7 @@ func (handlers *Handlers) RemoveLib(libName string) { //Close dynamic loader defer C.dlclose(unsafe.Pointer(handler.dl)) - ILog.Printf("RemoveLib : %s\n", libName) + log.Printf("[scoringmgr] RemoveLib : %s\n", libName) } func (handlers *Handlers) makeHandler(pairObj pair) (handlerObj *Handler) { @@ -127,7 +128,7 @@ func (handlers *Handlers) makeHandler(pairObj pair) (handlerObj *Handler) { func (handler *Handler) runScoring() { - ILog.Println("Run scoring") + log.Println("[scoringmgr] Run scoring") go func() { @@ -136,7 +137,7 @@ func (handler *Handler) runScoring() { case status := <-handler.statusSignal: handler.process(status) case <-handler.endSignal: - ILog.Println("consumer signal go routine die") + log.Println("[scoringmgr] consumer signal go routine die") return } } @@ -150,12 +151,12 @@ func (handler *Handler) runScoring() { select { case <-handler.endSignal: - ILog.Println("producer signal go routine die") + log.Println("[scoringmgr] producer signal go routine die") return default: handler.statusSignal <- constLibStatusRun time.Sleep(time.Duration(1000) * time.Millisecond) - ILog.Printf("status run sleep time : %d\n", handler.intervalMs) + fmt.Printf("[scoringmgr] status run sleep time : %d\n", handler.intervalMs) } } @@ -169,11 +170,11 @@ func (handler *Handler) process(status int) { switch status { case constLibStatusInit: - ILog.Printf("init\n") + log.Printf("[scoringmgr] init\n") handler.init() break case constLibStatusRun: - ILog.Printf("run\n") + fmt.Printf("[scoringmgr] run\n") handler.running() break } @@ -192,19 +193,19 @@ func (handler *Handler) init() { handler.dl = uintptr(dl) if err != nil { - ELog.Fatal("dlopen error occured") + log.Fatal("[scoringmgr] dlopen error occured") } symbolPtr, symbolErr := C.dlsym(dl, sym) if symbolErr != nil { - ELog.Fatal("symbol error occured") + log.Fatal("[scoringmgr] symbol error occured") } handler.symbol = uintptr(symbolPtr) - ILog.Printf("functionName : %s\n", handler.functionName) - ILog.Printf("libPath : %s\n", handler.libPath) - ILog.Printf("symbol : %#08X\n", handler.symbol) + log.Printf("[scoringmgr] functionName : %s\n", handler.functionName) + log.Printf("[scoringmgr] libPath : %s\n", handler.libPath) + log.Printf("[scoringmgr] symbol : %#08X\n", handler.symbol) return } diff --git a/src/scoringmgr/lib_scoring_interface.go b/src/scoringmgr/lib_scoring_interface.go old mode 100644 new mode 100755 index 306ec35..886b846 --- a/src/scoringmgr/lib_scoring_interface.go +++ b/src/scoringmgr/lib_scoring_interface.go @@ -4,13 +4,16 @@ package scoringmgr #include "resourceservice/resourceservice.c" */ import "C" -import "unsafe" +import ( + "fmt" + "unsafe" +) // LoadScoringGeneralInterface function func LoadScoringGeneralInterface(symbol uintptr) float64 { ret := C.wrap_myscoring(unsafe.Pointer(symbol)) - ILog.Println(ret) + fmt.Println("[scoringmgr]", ret) return float64(ret) @@ -25,4 +28,4 @@ func StopResourceService() { C.stopResourceService() } -//$ touch resourceservice/resourceservice.c \ No newline at end of file +//$ touch resourceservice/resourceservice.c diff --git a/src/scoringmgr/mock/mock_lib_add.go b/src/scoringmgr/mock/mock_lib_add.go index 40e6034..b6ef040 100755 --- a/src/scoringmgr/mock/mock_lib_add.go +++ b/src/scoringmgr/mock/mock_lib_add.go @@ -7,27 +7,25 @@ wrap_add(void *f, int a, int b){ } */ import "C" -import "unsafe" - import ( - scoringmgr "scoringmgr" + "log" + "unsafe" ) // LoadScoringInterfaceAdd function func LoadScoringInterfaceAdd(symbol uintptr) float64 { ret := C.wrap_add(unsafe.Pointer(symbol), 2, 3) - scoringmgr.ILog.Println(ret) + log.Println(ret) return float64(ret) } - func StartResourceServiceAdd() { - scoringmgr.ILog.Println("startResourceService of add library not meaning") + log.Println("[mockscoringmgr] startResourceService of add library not meaning") } func StopResourceServiceAdd() { - scoringmgr.ILog.Println("stopResourceService of add library not meaning") + log.Println("[mockscoringmgr] stopResourceService of add library not meaning") } diff --git a/src/scoringmgr/score.go b/src/scoringmgr/score.go index ea6e4d3..fceefc7 100755 --- a/src/scoringmgr/score.go +++ b/src/scoringmgr/score.go @@ -24,7 +24,7 @@ func GetScore(target string, name string) (scoreValue float64, err error) { scoreValue, err = getScoreRemoteEnv(target, name) } - DLog.Println("scoreValue", scoreValue) + log.Println("[scoringmgr] scoreValue", scoreValue) return } @@ -63,7 +63,7 @@ func getScoreRemoteEnv(target string, name string) (scoreValue float64, err erro func checkError(err error) bool { if err != nil { - ELog.Println(err.Error()) + log.Println(err.Error()) return true } return false diff --git a/src/scoringmgr/scoringmgr_test.go b/src/scoringmgr/scoringmgr_test.go index a37bc53..9da5edd 100755 --- a/src/scoringmgr/scoringmgr_test.go +++ b/src/scoringmgr/scoringmgr_test.go @@ -5,6 +5,7 @@ package scoringmgr_test import ( "context" "fmt" + "log" "net/http" "testing" "time" @@ -40,13 +41,13 @@ func TestBasicMockScoringMgrMySumLib(t *testing.T) { confPath := fmt.Sprintf("mock/%s/%s.conf", libName, libName) cfg := new(confdescription.Doc) sconf.Must(cfg).Read(ini.File(confPath)) - scoringmgr.ILog.Println(cfg) + log.Println(cfg) scoringmgr.PushLibPath(libPath, cfg, iscoringmgr.Ch) //working on time.Sleep(time.Duration(3) * time.Second) scoreValue, _ := iscoringmgr.IGetScore("mock", "mock") - scoringmgr.DLog.Printf("scorevalue : %f\n", scoreValue) + log.Printf("scorevalue : %f\n", scoreValue) //release iscoringmgr.IStopResourceService() @@ -76,13 +77,13 @@ func TestBasicMockScoringMgrMySumLibGetScoreLocal(t *testing.T) { confPath := fmt.Sprintf("mock/%s/%s.conf", libName, libName) cfg := new(confdescription.Doc) sconf.Must(cfg).Read(ini.File(confPath)) - scoringmgr.ILog.Println(cfg) + log.Println(cfg) scoringmgr.PushLibPath(libPath, cfg, iscoringmgr.Ch) //working on time.Sleep(time.Duration(3) * time.Second) scoreValue, _ := iscoringmgr.IGetScore("localhost", "mysum") - scoringmgr.DLog.Printf("scorevalue : %f\n", scoreValue) + log.Printf("scorevalue : %f\n", scoreValue) //release iscoringmgr.IStopResourceService() @@ -115,13 +116,13 @@ func TestBasicMockScoringMgrMySumLibGetScoreRemote(t *testing.T) { confPath := fmt.Sprintf("mock/%s/%s.conf", libName, libName) cfg := new(confdescription.Doc) sconf.Must(cfg).Read(ini.File(confPath)) - scoringmgr.ILog.Println(cfg) + log.Println(cfg) scoringmgr.PushLibPath(libPath, cfg, iscoringmgr.Ch) time.Sleep(time.Duration(3) * time.Second) //working on scoreValue, _ := iscoringmgr.IGetScore("127.0.0.1", "mysum") - scoringmgr.DLog.Printf("scorevalue : %f\n", scoreValue) + log.Printf("scorevalue : %f\n", scoreValue) time.Sleep(time.Duration(1) * time.Second) //release @@ -155,13 +156,13 @@ func TestScoringMgrMyScoringLib(t *testing.T) { confPath := fmt.Sprintf("mock/%s/%s.conf", libName, libName) cfg := new(confdescription.Doc) sconf.Must(cfg).Read(ini.File(confPath)) - scoringmgr.ILog.Println(cfg) + log.Println(cfg) scoringmgr.PushLibPath(libPath, cfg, iscoringmgr.Ch) //working on time.Sleep(time.Duration(3) * time.Second) scoreValue, _ := iscoringmgr.IGetScore("mock", "mock") - scoringmgr.DLog.Printf("scorevalue : %f\n", scoreValue) + log.Printf("scorevalue : %f\n", scoreValue) //release iscoringmgr.IStopResourceService() @@ -191,13 +192,13 @@ func TestScoringMgrMyScoringLibGetScoreLocal(t *testing.T) { confPath := fmt.Sprintf("mock/%s/%s.conf", libName, libName) cfg := new(confdescription.Doc) sconf.Must(cfg).Read(ini.File(confPath)) - scoringmgr.ILog.Println(cfg) + log.Println(cfg) scoringmgr.PushLibPath(libPath, cfg, iscoringmgr.Ch) //working on time.Sleep(time.Duration(3) * time.Second) scoreValue, _ := iscoringmgr.IGetScore("localhost", "myscoring") - scoringmgr.DLog.Printf("scorevalue : %f\n", scoreValue) + log.Printf("scorevalue : %f\n", scoreValue) //release iscoringmgr.IStopResourceService() @@ -232,13 +233,13 @@ func TestScoringMgrMyScoringLibGetScoreRemote(t *testing.T) { confPath := fmt.Sprintf("mock/%s/%s.conf", libName, libName) cfg := new(confdescription.Doc) sconf.Must(cfg).Read(ini.File(confPath)) - scoringmgr.ILog.Println(cfg) + log.Println(cfg) scoringmgr.PushLibPath(libPath, cfg, iscoringmgr.Ch) //working on time.Sleep(time.Duration(3) * time.Second) scoreValue, _ := iscoringmgr.IGetScore("127.0.0.1", "myscoring") - scoringmgr.DLog.Printf("scorevalue : %f\n", scoreValue) + log.Printf("scorevalue : %f\n", scoreValue) //release iscoringmgr.IStopResourceService() diff --git a/src/securemgr/cipher.go b/src/securemgr/cipher.go index 1af9149..491aeae 100755 --- a/src/securemgr/cipher.go +++ b/src/securemgr/cipher.go @@ -34,19 +34,16 @@ func EncryptByte(byteData []byte) (encryptedByte []byte, err error) { block, err := aes.NewCipher(createHashByte(passphrase)) // AES 대칭키 암호화 블록 생성 if err != nil { - log.Println(err) return } gcm, err := cipher.NewGCM(block) if err != nil { - log.Println(err) return } nonce := make([]byte, gcm.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { - log.Println(err) return } @@ -58,12 +55,10 @@ func EncryptByte(byteData []byte) (encryptedByte []byte, err error) { func EncrptJsonToByte(jsonMap map[string]interface{}) (encryptedByte []byte, err error) { jsonByte, err := json.Marshal(jsonMap) if err != nil { - log.Println("json.Mmarshal failed !!", err) return } encryptedByte, err = EncryptByte(jsonByte) if err != nil { - log.Println("data encryption failed !!") return } return @@ -77,7 +72,6 @@ func DecryptByte(byteData []byte) (decryptedByte []byte, err error) { block, err := aes.NewCipher(createHashByte(passphrase)) if err != nil { - log.Println(err) return } @@ -99,13 +93,11 @@ func DecryptByte(byteData []byte) (decryptedByte []byte, err error) { func DecryptByteToJson(data []byte) (jsonMap map[string]interface{}, err error) { decrpytedByte, err := DecryptByte(data) if err != nil { - log.Println("data dncryption failed !!", err) return } err = json.Unmarshal(decrpytedByte, &jsonMap) if err != nil { - log.Println("json.Unmarshal failed !!", err) return } return diff --git a/src/securemgr/cipher_test.go b/src/securemgr/cipher_test.go new file mode 100755 index 0000000..3cf9013 --- /dev/null +++ b/src/securemgr/cipher_test.go @@ -0,0 +1,151 @@ +package securemgr + +import ( + "encoding/json" + "log" + "strings" + "testing" +) + +const ( + // Resource mgr URI + ConstDeviceResourceUsageCPUGet = "/api/v1/device/resource/usage/cpu" + ConstDeviceResourceUsageDiskGet = "/api/v1/device/resource/usage/disk" + ConstDeviceResourceUsageMemoryGet = "/api/v1/device/resource/usage/memory" + ConstDeviceResourceUsageNetworkGet = "/api/v1/device/resource/usage/network" + + // discovery mgr URI + ConstDiscoverymgrDevicesGet = "/api/v1/discoverymgr/devices" + + // Service mgr URI + ConstServicemgrServices = "/api/v1/servicemgr/services" + ConstServicemgrServicesNoti = "/api/v1/servicemgr/services/notification/" + + // Scoring mgr URI + ConstScoremgrScore = "/api/v1/scoringmgr/score" + + ConstAppName = "AppName" + ConstServiceName = "ls" +) + +var keyFilePath string = "./test/key.txt" + +func Test_Init(t *testing.T) { + err := Init(keyFilePath) + retError(t, err) + + err = Init("") + if err == nil { + t.Error("Error to handle wrong key file") + } +} + +func Test_EncryptDecryptByte(t *testing.T) { + data := []byte("I love you !!") + encryptedByte, err := EncryptByte(data) + + retError(t, err) + if len(encryptedByte) == 0 { + t.Error(err.Error()) + } else { + log.Println(encryptedByte) + } + + decryptedByte, err := DecryptByte(encryptedByte) + + retError(t, err) + if len(decryptedByte) == 0 { + t.Error(err.Error()) + } else { + log.Println(decryptedByte) + } + + assertEqualByteSlice(t, data, decryptedByte) + + var nulByte []byte = nil + encryptedNulByte, err := EncryptByte(nulByte) + if err == nil || len(encryptedNulByte) != 0 { + t.Error(encryptedNulByte) + } + + decryptedNulByte, err := DecryptByte(nulByte) + if err == nil || len(encryptedNulByte) != 0 { + t.Error(decryptedNulByte) + } + +} + +func Test_EncryptDecryptByteJsonMap(t *testing.T) { + + doc := `{"member":7,"project":"edge-orchestration"}` + + var jsonMap map[string]interface{} + + json.Unmarshal([]byte(doc), &jsonMap) + + encryptedByte, err := EncrptJsonToByte(jsonMap) + retError(t, err) + if len(encryptedByte) == 0 { + t.Error(err.Error()) + } else { + log.Println(encryptedByte) + } + + decryptedJsonMap, err := DecryptByteToJson(encryptedByte) + jsonByte, err := json.Marshal(decryptedJsonMap) + + retError(t, err) + if len(jsonByte) == 0 { + t.Error(err.Error()) + } else { + log.Println(jsonByte) + } + + assertEqualStr(t, doc, string(jsonByte)) + + var nulByte []byte = nil + encryptedNulByte, err := EncryptByte(nulByte) + if err == nil || len(encryptedNulByte) != 0 { + t.Error(encryptedNulByte) + } + + decryptedNulByte, err := DecryptByte(nulByte) + if err == nil || len(encryptedNulByte) != 0 { + t.Error(decryptedNulByte) + } +} + +func Test_createHash(t *testing.T) { + data := []byte("I love you !!") + hashStr := createHash(string(data)) + hashByte := createHashByte(data) + + assertEqualByteSlice(t, hashByte, hashStr) +} + +func assertEqualByteSlice(t *testing.T, a, b []byte) { + t.Helper() + if len(a) != len(b) { + t.Error("byte array not equal", a, b) + } + for i, v := range a { + if v != b[i] { + t.Error("byte array not equal", a, b) + } + } +} + +func assertEqualStr(t *testing.T, a, b string) { + t.Helper() + if strings.Compare(a, b) != 0 { + t.Errorf("%s != %s", a, b) + } +} + +func retError(t *testing.T, err error) { + t.Helper() + + if err != nil { + t.Error(err.Error()) + } +} -- 2.7.4