"encoding/json"
"log"
"net/http"
+ "servicemgr"
)
// APIV1DeviceResourceUsageCPUGet function
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
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
--- /dev/null
+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)
+ }
+}
+*/
--- /dev/null
+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
+}
--- /dev/null
+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)
+ }
+}
--- /dev/null
+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)
+ }
+ }
+}
--- /dev/null
+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()
+}
+++ /dev/null
-/*
- * 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
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"`
+}