update service executor
authorwansuyoo <wansu.yoo@samsung.com>
Tue, 12 Mar 2019 06:23:22 +0000 (15:23 +0900)
committerwansuyoo <wansu.yoo@samsung.com>
Tue, 12 Mar 2019 06:23:22 +0000 (15:23 +0900)
pkg/linux_amd64/devicemgr.a [new file with mode: 0644]
pkg/linux_amd64/servicemgr.a [new file with mode: 0644]
src/restapi/v1/restapi.go
src/servicemgr/http_sender.go [new file with mode: 0644]
src/servicemgr/main.go [new file with mode: 0644]
src/servicemgr/play_service.go [new file with mode: 0644]
src/servicemgr/save_service.go [new file with mode: 0644]
src/servicemgr/service_agent.go [new file with mode: 0644]
src/servicemgr/service_execute.go [deleted file]
src/servicemgr/types.go

diff --git a/pkg/linux_amd64/devicemgr.a b/pkg/linux_amd64/devicemgr.a
new file mode 100644 (file)
index 0000000..7fff7ec
Binary files /dev/null and b/pkg/linux_amd64/devicemgr.a differ
diff --git a/pkg/linux_amd64/servicemgr.a b/pkg/linux_amd64/servicemgr.a
new file mode 100644 (file)
index 0000000..b971e79
Binary files /dev/null and b/pkg/linux_amd64/servicemgr.a differ
index da4bef29e778b2aa10fbd1e877e7de9bf2898d2a..2c3977bbb073491f33254d049a8a38a27683fd93 100644 (file)
@@ -14,6 +14,7 @@ import (
        "encoding/json"
        "log"
        "net/http"
+       "servicemgr"
 )
 
 // APIV1DeviceResourceUsageCPUGet function
@@ -56,8 +57,10 @@ func APIV1DeviceResourceUsageNetworkGet(w http.ResponseWriter, r *http.Request)
 func APIV1ServicemgrServiceDelete(w http.ResponseWriter, r *http.Request) {
        log.Printf("[%s] APIV1ServicemgrServiceDelete", logPrefix)
 
+       servicemgr.StopServiceHandler(w, r)
        w.Header().Set("Content-Type", "application/json; charset=UTF-8")
-       w.WriteHeader(http.StatusOK)
+       data := []byte("Your Request Path is " + r.URL.Path)
+       writeJSONResponse(w, data, http.StatusOK)
 }
 
 // APIV1ServicemgrServiceGet function
