Skip to content

Commit

Permalink
Merge pull request #174 from hossted/patch
Browse files Browse the repository at this point in the history
compose - mismatch ids + patch fixes
  • Loading branch information
AdheipSingh authored Nov 7, 2024
2 parents 85a702a + 00efc57 commit 3bbf335
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 158 deletions.
128 changes: 1 addition & 127 deletions hossted/service/compose/activate_compose.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ func ActivateCompose(composeFilePath string, develMode bool) error {

yamlData, err := yaml.Marshal(osInfo)
if err != nil {
return fmt.Errorf("error in YAML marshaling: %s\n", err)
return fmt.Errorf("error in YAML marshaling: %s", err)
}

err = writeFile(osFilePath, yamlData)
Expand Down Expand Up @@ -272,129 +272,3 @@ func GetClusterInfo() (OsInfo, error) {

return osInfo, nil
}

// provide prompt to enable monitoring and vulnerability scan

//

// func setUUID(email string) error {

// homeDir, err := os.UserHomeDir()
// if err != nil {
// fmt.Printf("Error getting home directory: %s\n", err)
// return err
// }
// // Construct the full path to compose-status.json
// filePath := filepath.Join(homeDir, ".hossted", "compose-status.json")
// if _, err := os.Stat(filePath); os.IsNotExist(err) {
// err = updateUUID(filePath, email)
// if err != nil {
// return err
// }
// } else if err != nil {
// return err
// } else {
// prompt := promptui.Select{
// Label: "Config file already exists do want to override it?",
// Items: []string{"Yes", "No"},
// }
// _, result, err := prompt.Run()
// if err != nil {
// fmt.Printf("Prompt failed %v\n", err)
// return err
// }
// if result == "No" {
// fmt.Println("Exiting.")
// os.Exit(0)
// }
// err = updateUUID(filePath, email)
// if err != nil {
// return err
// }
// }
// return nil
// }

// func updateUUID(filepath, email string) error {
// clusterUUID := "D-" + uuid.NewString()
// fmt.Println("Generating Cluster UUID", clusterUUID)
// info := AppsInfo{
// ClusterInfo: ClusterInfo{
// ClusterUUID: clusterUUID,
// EmailID: email,
// },
// ComposeStatus: []ComposeStatus{},
// }
// jsonData, err := json.MarshalIndent(info, "", " ")
// if err != nil {
// fmt.Printf("Error marshaling JSON: %s\n", err)
// return err
// }
// // Write the JSON data to the file
// err = ioutil.WriteFile(filepath, jsonData, 0644)
// if err != nil {
// fmt.Printf("Error writing JSON to file: %s\n", err)
// return err
// }
// return nil
// }

// func checkUUID(filePath string) (string, error) {
// file, err := os.Open(filePath)
// if err != nil {
// if os.IsNotExist(err) {
// fmt.Printf("File %s does not exist.\n", filePath)
// } else {
// fmt.Printf("Error opening file: %s\n", err)
// }
// return "", err
// }
// defer file.Close()

// data, err := ioutil.ReadAll(file)
// if err != nil {
// fmt.Printf("Error reading file: %s\n", err)
// return "", err
// }
// var appData AppsInfo
// err = json.Unmarshal(data, &appData)
// if err != nil {
// fmt.Printf("Error unmarshaling JSON: %s\n", err)
// return "", err
// }
// fmt.Println("UUID IS", appData.ClusterInfo.ClusterUUID)
// return appData.ClusterInfo.ClusterUUID, nil
// }

//GET CLUSTER ID

// func getClusterUUID() (string, error) {
// var clusterUUID string
// var err error
// yellow := color.New(color.FgYellow).SprintFunc()

// // Retry for 120 seconds
// for i := 0; i < 120; i++ {
// clusterUUID, err = getClusterUUIDFromDocker()
// if err == nil {
// return clusterUUID, nil
// }
// fmt.Println(yellow("Info:"), "Waiting for Hossted Operator to get into running state")
// time.Sleep(4 * time.Second) // Wait for 1 second before retrying
// }

// return "", fmt.Errorf("Failed to get ClusterUUID after 120 seconds: %v", err)
// }

// func getClusterUUIDFromDocker() (string, error) {
// cs := getKubeClient()
// hp, err := cs.Resource(hpGVK).Get(context.TODO(), "hossted-operator-cr", metav1.GetOptions{})
// if err != nil {
// return "", err
// }
// clusterUUID, _, err := unstructured.NestedString(hp.Object, "status", "clusterUUID")
// if err != nil || clusterUUID == "" {
// return "", fmt.Errorf("ClusterUUID is nil, func errored")
// }
// return clusterUUID, nil
// }
119 changes: 88 additions & 31 deletions hossted/service/compose/reconcile_compose.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -196,14 +197,14 @@ type request struct {
UUID string `json:"uuid"`
OsUUID string `json:"osuuid"`
OrgID string `json:"org_id"`
Email string `json:"email"`
Type string `json:"type"`
Product string `json:"product"`
CPUNum string `json:"cpunum"`
Memory string `json:"memory"`
Email string `json:"email,omitempty"`
Type string `json:"type,omitempty"`
Product string `json:"product,omitempty"`
CPUNum string `json:"cpunum,omitempty"`
Memory string `json:"memory,omitempty"`
OptionsState optionsState `json:"options_state"`
ComposeFile string `json:"compose_file"`
AccessInfo AccessInfo `json:"access_info"`
ComposeFile string `json:"compose_file,omitempty"`
AccessInfo AccessInfo `json:"access_info,omitempty"`
}

type dockerInstance struct {
Expand All @@ -225,24 +226,21 @@ func sendComposeInfo(appFilePath string, osInfo OsInfo) error {
hosstedAPIUrl := osInfo.HosstedApiUrl
orgID := osInfo.OrgID
token := osInfo.Token

composeInfo, err := readFile(appFilePath)
if err != nil {
return err
}

composeUrl := hosstedAPIUrl + "/compose/hosts"
containersUrl := hosstedAPIUrl + "/compose/containers"

projectName, err := getProjectName()
if err != nil {
return err
}

access_info := getAccessInfo("/opt/" + projectName + "/.env")
accessInfo := getAccessInfo("/opt/" + projectName + "/.env")

var data map[string]AppRequest
err = json.Unmarshal(composeInfo, &data)
if err != nil {
if err = json.Unmarshal(composeInfo, &data); err != nil {
return err
}

Expand All @@ -255,12 +253,33 @@ func sendComposeInfo(appFilePath string, osInfo OsInfo) error {
return err
}

isMarketplace, err := isMarketplaceVM()
if err != nil {
return fmt.Errorf("isMarketplaceVM func errored: %v", err)
}

if isMarketplace {
if err = submitPatchRequest(osInfo, data, *accessInfo, cpu, mem); err != nil {
return fmt.Errorf("error in patch request: %v", err)
}
fmt.Println("Successfully submitted PATCH request if marketplace VM")
} else {
if err = registerApplications(data, osInfo, *accessInfo, cpu, mem, orgID, token, hosstedAPIUrl+"/compose/hosts"); err != nil {
return err
}
}

return registerDockerInstances(data, osInfo, token, hosstedAPIUrl+"/compose/containers", isMarketplace)
}

// registerApplications registers all applications with the specified API URL.
func registerApplications(data map[string]AppRequest, osInfo OsInfo, accessInfo AccessInfo, cpu, mem, orgID, token, composeUrl string) error {
for appName, compose := range data {
newReq := request{
UUID: compose.AppAPIInfo.AppUUID,
OsUUID: compose.AppAPIInfo.OsUUID,
Email: compose.AppAPIInfo.EmailID,
AccessInfo: *access_info,
AccessInfo: accessInfo,
OrgID: orgID,
Type: "compose",
Product: appName,
Expand All @@ -274,25 +293,25 @@ func sendComposeInfo(appFilePath string, osInfo OsInfo) error {
ComposeFile: compose.AppInfo.ComposeFile,
}

body, err := json.Marshal(newReq)
if err != nil {
return err
}

err = common.HttpRequest("POST", composeUrl, token, body)
if err != nil {
if err := sendRequest("POST", composeUrl, token, newReq); err != nil {
return err
}

fmt.Printf("Successfully registered app [%s] with appID [%s]\n", appName, compose.AppAPIInfo.AppUUID)
}
return nil
}

// registerDockerInstances registers all docker instances based on whether it is a marketplace VM.
func registerDockerInstances(data map[string]AppRequest, osInfo OsInfo, token, containersUrl string, isMarketplace bool) error {
for appName, info := range data {
for _, ci := range info.AppInfo.DockerInstance {

instanceID := osInfo.AppUUID
if isMarketplace {
instanceID = osInfo.OsUUID
}
newDI := dockerInstance{
DockerID: ci.DockerID,
InstanceID: info.AppAPIInfo.AppUUID,
InstanceID: instanceID,
ImageID: ci.ImageID,
Ports: ci.Ports,
Status: ci.Status,
Expand All @@ -304,19 +323,58 @@ func sendComposeInfo(appFilePath string, osInfo OsInfo) error {
Tag: ci.Tag,
CreatedAt: ci.CreatedAt,
}
newDIBody, err := json.Marshal(newDI)
if err != nil {
return err
}

err = common.HttpRequest("POST", containersUrl, token, newDIBody)
if err != nil {
if err := sendRequest("POST", containersUrl, token, newDI); err != nil {
return err
}

fmt.Printf("Successfully registered docker info, appName:[%s], dockerName:[%s], appID:[%s]\n", appName, ci.Names, info.AppAPIInfo.AppUUID)
}
}
return nil
}

// submitPatchRequest sends a PATCH request with VM info for marketplace setups.
func submitPatchRequest(osInfo OsInfo, compose map[string]AppRequest, accessInfo AccessInfo, cpu, mem string) error {
composeUrl := osInfo.HosstedApiUrl + "/compose/hosts/" + osInfo.OsUUID

var composeFile, applicationName string
for appName, appReq := range compose {
composeFile = appReq.AppInfo.ComposeFile
applicationName = appName
}

newReq := request{
UUID: osInfo.AppUUID,
OsUUID: osInfo.OsUUID,
AccessInfo: accessInfo,
OrgID: osInfo.OrgID,
Type: "vm",
Product: applicationName,
CPUNum: cpu,
Memory: mem,
OptionsState: optionsState{
Monitoring: true,
Logging: true,
CVEScan: false,
},
ComposeFile: composeFile,
}

return sendRequest(http.MethodPatch, composeUrl, osInfo.Token, newReq)
}

// sendRequest handles HTTP requests for a given method, URL, token, and request body.
func sendRequest(method, url, token string, reqBody interface{}) error {
body, err := json.Marshal(reqBody)
if err != nil {
return fmt.Errorf("failed to marshal JSON: %v", err)
}

err = common.HttpRequest(method, url, token, body)
if err != nil {
return fmt.Errorf("error in %s request to %s: %v", method, url, err)
}

return nil
}
Expand Down Expand Up @@ -592,7 +650,6 @@ func runMonitoringCompose(monitoringEnable, osUUID, appUUID string) error {
// Replace the UUID placeholder with the actual UUID
configStr := string(configData)

fmt.Println(osUUID, appUUID)
configStr = strings.Replace(configStr, "${UUID}", fmt.Sprintf("\"%s\"", osUUID), -1)
configStr = strings.Replace(configStr, "${APP_UUID}", fmt.Sprintf("\"%s\"", appUUID), -1)

Expand Down

0 comments on commit 3bbf335

Please sign in to comment.