-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
316 lines (242 loc) · 8.5 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
package main
import (
"bytes"
"context"
"flag"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"time"
"github.com/goharbor/go-client/pkg/harbor"
assistClient "github.com/goharbor/go-client/pkg/sdk/assist/client"
"github.com/goharbor/go-client/pkg/sdk/assist/client/chart_repository"
"github.com/goharbor/go-client/pkg/sdk/v2.0/client"
"github.com/goharbor/go-client/pkg/sdk/v2.0/client/project"
"github.com/pkg/errors"
"github.com/schollz/progressbar/v3"
)
type HelmChart struct {
Name string
Project string
Version string
}
func (hc HelmChart) ChartFileName() string {
return fmt.Sprintf("%s-%s.tgz", hc.Name, hc.Version)
}
type ProjectsToMigrateList []string
const (
fileMode = 0o600
helmBinaryPath = "helm"
timeout = 5 * time.Second
defaultPageSize = 10
)
var (
harborClientV2 *client.HarborAPI //nolint:gochecknoglobals
harborClientV2Assist *assistClient.HarborAPI //nolint:gochecknoglobals
harborURL string //nolint:gochecknoglobals
harborUsername string //nolint:gochecknoglobals
harborPassword string //nolint:gochecknoglobals
harborHost string //nolint:gochecknoglobals
destPath string //nolint:gochecknoglobals
projectsToMigrate ProjectsToMigrateList //nolint:gochecknoglobals
)
func init() { //nolint:gochecknoinits
initFlags()
initHarborClients()
initHarborHost()
}
func initFlags() {
flag.StringVar(&harborURL, "url", "", "Harbor registry url")
flag.StringVar(&harborUsername, "username", "", "Harbor registry username")
flag.StringVar(&harborPassword, "password", "", "Harbor registry password")
flag.StringVar(&destPath, "destpath", "", "Destination subpath")
flag.Var(&projectsToMigrate, "project", "Name of the project(s) to migrate")
flag.Parse()
if harborURL == "" {
log.Fatal(errors.New("Missing required --url flag"))
}
if harborUsername == "" {
log.Fatal(errors.New("Missing required --username flag"))
}
if harborPassword == "" {
log.Fatal(errors.New("Missing required --password flag"))
}
}
func initHarborClients() {
config := &harbor.ClientSetConfig{
URL: harborURL,
Insecure: false,
Username: harborUsername,
Password: harborPassword,
}
harborClientSet, err := harbor.NewClientSet(config)
if err != nil {
log.Fatal(err, errors.Wrap(err, "fail to create harbor client"))
}
harborClientV2 = harborClientSet.V2() // v2 client
harborClientV2Assist = harborClientSet.Assist()
// Check Harbor url and credentials are ok
params := &project.ListProjectsParams{} //nolint:exhaustruct
if _, err = harborClientV2.Project.ListProjects(context.Background(), params); err != nil {
log.Fatal(errors.Wrap(err, "fail to contact Harbor registry, check your credentials"))
}
}
func initHarborHost() {
u, err := url.Parse(harborURL)
if err != nil {
log.Fatal(errors.Wrapf(err, "fail to parse Harbor URL"))
}
harborHost = u.Host
}
func main() {
if err := helmLogin(); err != nil {
log.Fatal(errors.Wrapf(err, "fail to login to Helm"))
}
helmChartsToMigrate, err := getHarborChartmuseumCharts()
if err != nil {
log.Fatal(errors.Wrapf(err, "fail to retrieve helm charts to migrate"))
}
log.Printf("%d Helm charts to migrate from Chartmuseum to OCI", len(helmChartsToMigrate))
bar := progressbar.Default(int64(len(helmChartsToMigrate)))
errorCount := 0
for _, helmChart := range helmChartsToMigrate {
_ = bar.Add(1)
if err := migrateChartFromChartmuseumToOCI(helmChart); err != nil {
errorCount++
log.Println(errors.Wrapf(err, "fail to migrate helm chart"))
}
}
log.Printf("%d Helm charts successfully migrated from Chartmuseum to OCI", len(helmChartsToMigrate)-errorCount)
}
func helmLogin() error {
cmd := exec.Command(helmBinaryPath, "registry", "login", "--username", harborUsername, "--password", harborPassword, harborURL) //nolint:lll
var stdErr bytes.Buffer
cmd.Stderr = &stdErr
if err := cmd.Run(); err != nil {
return errors.Wrapf(err, "fail to execute helm login' command: %s", stdErr.String())
}
return nil
}
func getHarborChartmuseumCharts() ([]HelmChart, error) {
helmCharts := make([]HelmChart, 0)
pageSize := int64(defaultPageSize)
for page := int64(1); true; page++ {
params := &project.ListProjectsParams{Page: &page, PageSize: &pageSize} //nolint:exhaustruct
projects, err := harborClientV2.Project.ListProjects(context.Background(), params)
if err != nil {
log.Fatal(errors.Wrapf(err, "fail to list harbor projects of page %d", page))
}
for _, harborProject := range projects.Payload {
if len(projectsToMigrate) > 0 && !projectsToMigrate.Includes(harborProject.Name) {
continue
}
projectHelmCharts, err := getHarborProjectChartmuseumCharts(harborProject.Name)
if err != nil {
return nil, errors.Wrapf(err, "fail to migrate charts from project %s", harborProject.Name)
}
helmCharts = append(helmCharts, projectHelmCharts...)
}
if projects.XTotalCount <= page**params.PageSize {
break
}
}
return helmCharts, nil
}
func getHarborProjectChartmuseumCharts(projectName string) ([]HelmChart, error) {
helmCharts := make([]HelmChart, 0)
params := &chart_repository.GetChartrepoRepoChartsParams{Repo: projectName} //nolint:exhaustruct
charts, err := harborClientV2Assist.ChartRepository.GetChartrepoRepoCharts(context.Background(), params)
if err != nil {
return nil, errors.Wrap(err, "fail to list harbor projects")
}
for _, chart := range charts.Payload {
params := &chart_repository.GetChartrepoRepoChartsNameParams{ //nolint:exhaustruct
Repo: projectName,
Name: *chart.Name,
}
chartVersions, err := harborClientV2Assist.ChartRepository.GetChartrepoRepoChartsName(context.Background(), params)
if err != nil {
return nil, errors.Wrapf(err, "fail to get chart %s in project %s", *chart.Name, projectName)
}
for _, chartVersion := range chartVersions.Payload {
helmChart := HelmChart{
Project: projectName,
Name: *chart.Name,
Version: *chartVersion.Version,
}
helmCharts = append(helmCharts, helmChart)
}
}
return helmCharts, nil
}
func migrateChartFromChartmuseumToOCI(helmChart HelmChart) error {
if err := pullChartFromChartmuseum(helmChart); err != nil {
return errors.Wrapf(err, "fail to pull chart from chartmuseum")
}
if err := pushChartToOCI(helmChart); err != nil {
return errors.Wrapf(err, "fail to push chart to OCI")
}
if err := removeChartFile(helmChart); err != nil {
return errors.Wrapf(err, "fail to remove chart file")
}
return nil
}
func pullChartFromChartmuseum(helmChart HelmChart) error {
chartFileName := helmChart.ChartFileName()
url := fmt.Sprintf("%s/chartrepo/%s/charts/%s", harborURL, helmChart.Project, chartFileName)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, http.NoBody)
if err != nil {
return errors.Wrapf(err, "fail to pull chart from Chartmuseum: %s", url)
}
req.SetBasicAuth(harborUsername, harborPassword)
httpClient := http.Client{Timeout: timeout} //nolint:exhaustruct
res, err := httpClient.Do(req)
if err != nil {
return errors.Wrapf(err, "fail to retrieve chart from chartmuseum: %s", url)
}
if res.StatusCode != http.StatusOK {
err := fmt.Errorf("received status %d", res.StatusCode) //nolint:goerr113
return errors.Wrapf(err, "fail to retrieve chart from chartmuseum: %s", url)
}
defer res.Body.Close()
resBody, err := io.ReadAll(res.Body)
if err != nil {
return errors.Wrapf(err, "fail to read chart body: %s", url)
}
err = os.WriteFile(chartFileName, resBody, fileMode)
return errors.Wrapf(err, "fail to write chart file to disk: %s", url)
}
func pushChartToOCI(helmChart HelmChart) error {
repoURL := fmt.Sprintf("oci://%s/%s%s", harborHost, helmChart.Project, destPath)
cmd := exec.Command(helmBinaryPath, "push", helmChart.ChartFileName(), repoURL) //nolint:gosec
var stdErr bytes.Buffer
cmd.Stderr = &stdErr
if err := cmd.Run(); err != nil {
return errors.Wrapf(err, "fail to execute helm push' command: %s for url: %s and file: %s", stdErr.String(), repoURL, helmChart.ChartFileName()) //nolint:lll
}
return nil
}
func removeChartFile(helmChart HelmChart) error {
chartFileName := helmChart.ChartFileName()
err := os.Remove(chartFileName)
return errors.Wrapf(err, "fail to delete file %s", chartFileName)
}
func (l *ProjectsToMigrateList) Set(value string) error {
*l = append(*l, value)
return nil
}
func (l *ProjectsToMigrateList) String() string {
return ""
}
func (l ProjectsToMigrateList) Includes(a string) bool {
for _, b := range l {
if b == a {
return true
}
}
return false
}