/
app_manage.go
99 lines (81 loc) · 2.41 KB
/
app_manage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package external
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/IceWhaleTech/CasaOS-Common/model"
http2 "github.com/IceWhaleTech/CasaOS-Common/utils/http"
"github.com/tidwall/gjson"
)
const (
AppManageURLFilename = "app-management.url"
APIComposeInfo = "/v2/app_management/compose"
APIComposeStatus = "/v2/app_management/compose"
)
type AppManageService interface {
GetAppInfo(storeId string) (model.ComposeAppWithStoreInfo, error)
PutAppStatus(storeId string, status string) (bool, error)
}
type appManageService struct {
address string
}
func (m *appManageService) GetAppInfo(storeId string) (model.ComposeAppWithStoreInfo, error) {
url := strings.TrimSuffix(m.address, "/") + APIComposeInfo + "/" + storeId
model := model.ComposeAppWithStoreInfo{}
response, err := http2.Get(url, 30*time.Second)
if err != nil {
return model, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return model, errors.New("failed to create route (status code: " + fmt.Sprint(response.StatusCode) + ")")
}
str, err := io.ReadAll(response.Body)
if err != nil {
return model, err
}
defer response.Body.Close()
gstr := gjson.Get(string(str), "data")
err = json.Unmarshal([]byte(gstr.Raw), &model)
return model, err
}
func (m *appManageService) PutAppStatus(storeId string, status string) (bool, error) {
url := strings.TrimSuffix(m.address, "/") + APIComposeStatus + "/" + storeId + "/status"
body := []byte(`"` + status + `"`)
response, err := http2.Put(url, body, 30*time.Second)
if err != nil {
return false, err
}
if response.StatusCode != http.StatusOK {
return false, errors.New("failed to change status (status code: " + fmt.Sprint(response.StatusCode) + ")")
}
return true, nil
}
func NewAppManageService(RuntimePath string) (AppManageService, error) {
managementAddressFile := filepath.Join(RuntimePath, AppManageURLFilename)
retry := 10
for retry > 0 {
if _, err := os.Stat(managementAddressFile); err == nil {
break
}
fmt.Printf("gateway management address file `%s` not found, retrying in 1 second...(%d)\n", managementAddressFile, retry)
time.Sleep(1 * time.Second)
retry--
}
address, err := getAddress(managementAddressFile)
if err != nil {
return nil, err
}
if err := ping(address, 30*time.Second); err != nil {
return nil, err
}
return &appManageService{
address: address,
}, nil
}