-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
370 lines (324 loc) · 10.1 KB
/
main.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
"github.com/phuslu/log"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/yaml"
)
type HelmIndex struct {
Entries map[string][]struct {
Name string `json:"name"`
Version string `json:"version"`
URLs []string `json:"urls"`
} `json:"entries"`
}
type AppRequest struct {
RepoName string `json:"repoName"`
Package string `json:"package"`
CategoryName string `json:"categoryName"`
Workspace string `json:"workspace"`
AppType string `json:"appType"`
}
var (
versionGVR = schema.GroupVersionResource{
Group: "application.kubesphere.io",
Version: "v2",
Resource: "applicationversions",
}
appGVR = schema.GroupVersionResource{
Group: "application.kubesphere.io",
Version: "v2",
Resource: "applications",
}
mark = "openpitrix-import"
dynamicClient *dynamic.DynamicClient
serverURL string
token string
repoURL string
)
func init() {
log.DefaultLogger = log.Logger{
TimeFormat: "15:04:05",
Caller: 1,
Writer: &log.ConsoleWriter{
ColorOutput: true,
QuoteString: true,
EndWithMessage: true,
},
}
}
func main() {
var rootCmd = &cobra.Command{
Use: "app-tool",
Short: "A CLI tool to manage applications",
Run: func(cmd *cobra.Command, args []string) {
if token == "" {
log.Info().Msg("Using token from /var/run/secrets/kubesphere.io/serviceaccount/token")
dst := "/var/run/secrets/kubesphere.io/serviceaccount/token"
data, err := os.ReadFile(dst)
if err != nil {
log.Fatal().Msgf("Failed to read token file: %v", err)
}
token = string(data)
}
run()
},
}
rootCmd.Flags().StringVar(&serverURL, "server", "", "Kubesphere Server URL (required)")
rootCmd.Flags().StringVar(&repoURL, "repo", "", "Helm index URL (required)")
rootCmd.Flags().StringVar(&token, "token", "", "token (required)")
rootCmd.MarkFlagRequired("server")
rootCmd.MarkFlagRequired("repo")
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func run() {
log.Info().Msgf("Starting to upload to %s ", serverURL)
err := initDynamicClient()
if err != nil {
log.Fatal().Msgf("Failed to initialize dynamic client: %v", err)
}
err = uploadChart()
if err != nil {
log.Fatal().Msgf("Failed to upload chart: %v", err)
}
listOptions := metav1.ListOptions{
LabelSelector: fmt.Sprintf("application.kubesphere.io/app-category-name=%s", mark),
}
err = updateAppStatus(listOptions)
if err != nil {
log.Fatal().Msgf("[1/4] Failed to update app status: %v", err)
}
log.Info().Msgf("[1/4] updateAppStatus completed successfully")
store := map[string]string{"application.kubesphere.io/app-store": "true"}
err = updateAppLabel(listOptions, store)
if err != nil {
log.Fatal().Msgf("[2/4] Failed to update app label: %v", err)
}
log.Info().Msgf("[2/4] updateAppLabel store completed successfully")
err = updateVersionStatus(listOptions)
if err != nil {
log.Fatal().Msgf("[3/4] Failed to update version status: %v", err)
}
log.Info().Msgf("[3/4] updateVersionStatus completed successfully")
categoryName := map[string]string{"application.kubesphere.io/app-category-name": "kubesphere-app-uncategorized"}
err = updateAppLabel(listOptions, categoryName)
if err != nil {
log.Fatal().Msgf("[4/4] Failed to update app category label: %v", err)
}
log.Info().Msgf("[4/4] updateAppLabel categoryName completed successfully")
}
func initDynamicClient() (err error) {
conf := config.GetConfigOrDie()
dynamicClient, err = dynamic.NewForConfig(conf)
if err != nil {
log.Error().Msgf("Failed to create dynamic client: %v", err)
return err
}
log.Info().Msgf("Dynamic client initialized successfully")
return nil
}
func uploadChart() error {
u := fmt.Sprintf("%s/index.yaml", repoURL)
indexData, err := fetchIndex(u)
if err != nil {
log.Error().Msgf("Failed to fetch Helm index: %v", err)
return err
}
for _, entries := range indexData.Entries {
var appID string
for idx, entry := range entries {
chartURL := entry.URLs[0]
chartData, err := fetchChart(chartURL)
if err != nil {
log.Error().Msgf("Failed to fetch chart %s: %v", entry.Name, err)
continue
}
appRequest := AppRequest{
RepoName: "upload",
Package: base64.StdEncoding.EncodeToString(chartData),
CategoryName: mark,
Workspace: "",
AppType: "helm",
}
var url string
if idx == 0 {
url = fmt.Sprintf("%s/kapis/application.kubesphere.io/v2/apps", serverURL)
appID, err = upload(appRequest, entry.Name, entry.Version, url)
if err != nil {
log.Error().Msgf("Failed to post app %s: %v", entry.Name, err)
appID = "" // Reset appID to empty string on failure
continue
}
} else {
if appID == "" {
log.Error().Msgf("Skipping version %s for app %s due to missing appID", entry.Version, entry.Name)
continue
}
url = fmt.Sprintf("%s/kapis/application.kubesphere.io/v2/apps/%s/versions", serverURL, appID)
_, err = upload(appRequest, entry.Name, entry.Version, url)
if err != nil {
log.Error().Msgf("Failed to post app version %s:%s %v", entry.Name, entry.Version, err)
continue
}
}
time.Sleep(200 * time.Millisecond)
}
}
return nil
}
func fetchIndex(url string) (*HelmIndex, error) {
resp, err := http.Get(url)
if err != nil {
log.Error().Msgf("Failed to fetch index: %v", err)
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Error().Msgf("Failed to read response body: %v", err)
return nil, err
}
var index HelmIndex
err = yaml.Unmarshal(body, &index)
if err != nil {
log.Error().Msgf("Failed to unmarshal index: %v", err)
return nil, err
}
return &index, nil
}
func fetchChart(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
log.Error().Msgf("Failed to fetch chart: %v", err)
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Error().Msgf("Failed to read response body: %v", err)
return nil, err
}
return body, nil
}
func upload(appRequest AppRequest, name, version, url string) (appID string, err error) {
jsonData, _ := json.Marshal(appRequest)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
log.Error().Msgf("Failed to create request: %v", err)
return "", err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Error().Msgf("Failed to send request: %v", err)
return "", err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
log.Fatal().Msgf("Failed to find app store manager, please check if it is installed")
return "", fmt.Errorf("please check if app store manager is installed")
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to post app, status code: %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Error().Msgf("Failed to read response body: %v", err)
return "", err
}
var response struct {
AppName string `json:"appName"`
}
err = json.Unmarshal(body, &response)
if err != nil {
log.Error().Msgf("Failed to unmarshal response body:%s, %v", string(body), err)
return "", err
}
log.Info().Msgf("App %s:%s posted successfully", name, version)
return response.AppName, nil
}
func updateVersionStatus(listOptions metav1.ListOptions) error {
list, err := dynamicClient.Resource(appGVR).List(context.TODO(), listOptions)
if err != nil {
log.Error().Msgf("Failed to list apps: %v", err)
return err
}
for _, item := range list.Items {
options := metav1.ListOptions{
LabelSelector: fmt.Sprintf("application.kubesphere.io/app-id=%s", item.GetName()),
}
versionList, err := dynamicClient.Resource(versionGVR).List(context.TODO(), options)
if err != nil {
log.Error().Msgf("Failed to list versions for app %s: %v", item.GetName(), err)
return err
}
for _, versionItem := range versionList.Items {
currentTime := time.Now().UTC().Format(time.RFC3339)
unstructured.SetNestedField(versionItem.Object, currentTime, "status", "updated")
unstructured.SetNestedField(versionItem.Object, "admin", "status", "userName")
unstructured.SetNestedField(versionItem.Object, "active", "status", "state")
_, err := dynamicClient.Resource(versionGVR).UpdateStatus(context.TODO(), &versionItem, metav1.UpdateOptions{})
if err != nil {
log.Error().Msgf("Failed to update version status for app %s: %v", item.GetName(), err)
return err
}
}
}
return nil
}
func updateAppLabel(listOptions metav1.ListOptions, label map[string]string) error {
list, err := dynamicClient.Resource(appGVR).List(context.TODO(), listOptions)
if err != nil {
log.Error().Msgf("Failed to list apps: %v", err)
return err
}
for _, item := range list.Items {
labels := item.GetLabels()
for k, v := range label {
labels[k] = v
}
item.SetLabels(labels)
_, err = dynamicClient.Resource(appGVR).Update(context.TODO(), &item, metav1.UpdateOptions{})
if err != nil {
log.Error().Msgf("Failed to update labels for app %s: %v", item.GetName(), err)
return err
}
}
return nil
}
func updateAppStatus(listOptions metav1.ListOptions) error {
list, err := dynamicClient.Resource(appGVR).List(context.TODO(), listOptions)
if err != nil {
log.Error().Msgf("Failed to list apps: %v", err)
return err
}
for _, item := range list.Items {
currentTime := time.Now().UTC().Format(time.RFC3339)
unstructured.SetNestedField(item.Object, "active", "status", "state")
unstructured.SetNestedField(item.Object, currentTime, "status", "updateTime")
_, err := dynamicClient.Resource(appGVR).UpdateStatus(context.TODO(), &item, metav1.UpdateOptions{})
if err != nil {
log.Error().Msgf("Failed to update status for app %s: %v", item.GetName(), err)
return err
}
}
return nil
}