+++ /dev/null
-[main]\r
-url=http://localhost/
\ No newline at end of file
+++ /dev/null
-package main
-
-import (
- "fmt"
- "strings"
-)
-
-func main() {
- getdirname("/tmp/foo/mysum")
- getdirname("/tmp/foo/mysum/")
-}
-
-func getdirname(path string) {
-
- idx := strings.LastIndex(path, "/")
- if idx == len(path)-1 {
- path = path[:len(path)-1]
- }
-
- dirname := path[strings.LastIndex(path, "/")+1:]
-
- libPath := path + "/" + "lib" + dirname + ".so"
- confPath := path + "/" + dirname + ".conf"
-
- fmt.Println("libPath : " + libPath)
- fmt.Println("confPath : " + confPath)
-
-}
+++ /dev/null
-package main
-
-import (
- "fmt"
- "gopkg.in/sconf/ini.v0"
- "gopkg.in/sconf/sconf.v0"
-)
-
-func main() {
- Example()
-}
-
-func Example() {
- var cfg = struct {
- Main struct {
- Url string
- }
- }{}
- sconf.Must(&cfg).Read(ini.File("./src/configuremgr/incubator/example.ini"))
- fmt.Println(cfg.Main.Url)
- // Output: http://localhost/
-}
+++ /dev/null
-package main
-
-import (
- "fmt"
-
- "gopkg.in/sconf/ini.v0"
- "gopkg.in/sconf/sconf.v0"
-)
-
-func main() {
- Example()
-}
-
-type doc struct {
- Version struct {
- ConfVersion string
- }
- ServiceInfo struct {
- ServiceName string
- ExecFilePath string
- }
- ScoringMethod struct {
- LibFile string
- FuncName string
- }
- ResourceType struct {
- IntervalTimeMs int
- MaxCount int
- }
-}
-
-func Example() {
- var cfg = new(doc)
- sconf.Must(cfg).Read(ini.File("./src/configuremgr/incubator/simple.ini"))
- // fmt.Println(cfg.Version.ConfVersion)
- fmt.Println(cfg)
-
- // Output: http://localhost/
-}
+++ /dev/null
-# Description of service that will be requested\r
-[Version]\r
-ConfVersion=v0.0 ; Version of Configuration file\r
-\r
-[ServiceInfo]\r
-ServiceName={service_name} ; Name of distributed service\r
-ExecFilePath=/path/to/execute/file ; Exec file path\r
-\r
-[ScoringMethod]\r
-LibFile={scoringMethod}.so ; Library file name\r
-FuncName=add\r
-\r
-[ResourceType]\r
-IntervalTimeMs=1000 ; Interval time of get resource\r
-MaxCount=10 ; Number of times\r
+++ /dev/null
-package main
-
-import (
- "github.com/fsnotify/fsnotify"
- "log"
-)
-
-func main() {
-
- watcher, err := fsnotify.NewWatcher()
- if err != nil {
- log.Fatal(err)
- }
- defer watcher.Close()
-
- done := make(chan bool)
- go func() {
- for {
- select {
- case event, ok := <-watcher.Events:
- log.Println("log event:", event)
-
- if !ok {
- return
- }
- if event.Op&fsnotify.Create == fsnotify.Create {
- log.Println("Created " + event.Name)
- }
- case err, ok := <-watcher.Errors:
- if !ok {
- return
- }
- log.Println("error:", err)
- // default:
- // fmt.Println("default")
- }
- }
- }()
-
- err = watcher.Add("/tmp/foo")
- if err != nil {
- log.Fatal(err)
- }
- <-done
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright 2019 Samsung Electronics All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *******************************************************************************/
-
-/*
- * Edge Orchestration
- *
- * Edge Orchestration support to deliver distributed service process environment.
- *
- * API version: v1-20190307
- * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
- */
-
-package devicemgr
-
-import (
- "log"
-)
-
-// InitDeviceMgr function
-func InitDeviceMgr() {
- log.Printf("[%s] InitDeviceMgr", logPrefix)
-
- // start go routines for sampling H/W resource
- go samplingProcStat(30)
- go samplingNetworkUsage()
- go samplingDiskUsage()
-}
-
-// GetGeneralUsageCPU function
-func GetGeneralUsageCPU() float64 {
- return getUsageCPU()
-}
-
-// GetUsageMemory function
-func GetUsageMemory() float64 {
- return getUsageMemory()
-}
-
-// GetUsageNetwork function
-func GetUsageNetwork() float64 {
- return getUsageNetwork()
-}
-
-// GetUsageDisk function
-func GetUsageDisk() float64 {
- return getUsageDisk()
-}
+++ /dev/null
-/*******************************************************************************
- * Copyright 2019 Samsung Electronics All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *******************************************************************************/
-
-/*
- * Edge Orchestration
- *
- * Edge Orchestration support to deliver distributed service process environment.
- *
- * API version: v1-20190307
- * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
- */
-
-package devicemgr
-
-import (
- "fmt"
- "io/ioutil"
- "strconv"
- "strings"
- "time"
-)
-
-type argError struct {
- prob string
-}
-
-func (e *argError) Error() string {
- return fmt.Sprintf("%s", e.prob)
-}
-
-//================================ CPU Usage ================================
-
-/*
-
-
- $ cat /proc/stat
- cpu 542368 14095 166906 800666582 273644 0 4972 0 0 0
- cpu0 129538 944 19348 100063536 7308 0 762 0 0 0
- cpu1 66523 1265 20022 100123890 9679 0 674 0 0 0
- cpu2 43494 874 19086 100153938 4139 0 391 0 0 0
- cpu3 101144 804 20314 100088439 11625 0 124 0 0 0
- cpu4 47182 2101 18928 100145633 6619 0 141 0 0 0
- cpu5 45282 1470 19422 100089955 6198 0 118 0 0 0
- cpu6 60139 4839 21580 99909671 218700 0 302 0 0 0
- cpu7 49062 1796 28203 100091517 9373 0 2458 0 0 0
-
-
-
- http://www.linuxhowtos.org/System/procstat.htm
- cpu num user nice-user system idle iowait irq softirq
- cpu 8975 0 14722 24534211 1294 0 530
-
- cpuUsage = (all of processor jiffies - all of processor idle jiffies) / (all of processor jiffies)
-
- cpuUsage = cpu0(100%) / (cpu0(100%) + ... + cpu7(0%)) = 12.5%
-
-*/
-
-func procStat() (idle, total uint64) {
- contents, _ := ioutil.ReadFile("/proc/stat")
-
- //parsing 'cpu' line
- lines := strings.Split(string(contents), "\n")
-
- for _, line := range lines {
- fields := strings.Fields(line)
-
- if fields[0] == "cpu" {
-
- numFields := len(fields)
-
- for i := 1; i < numFields; i++ {
- val, _ := strconv.ParseUint(fields[i], 10, 64)
-
- if i == 4 {
- idle = val
- }
-
- total += val
- }
-
- return
- }
- }
-
- return
-}
-
-var prevIdle uint64
-var prevTotal uint64
-var cpuUsage float64
-
-func samplingProcStat(frame uint64) {
-
- prevIdle, prevTotal = procStat()
-
- for true {
-
- time.Sleep(time.Duration(60/frame) * time.Second)
-
- nextIdle, nextTotal := procStat()
-
- idleTicks := float64(nextIdle - prevIdle)
- totalTicks := float64(nextTotal - prevTotal)
-
- cpuUsage = 100 * (totalTicks - idleTicks) / totalTicks
-
- fmt.Println("cpu jiffies: ", prevIdle, nextIdle, prevTotal, nextTotal, idleTicks, totalTicks)
- fmt.Println("cpu usage: ", cpuUsage)
-
- prevIdle = nextIdle
- prevTotal = nextTotal
- }
-}
-
-func getUsageCPU() float64 {
-
- return cpuUsage
-}
-
-func getIdleCPU() {
-
-}
-
-func getUserUsageCPU() {
-
-}
-
-func getNiceUserUsageCPU() {
-
-}
-
-func getSystemUsageCPU() {
-
-}
-
-func getIOwaitUsageCPU() {
-
-}
-
-func getIrqUsageCPU() {
-
-}
-
-func getSoftIrqUsageCPU() {
-
-}
-
-//================================ CPU Usage ================================
-
-//================================ MEM Usage ================================
-
-func getUsageMemory() float64 {
-
- contents, _ := ioutil.ReadFile("/proc/meminfo")
-
- //parsing 'cpu' line
- lines := strings.Split(string(contents), "\n")
-
- var memAvailable uint64
- var memTotal uint64
-
- var memUsage float64
-
- for _, line := range lines {
-
- // fmt.Println(line)
-
- fields := strings.Fields(line)
-
- numFields := len(fields)
-
- // fmt.Println(numFields)
-
- if numFields == 3 {
- // https://superuser.com/questions/980820/what-is-the-difference-between-memfree-and-memavailable-in-proc-meminfo
- if fields[0] == "MemAvailable:" {
- memAvailable, _ = strconv.ParseUint(fields[1], 10, 64)
- } else if fields[0] == "MemTotal:" {
- memTotal, _ = strconv.ParseUint(fields[1], 10, 64)
- }
-
- // fmt.Println(fields[0], "--", fields[1], "--", fields[2])
-
- } else if numFields == 2 {
-
- }
-
- }
-
- memUsage = 100 * float64(memTotal-memAvailable) / float64(memTotal)
- fmt.Println("mem: ", memUsage)
-
- return memUsage
-}
-
-//================================ MEM Usage ================================
-
-//================================ NET Usage ================================
-
-func getNetworkMBps() (recvTotal, tranTotal uint64) {
-
- recvTotal = 0
- tranTotal = 0
-
- contents, _ := ioutil.ReadFile("/proc/net/dev")
-
- lines := strings.Split(string(contents), "\n")
-
- for lineNum, line := range lines {
-
- // fmt.Println(line)
- // fmt.Println(lineNum)
-
- fields := strings.Fields(line)
-
- numFields := len(fields)
-
- if lineNum >= 2 && numFields == 17 {
- // fmt.Println(fields[1], "#", fields[9])
-
- recvVal, _ := strconv.ParseUint(fields[1], 10, 64)
- recvTotal += recvVal
-
- tranVal, _ := strconv.ParseUint(fields[9], 10, 64)
- tranTotal += tranVal
- }
- }
-
- return
-}
-
-var networkMBps float64
-
-func samplingNetworkUsage() {
-
- var prevRecv uint64
- var prevTran uint64
-
- var nextRecv uint64
- var nextTran uint64
-
- prevRecv, prevTran = getNetworkMBps()
-
- for true {
-
- time.Sleep(1 * time.Second)
-
- nextRecv, nextTran = getNetworkMBps()
-
- diffRecv := float64(nextRecv - prevRecv)
- diffTran := float64(nextTran - prevTran)
-
- networkMBps = (diffRecv + diffTran) / 1024 / 1024
-
- fmt.Println("net : ", networkMBps)
-
- prevRecv = nextRecv
- prevTran = nextTran
-
- }
-
-}
-
-func getUsageNetwork() float64 {
- return networkMBps
-}
-
-//================================ NET Usage ================================
-
-//================================ DISK Usage ================================
-
-func getDiskByteIO() (readingByteTotal, writingByteTotal uint64) {
-
- readingByteTotal = 0
- writingByteTotal = 0
-
- contents, _ := ioutil.ReadFile("/proc/diskstats")
-
- lines := strings.Split(string(contents), "\n")
-
- for _, line := range lines {
-
- // fmt.Println(line)
- // fmt.Println(lineNum)
-
- fields := strings.Fields(line)
-
- numFields := len(fields)
-
- if numFields < 14 {
- continue
- }
-
- name := fields[2]
-
- //exception 1
- if strings.Contains(name, "loop") {
- continue
- }
-
- //exception 2
- if strings.Contains(name, "ram") {
- continue
- }
-
- //exception 3
- if strings.Contains(name, "sr") {
- continue
- }
-
- // majorSector, _ := strconv.ParseUint(fields[0], 10, 64)
- minorSector, _ := strconv.ParseUint(fields[1], 10, 64)
-
- if minorSector == 0 {
-
- readSector, _ := strconv.ParseUint(fields[5], 10, 64)
- writeSector, _ := strconv.ParseUint(fields[9], 10, 64)
-
- sysFileForSector := fmt.Sprintf("/sys/block/%s/queue/hw_sector_size", name)
-
- sectorSizeContent, _ := ioutil.ReadFile(sysFileForSector)
- sectorSizeLines := strings.Split(string(sectorSizeContent), "\n")
-
- sectorSize, _ := strconv.ParseUint(sectorSizeLines[0], 10, 64)
-
- readingByteTotal += readSector * sectorSize
- writingByteTotal += writeSector * sectorSize
-
- }
-
- }
-
- return
-}
-
-var diskMBps float64
-
-func samplingDiskUsage() {
-
- var prevWriting uint64
- var prevReading uint64
-
- var nextWriting uint64
- var nextReading uint64
-
- prevWriting, prevReading = getDiskByteIO()
-
- for true {
-
- time.Sleep(1 * time.Second)
-
- nextWriting, nextReading = getDiskByteIO()
-
- diffWriting := float64(nextWriting - prevWriting)
- diffReading := float64(nextReading - prevReading)
-
- prevWriting = nextWriting
- prevReading = nextReading
-
- diskMBps = (diffWriting + diffReading) / 1024 / 1024
-
- fmt.Println("disk : ", diskMBps)
-
- }
-
- return
-}
-
-func getUsageDisk() float64 {
- return diskMBps
-}
-
-//================================ DISK Usage ================================
+++ /dev/null
-/*******************************************************************************
- * Copyright 2019 Samsung Electronics All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *******************************************************************************/
-package devicemgr
-
-var logPrefix = "devicemgr"
"net/http"
"os/exec"
"restapi/httpclient"
- "strconv"
"github.com/gorilla/mux"
- "devicemgr"
"discoverymgr"
"scoringmgr"
"securemgr"
"servicemgr"
)
-// APIV1DeviceResourceUsageCPUGet function
-func APIV1DeviceResourceUsageCPUGet(w http.ResponseWriter, r *http.Request) {
- log.Printf("[%s] APIV1DeviceResourceUsageCPUGet", logPrefix)
-
- usage := devicemgr.GetGeneralUsageCPU()
- data, _ := json.Marshal(CPUObject{CPUUsage: usage})
- writeJSONResponse(w, data, http.StatusOK)
-}
-
-// APIV1DeviceResourceUsageDiskGet fucntion
-func APIV1DeviceResourceUsageDiskGet(w http.ResponseWriter, r *http.Request) {
- log.Printf("[%s] APIV1DeviceResourceUsageDiskGet", logPrefix)
-
- usage := devicemgr.GetUsageDisk()
- data, _ := json.Marshal(DiskObject{DiskUsage: usage})
- writeJSONResponse(w, data, http.StatusOK)
-}
-
-// APIV1DeviceResourceUsageMemoryGet function
-func APIV1DeviceResourceUsageMemoryGet(w http.ResponseWriter, r *http.Request) {
- log.Printf("[%s] APIV1DeviceResourceUsageMemoryGet", logPrefix)
-
- usage := devicemgr.GetUsageMemory()
- data, _ := json.Marshal(MemoryObject{MemoryUsage: usage})
- writeJSONResponse(w, data, http.StatusOK)
-}
-
-// APIV1DeviceResourceUsageNetworkGet function
-func APIV1DeviceResourceUsageNetworkGet(w http.ResponseWriter, r *http.Request) {
- log.Printf("[%s] APIV1DeviceResourceUsageNetworkGet", logPrefix)
-
- usage := devicemgr.GetUsageNetwork()
- data, _ := json.Marshal(NetworkObject{NetworkUsage: usage})
- writeJSONResponse(w, data, http.StatusOK)
-}
-
// APIV1DiscoverymgrDevicesGet function
func APIV1DiscoverymgrDevicesGet(w http.ResponseWriter, r *http.Request) {
log.Printf("[%s] APIV1DiscoverymgrDevicesGet", logPrefix)
return
}
- distService["NotificationTargetURL"] = remoteAddr + ":" + strconv.Itoa(56001)
+ distService["NotificationTargetURL"] = remoteAddr
return
}
* limitations under the License.
*
*******************************************************************************/
+
package v1
import (
"strings"
"testing"
- "devicemgr"
"discoverymgr"
"restapi/httpclient"
"scoringmgr"
)
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
ConstDiscoverymgrDevices = "/api/v1/discoverymgr/devices"
ConstDiscoverymgrDevicesTXT = "/api/v1/discoverymgr/devices/TXT"
}
func init() {
- devicemgr.InitDeviceMgr()
servicemgr.Init()
discoverymgr.InitDiscovery()
scoringmgr.Init()
log.Println("testURL:", testURL)
}
-func TestAPIV1DeviceResourceUsageCPUGet(t *testing.T) {
- targetURI := ConstDeviceResourceUsageCPUGet
- testGet(t, targetURI, http.StatusOK)
-}
-
-func TestAPIV1DeviceResourceUsageDiskGet(t *testing.T) {
- targetURI := ConstDeviceResourceUsageDiskGet
- testGet(t, targetURI, http.StatusOK)
-}
-
-func TestAPIV1DeviceResourceUsageMemoryGet(t *testing.T) {
- targetURI := ConstDeviceResourceUsageMemoryGet
- testGet(t, targetURI, http.StatusOK)
-}
-
-func TestAPIV1DeviceResourceUsageNetworkGet(t *testing.T) {
- targetURI := ConstDeviceResourceUsageNetworkGet
- testGet(t, targetURI, http.StatusOK)
-}
-
func TestAPIV1DiscoverymgrDevicesGet(t *testing.T) {
targetURI := ConstDiscoverymgrDevices
testGet(t, targetURI, http.StatusOK)
Index,
},
- Route{
- "APIV1DeviceResourceUsageCPUGet",
- strings.ToUpper("Get"),
- "/api/v1/device/resource/usage/cpu",
- APIV1DeviceResourceUsageCPUGet,
- },
-
- Route{
- "APIV1DeviceResourceUsageDiskGet",
- strings.ToUpper("Get"),
- "/api/v1/device/resource/usage/disk",
- APIV1DeviceResourceUsageDiskGet,
- },
-
- Route{
- "APIV1DeviceResourceUsageMemoryGet",
- strings.ToUpper("Get"),
- "/api/v1/device/resource/usage/memory",
- APIV1DeviceResourceUsageMemoryGet,
- },
-
- Route{
- "APIV1DeviceResourceUsageNetworkGet",
- strings.ToUpper("Get"),
- "/api/v1/device/resource/usage/network",
- APIV1DeviceResourceUsageNetworkGet,
- },
-
Route{
"APIV1DiscoverymgrDevicesGet",
strings.ToUpper("Get"),
* limitations under the License.
*
*******************************************************************************/
+
package v1
var logPrefix = "restapi/v1"
+++ /dev/null
-package main\r
-\r
-import (\r
- "fmt"\r
-)\r
-\r
-func getPrime(rangeNum uint64){\r
-\r
- var targetNum uint64\r
- var isPrime bool\r
- var n uint64\r
- var count uint32\r
-\r
- targetNum = 2\r
- isPrime = true\r
- count = 0\r
-\r
- for targetNum <= rangeNum {\r
- \r
- isPrime = true\r
-\r
- for n = 2 ; n < targetNum ; n++ {\r
-\r
- if targetNum % n == 0 {\r
- isPrime = false\r
- break;\r
- }\r
- }\r
-\r
- if isPrime {\r
- fmt.Print(targetNum, " ")\r
- count++\r
- }\r
- \r
- targetNum += 1\r
- }\r
-\r
- fmt.Println("count : ", count)\r
-\r
-}\r
-\r
-func main(){\r
-\r
- getPrime(100000000000)\r
-}
\ No newline at end of file
+++ /dev/null
-package main
-
-/*
-#include <stdlib.h>
-#include <dlfcn.h>
-#cgo LDFLAGS: -ldl
-
-int
-wrap_add(void *f, int a, int b){
- return ((int (*)(int a, int b))f)(a,b);
-}
-*/
-import "C"
-import "unsafe"
-import "fmt"
-import "time"
-import "log"
-import "os"
-
-var ILog *log.Logger = log.New(os.Stdout, "[scoringmgr] INFO : ", log.LstdFlags)
-var ELog *log.Logger = log.New(os.Stdout, "[scoringmgr] ERROR : ", log.LstdFlags)
-var DLog *log.Logger = log.New(os.Stdout, "[scoringmgr] DEBUG : ", log.LstdFlags)
-
-func main() {
-
- // LoadScoringAdd("src/scoringmgr/mock/mysum/libmysum.so", 1000)
- go func() {
-
- symbol := Init()
- LoadScoringInterfaceAdd(symbol)
- }()
-
- for {
- }
-
-}
-
-func LoadScoringAdd(libPath string, intervalMs int) {
-
- go func() {
-
- sym := C.CString("add")
- defer C.free(unsafe.Pointer(sym))
-
- lib := C.CString(libPath)
-
- defer C.free(unsafe.Pointer(lib))
-
- handle, err := C.dlopen(lib, C.RTLD_LAZY)
- defer C.dlclose(handle)
-
- if err != nil {
- fmt.Println("dlopen error occured")
- }
-
- symbolPtr, symbolErr := C.dlsym(handle, sym)
- if symbolErr != nil {
- fmt.Println("dlsym error occured")
- }
-
- fmt.Printf("addSymbol is at %p\n", symbolPtr)
- fmt.Println(C.wrap_add(symbolPtr, 2, 3))
-
- for {
- fmt.Println(C.wrap_add(symbolPtr, 2, 3))
- time.Sleep(time.Duration(intervalMs) * time.Millisecond)
- }
- }()
-
- return
-}
-
-func Init() unsafe.Pointer {
-
- lib := C.CString("src/scoringmgr/mock/mysum/libmysum.so")
- defer C.free(unsafe.Pointer(lib))
-
- dl, err := C.dlopen(lib, C.RTLD_LAZY)
- //TODO : release dlclose
- // defer C.dlclose(dl)
-
- if err != nil {
- ELog.Fatal("dlopen error occured")
- }
-
- sym := C.CString("add")
- defer C.free(unsafe.Pointer(sym))
-
- symbol, symbolErr := C.dlsym(dl, sym)
- if symbolErr != nil {
- ELog.Fatal("symbol error occured")
- }
-
- return symbol
-}
-
-func LoadScoringInterfaceAdd(symbol unsafe.Pointer) {
-
- ILog.Println(C.wrap_add(symbol, 2, 3))
-
- return
-}
+++ /dev/null
-package main
-
-/*
-#include <stdlib.h>
-#include <dlfcn.h>
-#include "../resourceservice/resourceservice.c"
-#cgo LDFLAGS: -ldl -lpthread
-*/
-import "C"
-import "unsafe"
-import "log"
-import "os"
-import "time"
-
-var ILog *log.Logger = log.New(os.Stdout, "[scoringmgr] INFO : ", log.LstdFlags)
-var ELog *log.Logger = log.New(os.Stdout, "[scoringmgr] ERROR : ", log.LstdFlags)
-var DLog *log.Logger = log.New(os.Stdout, "[scoringmgr] DEBUG : ", log.LstdFlags)
-
-func main() {
- C.startResourceService()
-
- symbol := Init()
- for i := 0 ; i < 3 ; i++ {
- LoadScoringGeneralInterface(symbol)
- time.Sleep(time.Duration(1) * time.Second)
- }
-
- C.stopResourceService()
- time.Sleep(time.Duration(1) * time.Second)
-}
-
-func Init() unsafe.Pointer {
-
-
- lib := C.CString("src/scoringmgr/mock/myscoring/libmyscoring.so")
- defer C.free(unsafe.Pointer(lib))
-
- dl, err := C.dlopen(lib , C.RTLD_LAZY)
- //TODO : release dlclose
- // defer C.dlclose(dl)
-
- if err != nil {
- ELog.Fatal("dlopen error occured")
- }
-
-
- sym := C.CString("myscoring")
- defer C.free(unsafe.Pointer(sym))
-
- symbol, symbolErr := C.dlsym(dl, sym)
- if symbolErr != nil {
- ELog.Fatal("symbol error occured")
- }
-
- return symbol
-}
-
-func LoadScoringGeneralInterface(symbol unsafe.Pointer) {
- ILog.Printf("scorevalue : %f\n", C.wrap_myscoring(symbol))
-
- return
-}
+++ /dev/null
-package main
-
-import (
- "log"
-)
-
-type handler struct {
- handlerName string
- handlerPath string
-
- devicesScoreValue map[string]float64
- handle int
- interval int
- resourceCount int
-
- scoreValue int
-}
-
-type pair struct {
- a string
- b string
-}
-
-type Handlers struct {
- Table map[string]*handler
- ch chan pair
-}
-
-var handlers = Handlers{
- Table: make(map[string]*handler),
- ch: make(chan pair, 1024),
-}
-
-func main() {
-
- handlerObj := new(handler)
- handlerObj.handlerName = "HelloWorld"
- handlerObj.handlerPath = "/usr/local/lib/libhelloworld"
-
- handlers.Table["A"] = handlerObj
-
- log.Println(handlerObj)
-
- done := make(chan bool)
- go func() {
- handlers.ch <- pair{"A", "B"}
- }()
-
- go func() {
- pairObj := <-handlers.ch
- log.Println(pairObj)
- done <- true
- }()
-
- <-done
-}
+++ /dev/null
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-//network
-#include <sys/socket.h>
-#include <sys/ioctl.h>
-#include <netinet/in.h>
-#include <linux/sockios.h>
-#include <linux/ethtool.h>
-#include <net/if.h>
-
-//cpu
-#include <sys/sysinfo.h>
-
-#define SSTRNCMP(stream, name) strncmp(stream, name, strlen(name))
-#define NIC_NAME_LEN 64
-#define NIC_MAX_COUNT 32
-
-unsigned long networkPackets(char *ifNamePath)
-{
- FILE *fd;
- char buf[64];
- fd = fopen(ifNamePath, "r");
- fgets(buf, 64, fd);
- fclose(fd);
-
- unsigned long bytes;
- sscanf(buf, "%ld", &bytes);
-
- return bytes;
-}
-
-unsigned long networkTotalPackets(char **ifNamesPath, int count)
-{
- unsigned long totalBytes = 0;
-
- for (int i = 0; i < count; i++)
- {
-
- totalBytes += networkPackets(ifNamesPath[i]);
- }
-
- return totalBytes;
-}
-
-void makeIfNamesPath(char (*ifNames)[NIC_NAME_LEN], int count, char **ifNamesPath)
-{
- for (int i = 0; i < count; i++)
- {
- sprintf(ifNamesPath[i * 2], "/sys/class/net/%s/statistics/rx_bytes", ifNames[i]);
- sprintf(ifNamesPath[i * 2 + 1], "/sys/class/net/%s/statistics/tx_bytes", ifNames[i]);
-
- // printf("%s\n", ifNamesPath[i * 2]);
- // printf("%s\n", ifNamesPath[i * 2 + 1]);
- }
-}
-
-void getInterfaceAdapter(char ifnames[][NIC_NAME_LEN])
-{
- struct if_nameindex *if_nidxs, *intf;
-
- if_nidxs = if_nameindex();
- if (if_nidxs != NULL)
- {
- int i = 0;
- for (intf = if_nidxs; intf->if_index != 0 || intf->if_name != NULL; intf++, i++)
- {
- // printf("%s\n", intf->if_name);
- strcpy(ifnames[i], intf->if_name);
- }
-
- ifnames[i][0] = '\0';
- }
-}
-
-int filteringIfNames(char allIfNames[][NIC_NAME_LEN], char targetIfNames[][NIC_NAME_LEN])
-{
- int allIfNamesIter = 0;
- int targetIfNamesIter = 0;
-
- //iterator
- while (allIfNames[allIfNamesIter][0] != '\0')
- {
- if ((SSTRNCMP(allIfNames[allIfNamesIter], "eth") == 0) || (SSTRNCMP(allIfNames[allIfNamesIter], "enp") == 0) || (SSTRNCMP(allIfNames[allIfNamesIter], "wl") == 0))
- {
- printf("%s\n", allIfNames[allIfNamesIter]);
- strcpy(targetIfNames[targetIfNamesIter++], allIfNames[allIfNamesIter]);
- }
-
- allIfNamesIter++;
- }
-
- return targetIfNamesIter;
-}
-
-void sampingGetCpuUsage(double *cpuTotal, double *cpuIdle)
-{
-
- unsigned long cpuAttributes[10];
-
-#ifdef __linux__
- char stream[1024];
-
- FILE *file = fopen("/proc/stat", "r");
- fscanf(file, "cpu ");
- for (int i = 0; i < 10; i++)
- {
- fscanf(file, " %lu", &cpuAttributes[i]);
- // printf("aa : %lu\n", cpuAttributes[i]);
- }
- fclose(file);
-
- *cpuTotal = 0.0;
- for (int i = 0; i < 10; i++)
- {
- *cpuTotal += cpuAttributes[i];
- }
-
- *cpuIdle = cpuAttributes[3];
-
-#else
-#error "Not Support this architecture"
-#endif
-}
-
-//======================= PUBLIC API ===============================
-double getCpuUsage()
-{
- double cpuTotalPrev, cpuTotalNext;
- double cpuIdlePrev, cpuIdleNext;
-
- sampingGetCpuUsage(&cpuTotalPrev, &cpuIdlePrev);
- usleep(1000 * 1000);
- sampingGetCpuUsage(&cpuTotalNext, &cpuIdleNext);
-
- double totalTick;
- double idleTick;
-
- double cpuUsage;
-
- printf("%f %f\n", cpuTotalNext, cpuTotalPrev);
- printf("%f %f\n", cpuIdleNext, cpuIdlePrev);
-
- totalTick = (cpuTotalNext - cpuTotalPrev);
- idleTick = (cpuIdleNext - cpuIdlePrev);
-
- cpuUsage = 100 * (totalTick - idleTick) / (totalTick);
-
- return cpuUsage;
-}
-
-double getCpuCount()
-{
- return get_nprocs();
-}
-
-//it support over linux kernel 3.14
-double getMemoryAvailable()
-{
-
- long int memAvailable;
-
-#ifdef __linux__
- char stream[1024];
-
- FILE *file = fopen("/proc/meminfo", "r");
-
- //just reading one string , so check return to 1
- while (fscanf(file, " %1023s", stream) == 1)
- {
- if (!SSTRNCMP(stream, "MemAvailable:"))
- {
- fscanf(file, " %ld", &memAvailable);
- }
- }
- fclose(file);
-
-#else
-#error "Not Support this architecture"
-#endif
-
- return (double)memAvailable;
-}
-
-double getMemoryFree()
-{
-
- long int memFree;
-
-#ifdef __linux__
- char stream[1024];
-
- FILE *file = fopen("/proc/meminfo", "r");
-
- //just reading one string , so check return to 1
- while (fscanf(file, " %1023s", stream) == 1)
- {
- if (!SSTRNCMP(stream, "MemFree:"))
- {
- fscanf(file, " %ld", &memFree);
- }
- }
- fclose(file);
-
-#else
-#error "Not Support this architecture"
-#endif
-
- return (double)memFree;
-}
-
-double networkMbps(char (*ifNames)[NIC_NAME_LEN], int count)
-{
- unsigned long prevTotalByte, nextTotalByte;
-
- char **ifNamesPath = malloc(sizeof(char *) * count * 2);
- for (int i = 0; i < count * 2; i++)
- {
- ifNamesPath[i] = malloc(sizeof(char) * 512);
- }
-
- makeIfNamesPath(ifNames, count, ifNamesPath);
- prevTotalByte = networkTotalPackets(ifNamesPath, count * 2);
- usleep(1000 * 1000);
- nextTotalByte = networkTotalPackets(ifNamesPath, count * 2);
-
- double mbps = (nextTotalByte - prevTotalByte) / 1024.0 / 1024.0;
-
- for (int i = 0; i < count * 2; i++)
- {
- free(ifNamesPath[i]);
- }
- free(ifNamesPath);
-
- return mbps;
-}
-
-double networkBandwidth()
-{
- int sock;
- struct ifreq ifr;
- struct ethtool_cmd edata;
- int rc;
-
- sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
- if (sock < 0)
- {
- perror("socket");
- exit(1);
- }
-
- strncpy(ifr.ifr_name, "enp4s0", sizeof(ifr.ifr_name));
- ifr.ifr_data = &edata;
-
- edata.cmd = ETHTOOL_GSET;
-
- rc = ioctl(sock, SIOCETHTOOL, &ifr);
- if (rc < 0)
- {
- perror("ioctl");
- exit(1);
- }
- switch (ethtool_cmd_speed(&edata))
- {
- case SPEED_10:
- printf("10Mbps\n");
- break;
- case SPEED_100:
- printf("100Mbps\n");
- break;
- case SPEED_1000:
- printf("1Gbps\n");
- break;
- case SPEED_2500:
- printf("2.5Gbps\n");
- break;
- case SPEED_10000:
- printf("10Gbps\n");
- break;
- default:
- printf("Speed returned is %d\n", edata.speed);
- }
-
- return (0);
-}
-//======================= PUBLIC API ===============================
-
-int main(int argc, char **argv)
-{
-
- char allIfNames[NIC_MAX_COUNT][NIC_NAME_LEN];
- char targetIfNames[NIC_MAX_COUNT][NIC_NAME_LEN];
- int targetIfNamesCount;
-
- getInterfaceAdapter(allIfNames);
- targetIfNamesCount = filteringIfNames(allIfNames, targetIfNames);
- printf("count : %d\n", targetIfNamesCount);
-
- while (1)
- {
- printf("=======================\n");
- printf("networkmbps : %f\n", networkMbps(targetIfNames, targetIfNamesCount));
- printf("networkbandwidth : %f\n", networkBandwidth());
- printf("memory available : %f\n", getMemoryAvailable());
- printf("memory free : %f\n", getMemoryFree());
- printf("cpu count : %f\n", getCpuCount());
- printf("cpu usage : %f\n", getCpuUsage());
- printf("=======================\n");
- }
-}
\ No newline at end of file