Skip to content

Commit

Permalink
server: api: srest: Agent Install API updated
Browse files Browse the repository at this point in the history
Automatically install the agent on a remote server
  • Loading branch information
taking committed Jul 23, 2024
1 parent c61ea93 commit d34aa3b
Show file tree
Hide file tree
Showing 4 changed files with 171 additions and 2 deletions.
66 changes: 66 additions & 0 deletions server/lib/ssh/sourceFiles/copyAgent.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#!/bin/bash

AGENT_REPO="https://raw.githubusercontent.com/cloud-barista/cm-honeybee/main/agent"

get_latest_release() {
curl --silent "https://api.github.com/repos/$1/releases/latest" | # Get latest release from GitHub api
grep '"tag_name":' | # Get tag line
sed -E 's/.*"([^"]+)".*/\1/' # Pluck JSON value
}

Initializer() {
if [ -f /tmp/agentFirst ]; then
# 첫 실행이 아닐 경우
# echo "[Install] --PASS"
echo ""

sleep 1
else
# 첫 실행인 경우
touch /tmp/agentFirst

if [ -f /etc/debian_version ]; then
apt-get install -y curl wget > /tmp/honeybee-agent-install.log 2>&1
elif [ -f /etc/redhat-release ]; then
yum install -y curl wget > /tmp/honeybee-agent-install-install.log 2>&1
fi
fi
}

Copy() {
if [ -f /usr/bin/cm-honeybee-agent ]; then
# echo "[Binary Copy] --PASS"
echo ""

sleep 1
else
LATEST_RELEASE=$(get_latest_release "cloud-barista/cm-honeybee")
DOWNLOAD_URL=https://github.com/cloud-barista/cm-honeybee/releases/download/${LATEST_RELEASE}/cm-honeybee-agent

wget --no-check-certificate --continue --quiet $DOWNLOAD_URL -P /usr/bin
chmod a+x /usr/bin/cm-honeybee-agent

mkdir -p /etc/cloud-migrator/cm-honeybee-agent/conf
wget --no-check-certificate --continue --quiet ${AGENT_REPO}/conf/cm-honeybee-agent.yaml -P /etc/cloud-migrator/cm-honeybee-agent/conf
wget --no-check-certificate --continue --quiet ${AGENT_REPO}/scripts/systemd/cm-honeybee-agent.service -P /etc/systemd/system
fi
}

Start() {
status=$(service cm-honeybee-agent status | grep Active | awk '{print $3}')
if [[ "$status" == "(running)" ]]; then
# echo "[service start] --PASS"
echo ""

sleep 1
else
systemctl daemon-reload
systemctl enable --now cm-honeybee-agent
fi

sleep 1
}

Initializer
Copy
Start
80 changes: 79 additions & 1 deletion server/lib/ssh/ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/jollaman999/utils/logger"
"strconv"
"strings"

"github.com/jollaman999/utils/logger"

"github.com/cloud-barista/cm-honeybee/server/pkg/api/rest/model"

"io"
Expand Down Expand Up @@ -169,6 +170,83 @@ func (o *SSH) RunBenchmark(connectionInfo model.ConnectionInfo) ([]model.Benchma
return BenchmarkList, nil
}

func (o *SSH) RunAgent(connectionInfo model.ConnectionInfo) (bool, error) {
err := o.NewClientConn(connectionInfo)
if err != nil {
return false, err
}
defer func() {
o.Close()
}()

// SFTP Client 설정
client, err := sftp.NewClient(o.Options.client)
if err != nil {
logger.Println(logger.ERROR, true, "Failed to SFTP Connect: "+err.Error())
return false, err
}
defer func() {
_ = client.Close()
}()

dstPath := "/tmp/"

files := []string{"sourceFiles/copyAgent.sh"}

for _, file := range files {
fileContents, err := sourceFiles.ReadFile(file)
if err != nil {
logger.Println(logger.ERROR, true, "SSH: Failed to read source file: "+err.Error())
return false, err
}

dstFilePath := filepath.Join(dstPath, strings.Split(file, "/")[1])
dstFile, err := client.Create(dstFilePath)
if err != nil {
logger.Println(logger.ERROR, true, "SSH: Failed to create destination file: "+err.Error())
return false, err
}

logger.Println(logger.DEBUG, true, "SSH: Copying "+file+" to "+dstFilePath)
_, err = io.Copy(dstFile, bytes.NewReader(fileContents))
if err != nil {
log.Fatal("SSH: Failed to File Copy: ", err)
}

output, err := o.RunCmd("chmod +x " + dstFilePath)
if err != nil {
logger.Println(logger.ERROR, true, "SSH: Failed to run command: "+
output+" (Error: "+err.Error())
return false, err
}

_ = dstFile.Close()
}

commands := "/tmp/copyAgent.sh"

logger.Printf(logger.DEBUG, true, "SSH: copyAgent Progressing...\n")
output, err := o.RunCmd("sudo " + commands)
if err != nil {
logger.Println(logger.ERROR, true, "SSH: Failed to run command: "+
output+" (Error: "+err.Error())
return false, err
}

output, err = o.RunCmd("curl -o /dev/null -w '%{http_code}' -X GET http://localhost:8082/honeybee-agent/readyz -H 'accept: application/json'")
if err != nil {
logger.Println(logger.ERROR, true, "SSH: Failed to run command: "+
output+" (Error: "+err.Error())
return false, err
}

if(output == "200") {
return true, nil
}

return false, nil
}

func (o *SSH) getAuthMethods(connectionInfo model.ConnectionInfo) []ssh.AuthMethod {
var methods []ssh.AuthMethod

Expand Down
23 changes: 23 additions & 0 deletions server/pkg/api/rest/controller/benchmarkInfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,26 @@ func RunBenchmarkInfo(c echo.Context) error {

return c.JSONPretty(http.StatusOK, oldSavedBenchmarkInfo, " ")
}

func AgentInitInfo(c echo.Context) error {
connID := c.Param("connId")
if connID == "" {
return common.ReturnErrorMsg(c, "Please provide the connId.")
}

connectionInfo, err := dao.ConnectionInfoGet(connID)
if err != nil {
return common.ReturnErrorMsg(c, err.Error())
}

s := &ssh.SSH{
Options: ssh.DefaultSSHOptions(),
}

data, err := s.RunAgent(*connectionInfo)
if err != nil {
return common.ReturnInternalError(c, err, "Error occurred while getting benchmark information.")
}

return c.JSONPretty(http.StatusOK, data, " ")
}
4 changes: 3 additions & 1 deletion server/pkg/api/rest/route/benchmark.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package route

import (
"strings"

"github.com/cloud-barista/cm-honeybee/server/common"
"github.com/cloud-barista/cm-honeybee/server/pkg/api/rest/controller"
"github.com/labstack/echo/v4"
"strings"
)

func RegisterBenchmark(e *echo.Echo) {
e.GET("/"+strings.ToLower(common.ShortModuleName)+"/bench/:connId", controller.GetBenchmarkInfo)
e.GET("/"+strings.ToLower(common.ShortModuleName)+"/run/bench/:connId", controller.RunBenchmarkInfo)
e.GET("/"+strings.ToLower(common.ShortModuleName)+"/init/agent/:connId", controller.AgentInitInfo)
}

0 comments on commit d34aa3b

Please sign in to comment.