forked from goodrain/rainbond
/
import_app.go
255 lines (222 loc) · 7.18 KB
/
import_app.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// WUTONG, Application Management Platform
// Copyright (C) 2014-2017 Wutong Co., Ltd.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. For any non-GPL usage of Wutong,
// one or multiple Commercial Licenses authorized by Wutong Co., Ltd.
// must be obtained first.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package exector
import (
"encoding/json"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/wutong-paas/wutong-oam/pkg/localimport"
"github.com/wutong-paas/wutong-oam/pkg/ram/v1alpha1"
"github.com/wutong-paas/wutong/api/model"
"github.com/wutong-paas/wutong/chaos"
"github.com/wutong-paas/wutong/chaos/sources"
"github.com/wutong-paas/wutong/db"
"github.com/wutong-paas/wutong/event"
)
func init() {
RegisterWorker("import_app", NewImportApp)
}
// ImportApp Export app to specified format(wutong-app or dockercompose)
type ImportApp struct {
EventID string `json:"event_id"`
Format string `json:"format"`
SourceDir string `json:"source_dir"`
Apps []string `json:"apps"`
ServiceImage model.ServiceImage `json:"service_image"`
Logger event.Logger
oldAPPPath map[string]string
oldPluginPath map[string]string
// ContainerdCli export.ContainerdAPI
ImageClient sources.ImageClient
}
// NewImportApp create
func NewImportApp(in []byte, m *exectorManager) (TaskWorker, error) {
var importApp ImportApp
if err := json.Unmarshal(in, &importApp); err != nil {
return nil, err
}
if importApp.ServiceImage.HubURL == "" || importApp.ServiceImage.HubURL == "wutong.me" {
importApp.ServiceImage.HubURL = chaos.REGISTRYDOMAIN
importApp.ServiceImage.HubUser = chaos.REGISTRYUSER
importApp.ServiceImage.HubPassword = chaos.REGISTRYPASS
}
logrus.Infof("load app image to hub %s", importApp.ServiceImage.HubURL)
importApp.Logger = event.GetManager().GetLogger(importApp.EventID)
// importApp.ContainerdCli = m.ContainerdCli
importApp.ImageClient = m.imageClient
importApp.oldAPPPath = make(map[string]string)
importApp.oldPluginPath = make(map[string]string)
return &importApp, nil
}
// Stop stop
func (i *ImportApp) Stop() error {
return nil
}
// Name return worker name
func (i *ImportApp) Name() string {
return "import_app"
}
// GetLogger GetLogger
func (i *ImportApp) GetLogger() event.Logger {
return i.Logger
}
// ErrorCallBack if run error will callback
func (i *ImportApp) ErrorCallBack(err error) {
i.updateStatus("failed")
}
// Run Run
func (i *ImportApp) Run(timeout time.Duration) error {
if i.Format == "wutong-app" {
err := i.importApp()
if err != nil {
logrus.Errorf("load wutong app failure %s", err.Error())
return err
}
return nil
}
return errors.New("Unsupported the format: " + i.Format)
}
// importApp import app
// support batch import
func (i *ImportApp) importApp() error {
oldSourceDir := i.SourceDir
var datas []v1alpha1.WutongApplicationConfig
for _, app := range i.Apps {
appFile := filepath.Join(oldSourceDir, app)
tmpDir := path.Join(oldSourceDir, app+"-cache")
li, err := localimport.New(logrus.StandardLogger(), i.ImageClient.GetContainerdClient(), i.ImageClient.GetDockerClient(), tmpDir)
if err != nil {
logrus.Errorf("create localimport failure %s", err.Error())
i.updateStatusForApp(app, "failed")
continue
}
if err := i.updateStatusForApp(app, "importing"); err != nil {
logrus.Errorf("Failed to update status to importing for app %s: %v", app, err)
}
ram, err := li.Import(appFile, v1alpha1.ImageInfo{
HubURL: i.ServiceImage.HubURL,
HubUser: i.ServiceImage.HubUser,
HubPassword: i.ServiceImage.HubPassword,
Namespace: i.ServiceImage.NameSpace,
})
if err != nil {
logrus.Errorf("Failed to load app %s: %v", appFile, err)
i.updateStatusForApp(app, "failed")
continue
}
i.updateStatusForApp(app, "success")
// copy(appFile, appFile+".success")
// os.Rename(appFile, appFile+".success")
datas = append(datas, *ram)
logrus.Infof("Successful import app: %s", appFile)
os.Remove(tmpDir)
}
metadatasFile := fmt.Sprintf("%s/metadatas.json", i.SourceDir)
dataBytes, _ := json.Marshal(datas)
if err := os.WriteFile(metadatasFile, []byte(dataBytes), 0644); err != nil {
logrus.Errorf("Failed to load apps %s: %v", i.SourceDir, err)
return err
}
if err := i.updateStatus("success"); err != nil {
logrus.Errorf("Failed to load apps %s: %v", i.SourceDir, err)
return err
}
return nil
}
func (i *ImportApp) updateStatus(status string) error {
logrus.Debug("Update app status in database to: ", status)
// 从数据库中获取该应用的状态信息
res, err := db.GetManager().AppDao().GetByEventId(i.EventID)
if err != nil {
err = fmt.Errorf("failed to get app %s from db: %s", i.EventID, err.Error())
logrus.Error(err)
return err
}
// 在数据库中更新该应用的状态信息
res.Status = status
if err := db.GetManager().AppDao().UpdateModel(res); err != nil {
err = fmt.Errorf("failed to update app %s: %s", i.EventID, err.Error())
logrus.Error(err)
return err
}
return nil
}
func (i *ImportApp) updateStatusForApp(app, status string) error {
logrus.Debugf("Update status in database for app %s to: %s", app, status)
// 从数据库中获取该应用的状态信息
res, err := db.GetManager().AppDao().GetByEventId(i.EventID)
if err != nil {
err = fmt.Errorf("failed to get app %s from db: %s", i.EventID, err.Error())
logrus.Error(err)
return err
}
// 在数据库中更新该应用的状态信息
appsMap := str2map(res.Apps)
appsMap[app] = status
res.Apps = map2str(appsMap)
if err := db.GetManager().AppDao().UpdateModel(res); err != nil {
err = fmt.Errorf("failed to update app %s: %s", i.EventID, err.Error())
logrus.Error(err)
return err
}
return nil
}
func str2map(str string) map[string]string {
result := make(map[string]string, 10)
for _, app := range strings.Split(str, ",") {
appMap := strings.Split(app, ":")
result[appMap[0]] = appMap[1]
}
return result
}
func map2str(m map[string]string) string {
var result string
for k, v := range m {
kv := k + ":" + v
if result == "" {
result += kv
} else {
result += "," + kv
}
}
return result
}
// func copy(src, dst string) (int64, error) {
// sourceFileStat, err := os.Stat(src)
// if err != nil {
// return 0, err
// }
// if !sourceFileStat.Mode().IsRegular() {
// return 0, fmt.Errorf("%s is not a regular file", src)
// }
// source, err := os.Open(src)
// if err != nil {
// return 0, err
// }
// defer source.Close()
// destination, err := os.Create(dst)
// if err != nil {
// return 0, err
// }
// defer destination.Close()
// nBytes, err := io.Copy(destination, source)
// return nBytes, err
// }