Files

358 lines
9.1 KiB
Go
Raw Permalink Normal View History

package handlers
import (
"encoding/json"
"errors"
2024-07-05 15:47:43 +05:45
"fmt"
"io"
2024-12-12 15:57:43 +05:45
"log"
"net/http"
2024-07-05 15:08:45 +05:45
"ociswrapper/common"
"ociswrapper/ocis"
2024-12-12 15:57:43 +05:45
"ociswrapper/ocis/config"
2025-04-30 12:02:55 +05:45
"strconv"
"strings"
)
2024-07-05 12:54:42 +05:45
type BasicResponse struct {
Status string `json:"status"`
Message string `json:"message"`
}
type CommandResponse struct {
*BasicResponse
ExitCode int `json:"exitCode"`
}
func parseJsonBody(reqBody io.ReadCloser) (map[string]any, error) {
body, _ := io.ReadAll(reqBody)
if len(body) == 0 || !json.Valid(body) {
2024-07-05 12:54:42 +05:45
return nil, errors.New("invalid json data")
}
var bodyMap map[string]any
json.Unmarshal(body, &bodyMap)
return bodyMap, nil
}
func sendResponse(res http.ResponseWriter, statusCode int, message string) {
2024-07-05 12:54:42 +05:45
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(statusCode)
2024-07-05 12:54:42 +05:45
var status string
if statusCode == http.StatusOK {
2024-07-05 12:54:42 +05:45
status = "OK"
} else {
2024-07-05 12:54:42 +05:45
status = "ERROR"
}
resBody := BasicResponse{
Status: status,
Message: message,
}
jsonResponse, _ := json.Marshal(resBody)
res.Write(jsonResponse)
}
func sendCmdResponse(res http.ResponseWriter, exitCode int, message string) {
2024-07-05 14:55:03 +05:45
resBody := CommandResponse{
BasicResponse: &BasicResponse{
Message: message,
},
ExitCode: exitCode,
}
2024-07-05 12:54:42 +05:45
if exitCode == 0 {
2024-07-05 14:55:03 +05:45
resBody.BasicResponse.Status = "OK"
2024-07-05 12:54:42 +05:45
} else {
2024-07-05 14:55:03 +05:45
resBody.BasicResponse.Status = "ERROR"
}
2024-07-05 14:55:03 +05:45
res.WriteHeader(http.StatusOK)
res.Header().Set("Content-Type", "application/json")
jsonResponse, _ := json.Marshal(resBody)
res.Write(jsonResponse)
}
func SetEnvHandler(res http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPut {
sendResponse(res, http.StatusMethodNotAllowed, "")
return
}
2024-07-05 15:47:43 +05:45
envBody, err := parseJsonBody(req.Body)
if err != nil {
sendResponse(res, http.StatusMethodNotAllowed, "Invalid json body")
return
}
2024-07-05 15:47:43 +05:45
var envMap []string
for key, value := range envBody {
envMap = append(envMap, fmt.Sprintf("%s=%v", key, value))
}
ocis.ServiceEnvConfigs["ocis"] = append(ocis.ServiceEnvConfigs["ocis"], envMap...)
2024-07-05 15:47:43 +05:45
2024-07-05 12:54:42 +05:45
var message string
success, _ := ocis.Restart(ocis.ServiceEnvConfigs["ocis"])
2024-07-05 12:54:42 +05:45
if success {
message = "oCIS configured successfully"
sendResponse(res, http.StatusOK, message)
return
2024-07-05 12:54:42 +05:45
}
message = "Failed to restart oCIS with new configuration"
sendResponse(res, http.StatusInternalServerError, message)
}
func K8sSetEnvHandler(res http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPut {
sendResponse(res, http.StatusMethodNotAllowed, "")
return
}
envBody, err := parseJsonBody(req.Body)
if err != nil {
sendResponse(res, http.StatusMethodNotAllowed, "Invalid json body")
return
}
var message string
var envMap []string
for service, envs := range envBody {
for env, value := range envs.(map[string]any) {
envMap = append(envMap, fmt.Sprintf("%s=%v", env, value))
}
service = strings.ReplaceAll(service, "-", "")
success, _ := ocis.K8sUpdateEnv(service, envMap)
if !success {
message = "Failed to restart oCIS with new configuration"
sendResponse(res, http.StatusInternalServerError, message)
return
}
envMap = []string{}
}
message = "oCIS configured successfully"
sendResponse(res, http.StatusOK, message)
}
func RollbackHandler(res http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodDelete {
sendResponse(res, http.StatusMethodNotAllowed, "")
return
}
2024-07-05 12:54:42 +05:45
var message string
ocis.ServiceEnvConfigs["ocis"] = []string{}
2025-01-20 14:55:21 +05:45
success, _ := ocis.Restart([]string{})
2024-07-05 12:54:42 +05:45
if success {
message = "oCIS configuration rolled back successfully"
sendResponse(res, http.StatusOK, message)
return
2024-07-05 12:54:42 +05:45
}
message = "Failed to restart oCIS with initial configuration"
sendResponse(res, http.StatusInternalServerError, message)
2024-07-05 12:54:42 +05:45
}
func K8sRollbackHandler(res http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodDelete {
sendResponse(res, http.StatusMethodNotAllowed, "")
return
}
var message string
success, _ := ocis.K8sRollback()
if success {
message = "oCIS rolled back successfully"
sendResponse(res, http.StatusOK, message)
return
}
message = "Failed to rollback oCIS"
sendResponse(res, http.StatusInternalServerError, message)
}
2024-07-05 12:54:42 +05:45
func StopOcisHandler(res http.ResponseWriter, req *http.Request) {
2024-07-05 15:08:45 +05:45
if req.Method != http.MethodPost {
sendResponse(res, http.StatusMethodNotAllowed, "")
2024-07-05 12:54:42 +05:45
return
}
success, message := ocis.Stop()
if success {
sendResponse(res, http.StatusOK, message)
return
}
sendResponse(res, http.StatusInternalServerError, message)
2024-07-05 12:54:42 +05:45
}
2024-07-05 15:08:45 +05:45
func StartOcisHandler(res http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
sendResponse(res, http.StatusMethodNotAllowed, "")
2024-07-05 15:08:45 +05:45
return
}
if ocis.IsOcisRunning() {
sendResponse(res, http.StatusConflict, "oCIS server is already running")
2024-07-05 15:08:45 +05:45
return
}
common.Wg.Add(1)
go ocis.Start(ocis.ServiceEnvConfigs[ocis.OcisServiceName])
2024-07-05 15:08:45 +05:45
success, message := ocis.WaitForConnection()
if success {
sendResponse(res, http.StatusOK, message)
return
}
sendResponse(res, http.StatusInternalServerError, message)
2024-07-05 15:08:45 +05:45
}
2024-07-05 12:54:42 +05:45
func CommandHandler(res http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
sendResponse(res, http.StatusMethodNotAllowed, "")
2024-07-05 12:54:42 +05:45
return
}
2024-07-05 14:55:03 +05:45
if req.Body == nil {
sendResponse(res, http.StatusBadRequest, "Body is missing")
2024-07-05 12:54:42 +05:45
return
}
body, err := parseJsonBody(req.Body)
2024-07-05 14:55:03 +05:45
if err != nil {
sendResponse(res, http.StatusBadRequest, "Invalid json body")
return
}
if _, ok := body["command"]; !ok {
sendResponse(res, http.StatusBadRequest, "Command is missing")
2024-07-05 12:54:42 +05:45
return
}
command := body["command"].(string)
stdIn := []string{}
if _, ok := body["inputs"]; ok {
if inputs, ok := body["inputs"].([]interface{}); ok {
for _, input := range inputs {
if _, ok := input.(string); ok {
stdIn = append(stdIn, input.(string))
} else {
sendResponse(res, http.StatusBadRequest, "Invalid input data. Expected string")
return
}
}
}
}
exitCode, output := ocis.RunCommand(command, stdIn)
2024-07-05 14:55:03 +05:45
sendCmdResponse(res, exitCode, output)
}
2024-12-12 15:57:43 +05:45
func OcisServiceHandler(res http.ResponseWriter, req *http.Request) {
serviceName := req.PathValue("service")
2025-04-30 12:02:55 +05:45
var envBody map[string]interface{}
if req.Body != nil && req.ContentLength > 0 {
var err error
envBody, err = parseJsonBody(req.Body)
if err != nil {
sendResponse(res, http.StatusBadRequest, "Invalid json body")
return
}
}
2024-12-12 15:57:43 +05:45
if req.Method == http.MethodPost {
for key, value := range envBody {
2025-04-02 16:13:35 +02:00
ocis.ServiceEnvConfigs[serviceName] = append(ocis.ServiceEnvConfigs[serviceName], fmt.Sprintf("%s=%v", key, value))
if strings.HasSuffix(key, "DEBUG_ADDR") {
address := strings.Split(value.(string), ":")
port, _ := strconv.Atoi(address[1])
config.SetServiceDebugPort(serviceName, port)
2024-12-12 15:57:43 +05:45
}
}
2025-04-30 12:02:55 +05:45
log.Println(fmt.Sprintf("Starting '%s' service...", serviceName))
2024-12-12 15:57:43 +05:45
common.Wg.Add(1)
go ocis.StartService(serviceName, ocis.ServiceEnvConfigs[serviceName])
success := ocis.WaitForServiceStatus(serviceName, true)
if success {
2025-04-30 12:02:55 +05:45
sendResponse(res, http.StatusOK, fmt.Sprintf("'%s' service started successfully", serviceName))
} else {
2025-04-30 12:02:55 +05:45
sendResponse(res, http.StatusInternalServerError, fmt.Sprintf("Failed to start '%s' service.", serviceName))
}
return
} else if req.Method == http.MethodDelete {
success, message := ocis.StopService(serviceName)
log.Println(message)
if success {
sendResponse(res, http.StatusOK, message)
} else {
sendResponse(res, http.StatusInternalServerError, message)
}
return
} else if req.Method == http.MethodPatch {
success, message := ocis.StopService(serviceName)
if success {
2025-04-02 16:13:35 +02:00
var serviceEnvMap []string
2024-12-12 15:57:43 +05:45
for key, value := range envBody {
serviceEnvMap = append(serviceEnvMap, fmt.Sprintf("%s=%v", key, value))
if strings.HasSuffix(key, "DEBUG_ADDR") {
address := strings.Split(value.(string), ":")
port, _ := strconv.Atoi(address[1])
config.SetServiceDebugPort(serviceName, port)
}
serviceEnvMap = append(ocis.ServiceEnvConfigs[serviceName], serviceEnvMap...)
2024-12-12 15:57:43 +05:45
}
common.Wg.Add(1)
2025-04-30 12:02:55 +05:45
log.Println(fmt.Sprintf("Restarting '%s' service...", serviceName))
2024-12-12 15:57:43 +05:45
go ocis.StartService(serviceName, serviceEnvMap)
success := ocis.WaitForServiceStatus(serviceName, true)
if success {
2025-04-30 12:02:55 +05:45
sendResponse(res, http.StatusOK, fmt.Sprintf("'%s' service updated successfully", serviceName))
return
}
2024-12-12 15:57:43 +05:45
}
sendResponse(res, http.StatusInternalServerError, message)
2024-12-12 15:57:43 +05:45
return
}
sendResponse(res, http.StatusMethodNotAllowed, "Method Not Allowed")
}
2025-03-06 17:08:54 +05:45
func RollbackServicesHandler(res http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodDelete {
sendResponse(res, http.StatusMethodNotAllowed, "")
return
}
var rollbackFailed bool
var message string
for serviceName := range ocis.ServiceEnvConfigs {
if serviceName != "ocis" {
if success := ocis.WaitForServiceStatus(serviceName, true); success {
success, message := ocis.StopService(serviceName)
log.Println(message)
if !success {
rollbackFailed = true
break
}
delete(ocis.ServiceEnvConfigs, serviceName)
}
}
}
if rollbackFailed {
sendResponse(res, http.StatusInternalServerError, message)
} else {
sendResponse(res, http.StatusOK, "All services have been rolled back successfully")
}
}