-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
225 lines (198 loc) · 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
package main
import (
"bytes"
"context"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"os/signal"
"strings"
"sync"
"time"
"github.com/fluxcd/pkg/untar"
flag "github.com/spf13/pflag"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/config"
)
var (
localPort int
serviceName string
serviceNamespace string
servicePort int
revision string
sourceType string
sourceName string
sourceNamespace string
allowedTypes = []string{"gitrepository", "helmchart"}
)
func main() {
allowedTypesString := strings.Join(allowedTypes, ", ")
flag.IntVar(&localPort, "local-port", 8080, "local port for port-forward")
flag.StringVar(&sourceName, "name", "", "Source name")
flag.StringVar(&sourceNamespace, "namespace", "flux-system", "Source namespace")
flag.StringVar(&revision, "revision", "latest", "Source revision")
flag.StringVar(&serviceName, "service-name", "source-controller", "service name")
flag.StringVar(&serviceNamespace, "service-namespace", "flux-system", "service namespace")
flag.IntVar(&servicePort, "service-port", 80, "service port for port-forward")
flag.StringVar(&sourceType, "source-type", "gitrepository", "type of source to use: "+allowedTypesString)
flag.Parse()
if !contains(allowedTypes, sourceType) {
log.Fatalf("--source-type %q not allowed, must be one of: %s", sourceType, allowedTypesString)
}
if sourceName == "" || sourceNamespace == "" {
log.Fatal("--name and --namespace flags are mandatory")
}
// Start port forwarding
var wg sync.WaitGroup
interrupt := make(chan os.Signal, 1)
{
log.Printf(
"Starting port forwarding to %s/%s %d:%d...",
serviceNamespace, serviceName, localPort, servicePort,
)
signal.Notify(interrupt, os.Interrupt)
cmd := exec.Command(
"kubectl",
"port-forward",
"-n",
serviceNamespace,
fmt.Sprintf("svc/%s", serviceName),
fmt.Sprintf("%d:%d", localPort, servicePort),
)
wg.Add(1)
go func() {
err := cmd.Start()
if err != nil {
log.Fatal(err)
}
s := <-interrupt
err = cmd.Process.Signal(s)
if err != nil {
log.Fatal(err)
}
log.Println("Ended port forwarding")
wg.Done()
}()
}
// wait a second for port-forwarding to be established
time.Sleep(3 * time.Second)
// download and untar the artifact
dir, err := os.MkdirTemp(
"",
fmt.Sprintf("%s-%s-%s-*", sourceNamespace, sourceName, revision),
)
if err != nil {
interrupt <- os.Interrupt
wg.Wait()
log.Fatal(err)
}
log.Println("Downloading and untarring the source...")
var url string
switch sourceType {
case "gitrepository":
url = gitrepositoryURL()
case "helmchart":
url, err = helmchartURL()
if err != nil {
log.Fatal(err)
}
}
err = downloadSource(dir, url)
if err != nil {
interrupt <- os.Interrupt
wg.Wait()
log.Fatal(err)
}
// end port forwarding
interrupt <- os.Interrupt
wg.Wait()
}
func gitrepositoryURL() string {
return fmt.Sprintf(
"http://localhost:%d/%s/%s/%s/%s.tar.gz",
localPort, sourceType, sourceNamespace, sourceName, revision,
)
}
func helmchartURL() (string, error) {
log.Println("Getting URL from the HelmChart...")
conf := config.GetConfigOrDie()
// avoid annoying client-side throttling
conf.QPS = 50
conf.Burst = 100
c, err := client.New(conf, client.Options{})
if err != nil {
return "", err
}
u := &unstructured.Unstructured{}
u.SetGroupVersionKind(schema.GroupVersionKind{
Group: "source.toolkit.fluxcd.io",
Kind: "HelmChart",
Version: "v1beta1",
})
err = c.Get(
context.Background(),
client.ObjectKey{
Namespace: sourceNamespace,
Name: sourceName,
},
u,
)
if err != nil {
return "", err
}
url, ok, err := unstructured.NestedString(u.Object, "status", "url")
if err != nil {
return "", err
}
if !ok {
return "", fmt.Errorf(".status.url not set")
}
// get rid of in-cluster service address
urlElements := strings.SplitN(url, "/", 4)
url = fmt.Sprintf("http://localhost:%d/%s", localPort, urlElements[len(urlElements)-1])
// change "latest" to required revision
url = strings.Replace(url, "latest.tgz", fmt.Sprintf("%s.tgz", revision), 1)
return url, nil
}
func downloadSource(dir, url string) error {
client := &http.Client{Timeout: 15 * time.Second}
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
response, err := client.Do(request)
if err != nil {
return err
}
if response.StatusCode != http.StatusOK {
return fmt.Errorf(
"error calling %q: expected %d, got %d",
request.URL, http.StatusOK, response.StatusCode,
)
}
defer response.Body.Close()
var buf bytes.Buffer
_, err = io.Copy(&buf, response.Body)
if err != nil {
return err
}
log.Printf("Downloaded %q", request.URL)
if _, err = untar.Untar(&buf, dir); err != nil {
return err
}
log.Printf("Untarred in %q", dir)
return nil
}
func contains(slice []string, s string) bool {
for _, x := range slice {
if x == s {
return true
}
}
return false
}