@@ -72,8 +75,10 @@ func APIV1ServicemgrServiceGet(w http.ResponseWriter, r *http.Request) {
 func APIV1ServicemgrServicePost(w http.ResponseWriter, r *http.Request) {
        log.Printf("[%s] APIV1ServicemgrServicePost", logPrefix)
 
+       go servicemgr.Run(servicemgr.StartServiceHandler(w, r))
        w.Header().Set("Content-Type", "application/json; charset=UTF-8")
-       w.WriteHeader(http.StatusOK)
+       data := []byte("Your Request Path is " + r.URL.Path)
+       writeJSONResponse(w, data, http.StatusOK)
 }
 
 // APIV1ServicemgrServiceServiceIDGet function
diff --git a/src/servicemgr/http_sender.go b/src/servicemgr/http_sender.go
new file mode 100644 (file)
index 0000000..cad4a6f
--- /dev/null
@@ -0,0 +1,125 @@
+package servicemgr
+
+import (
+       "bytes"
+       "fmt"
+       "io/ioutil"
+       "net/http"
+       "os"
+)
+
+// SendPostJSONMsg is for sending JSON body
+func SendPostJSONMsg(targetURL string, pbytes []byte) {
+       buff := bytes.NewBuffer(pbytes)
+
+       req, err := http.NewRequest("POST", targetURL, buff)
+       if err != nil {
+               panic(err)
+       }
+
+       // Content-Type Header
+       req.Header.Add("Content-Type", "application/json")
+
+       client := &http.Client{}
+       resp, err := client.Do(req)
+       if err != nil {
+               panic(err)
+       }
+       defer resp.Body.Close()
+
+       // Checking Response Validation
+       respBody, err := ioutil.ReadAll(resp.Body)
+       if err == nil {
+               str := string(respBody)
+               println(str)
+       }
+}
+
+func convertFile(fileToBeUploaded string) (*os.File, []byte) {
+       file, err := os.Open(fileToBeUploaded)
+
+       if err != nil {
+               fmt.Println(err)
+               panic(err)
+       }
+
+       fileContents, err := ioutil.ReadAll(file)
+       if err != nil {
+               return nil, nil
+       }
+       // fileInfo, _ := file.Stat()
+       // var size int64 = fileInfo.Size()
+       // bytes := make([]byte, size)
+
+       return file, fileContents
+       // defer file.Close()
+
+       // It is buffer -> file
+       // buffer := bufio.NewReader(file)
+       // _, err = buffer.Read(bytes)
+}
+
+// SendPostFile is for sending file type body
+// @TODO It needs to test
+/*func SendPostFile() {
+       targetURL := "http://10.113.175.60:5000/executeService"
+       fileName := "daisy.jpg"
+       var buf bytes.Buffer
+       mpw := multipart.NewWriter(&buf)
+
+       exampleParam := common.ExecutionType{"", "", "save", common.SaveServiceInfo{"./storage2/", nil}}
+       pbytes, _ := json.Marshal(exampleParam)
+
+       executionCommandField, err := mpw.CreateFormField("executionCommand")
+       if err != nil {
+               panic(err)
+       }
+       if _, err := executionCommandField.Write(pbytes); err != nil {
+               fmt.Println("mpw is not closed normally")
+       }
+
+       file, err := os.Open(fileName)
+       if err != nil {
+               panic(err)
+       }
+
+       fileContents, err := ioutil.ReadAll(file)
+       if err != nil {
+               panic(err)
+       }
+
+       fileField, err := mpw.CreateFormFile("file", fileName)
+       if err != nil {
+               panic(err)
+       }
+
+       if _, err := fileField.Write(fileContents); err != nil {
+               fmt.Println("mpw is not closed normally")
+       }
+
+       req, err := http.NewRequest("POST", targetURL, &buf)
+       if err != nil {
+               return
+       }
+
+       req.Header.Set("Content-Type", mpw.FormDataContentType())
+
+       if err := mpw.Close(); err != nil {
+               fmt.Println("mpw is not closed normally")
+       }
+       // Request
+       client := &http.Client{}
+       resp, err := client.Do(req)
+       if err != nil {
+               panic(err)
+       }
+       defer resp.Body.Close()
+
+       // Checking Response Validation
+       respBody, err := ioutil.ReadAll(resp.Body)
+       if err == nil {
+               str := string(respBody)
+               println(str)
+       }
+}
+*/
diff --git a/src/servicemgr/main.go b/src/servicemgr/main.go
new file mode 100644 (file)
index 0000000..ab46614
--- /dev/null
@@ -0,0 +1,96 @@
+package servicemgr
+
+import (
+       "encoding/json"
+       "fmt"
+       "io"
+       "log"
+       "net/http"
+       "os"
+)
+
+func checkHTTPError(w http.ResponseWriter, err error) {
+       if err != nil {
+               http.Error(w, err.Error(), http.StatusInternalServerError)
+               panic(err)
+       }
+}
+
+// StartServiceHandler func
+func StartServiceHandler(w http.ResponseWriter, req *http.Request) DistService {
+       decoder := json.NewDecoder(req.Body)
+
+       distService := DistService{}
+       err := decoder.Decode(&distService)
+       if err != nil {
+               panic(err)
+       }
+
+       return distService
+}
+
+// StopServiceHandler func
+func StopServiceHandler(w http.ResponseWriter, req *http.Request) {
+       decoder := json.NewDecoder(req.Body)
+
+       distService := DistService{}
+       err := decoder.Decode(&distService)
+       if err != nil {
+               panic(err)
+       }
+
+       cmd, exists := ServiceCmdMap[distService.ServiceName]
+
+       if exists {
+               err = cmd.Process.Kill()
+               if err != nil {
+                       log.Println("Error occured from Process.Kill() : ", err)
+               }
+
+               delete(ServiceCmdMap, distService.ServiceName)
+       } else {
+               log.Println(distService.ServiceName, "is not exist service")
+       }
+}
+
+func startServiceHandlerForm(w http.ResponseWriter, req *http.Request) ExecutionType {
+       mr, err := req.MultipartReader()
+       checkHTTPError(w, err)
+
+       executionInfo := ExecutionType{}
+       index := 0
+       executionInfo.ServiceInfo.FileItem = make([]FileItem, 10, 100)
+
+       for {
+               part, err := mr.NextPart()
+
+               if err == io.EOF {
+                       break
+               }
+               checkHTTPError(w, err)
+
+               if part.FormName() == "file" {
+                       fmt.Println("index", index, part.FileName())
+                       outfile, err := os.Create("./storage/" + part.FileName())
+                       defer outfile.Close()
+                       executionInfo.ServiceInfo.FileItem[index].FileName = part.FileName()
+                       fmt.Println("FileName:", executionInfo.ServiceInfo.FileItem[index].FileName)
+
+                       checkHTTPError(w, err)
+
+                       _, err = io.Copy(outfile, part)
+                       checkHTTPError(w, err)
+
+                       index++
+               } else if part.FormName() == "executionCommand" {
+                       jsonDecoder := json.NewDecoder(part)
+
+                       err = jsonDecoder.Decode(&executionInfo)
+                       checkHTTPError(w, err)
+
+                       fmt.Println(executionInfo.Name, executionInfo.ParamStr, executionInfo.ServiceType)
+               }
+       }
+
+       return executionInfo
+}
diff --git a/src/servicemgr/play_service.go b/src/servicemgr/play_service.go
new file mode 100644 (file)
index 0000000..2aec40e
--- /dev/null
@@ -0,0 +1,62 @@
+package servicemgr
+
+import (
+       "encoding/json"
+       "fmt"
+       "log"
+       "os"
+       "os/exec"
+)
+
+// PlayService for service that execute by self
+type PlayService struct {
+       serviceName string
+       paramStr    []string
+}
+
+func (p PlayService) execute() {
+       fmt.Println(p.serviceName, " ", p.paramStr)
+
+       binary, lookErr := exec.LookPath(p.serviceName)
+       if lookErr != nil {
+               panic(lookErr)
+       }
+
+       var cmd *exec.Cmd
+       if len(p.paramStr) == 0 {
+               cmd = exec.Command(binary)
+       } else {
+               cmd = exec.Command(binary, p.paramStr...)
+       }
+
+       ServiceCmdMap[p.serviceName] = cmd
+
+       cmd.Stdout = os.Stdout
+
+       err := cmd.Start()
+       if err != nil {
+               log.Fatal(err)
+       }
+
+       log.Printf("Just ran subprocess %d, exiting\n", cmd.Process.Pid)
+
+       ch := make(chan error)
+
+       go func() {
+               ch <- cmd.Wait()
+       }()
+
+       select {
+       case e := <-ch:
+               if e != nil {
+                       log.Println(p.serviceName, "exited with Error : ", e)
+
+                       pbytes, _ := json.Marshal(ErrorType{e.Error()})
+                       // @TODO TargetURL needs to be declared
+                       SendPostJSONMsg("targetURL", pbytes)
+               } else {
+                       log.Println(p.serviceName, "exited")
+               }
+               delete(ServiceCmdMap, p.serviceName)
+       }
+}
diff --git a/src/servicemgr/save_service.go b/src/servicemgr/save_service.go
new file mode 100644 (file)
index 0000000..3ec5272
--- /dev/null
@@ -0,0 +1,34 @@
+package servicemgr
+
+import (
+       "fmt"
+       "os"
+)
+
+// SaveService structure
+type SaveService struct {
+       targetPath string
+       fileInfo   []FileItem
+}
+
+func (s SaveService) execute() {
+       fmt.Println(s.targetPath)
+
+       for index, fileItem := range s.fileInfo {
+               name := fileItem.FileName
+
+               if len(name) == 0 {
+                       break
+               }
+
+               fmt.Println(index, fileItem.FileName)
+
+               oldLocation := "./storage/" + name
+               newLocation := s.targetPath + name
+               err := os.Rename(oldLocation, newLocation)
+
+               if err != nil {
+                       fmt.Println("Failed saving file : ", index, name)
+               }
+       }
+}
diff --git a/src/servicemgr/service_agent.go b/src/servicemgr/service_agent.go
new file mode 100644 (file)
index 0000000..5054a6d
--- /dev/null
@@ -0,0 +1,33 @@
+package servicemgr
+
+import (
+       "strconv"
+)
+
+// ServiceAgent is interface for basic-service
+type ServiceAgent interface {
+       execute()
+}
+
+// Run is for executing service
+func Run(executionJSON DistService) {
+       var service ServiceAgent
+       serviceType := executionJSON.Type
+
+       var args []string
+       for _, userParam := range executionJSON.UserParam.Args {
+               args = append(args, userParam)
+       }
+
+       args = append(args, executionJSON.SystemParam.IP)
+       args = append(args, strconv.Itoa(executionJSON.SystemParam.Port))
+
+       if serviceType == "CPU" {
+               service = PlayService{executionJSON.ServiceName, args}
+       }
+       // else {
+       // service = SaveService{executionJSON.ServiceInfo.SavePath, executionJSON.ServiceInfo.FileItem}
+       // }
+
+       service.execute()
+}
diff --git a/src/servicemgr/service_execute.go b/src/servicemgr/service_execute.go
deleted file mode 100644 (file)
index 1da7595..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-/*
- * 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 servicemgr
index 020bc0c7578e66184120f333ff926dc146ef2710..26a057c0f7d4005be58be980a690bb985415a387 100644 (file)
@@ -1,3 +1,59 @@
 package servicemgr
 
+import "os/exec"
+
 var logPrefix = "servicemgr"
+
+// ServiceCmdMap map
+var ServiceCmdMap = map[string](*exec.Cmd){}
+
+// ExecutionParam structure
+type ExecutionParam struct {
+       Broker string
+       Topic  string
+       Value  string
+}
+
+// FileItem structure
+type FileItem struct {
+       FileName string
+}
+
+// SaveServiceInfo structure
+type SaveServiceInfo struct {
+       SavePath string
+       FileItem []FileItem
+}
+
+// ExecutionType structure
+type ExecutionType struct {
+       Name        string
+       ParamStr    string
+       ServiceType string
+       ServiceInfo SaveServiceInfo
+}
+
+// DistService structure
+type DistService struct {
+       ServiceName string      `json:"ServiceName"`
+       Status      string      `json:"Status"`
+       Type        string      `json:"Type"`
+       SystemParam SystemParam `json:"SystemParam"`
+       UserParam   UserParam   `json:"UserParam"`
+}
+
+// SystemParam structure
+type SystemParam struct {
+       IP   string `json:"IP"`
+       Port int    `json:"Port"`
+}
+
+// UserParam structure
+type UserParam struct {
+       Args []string `json:"Args"`
+}
+
+// ErrorType structure
+type ErrorType struct {
+       ErrorCode string `json:"ErrorCode"`
+}