/
godoc_deployer.go
260 lines (226 loc) · 7.66 KB
/
godoc_deployer.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
/*
Copyright 2018 The Kubernetes authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pullrequest
import (
"context"
"fmt"
"log"
"net/url"
"strconv"
"strings"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
"sigs.k8s.io/controller-tools/examples/godocbot/pkg/apis/code/v1alpha1"
)
// GodocDeployer watches PullRequest object which have a commitID specified in
// their Spec and deploys a Godoc deployment which runs godoc server for the PR.
// It watches the PullRequest object for changes in commitID and reconciles the
// generated godoc deployment. CommitID for PRs is updated by GithubSyncer
// module.
type GodocDeployer struct {
controller.Controller
}
func NewGodocDeployer(mgr manager.Manager) (*GodocDeployer, error) {
prReconciler := &pullRequestReconciler{
Client: mgr.GetClient(),
scheme: mgr.GetScheme(),
}
// Setup a new controller to Reconcile PullRequests
c, err := controller.New("pull-request-controller", mgr, controller.Options{Reconcile: prReconciler})
if err != nil {
return nil, err
}
// Watch PullRequest objects
err = c.Watch(
&source.Kind{Type: &v1alpha1.PullRequest{}},
&handler.Enqueue{})
if err != nil {
return nil, err
}
// Watch deployments generated for PullRequests objects
err = c.Watch(
&source.Kind{Type: &appsv1.Deployment{}},
&handler.EnqueueOwner{
OwnerType: &v1alpha1.PullRequest{},
IsController: true,
},
)
if err != nil {
return nil, err
}
return &GodocDeployer{Controller: c}, nil
}
// pullRequestReconciler ensures there is a godoc deployment is running with
// the commitID specified in the PullRequest object.
type pullRequestReconciler struct {
Client client.Client
scheme *runtime.Scheme
}
func (r *pullRequestReconciler) Reconcile(request reconcile.Request) (reconcile.Result, error) {
ctx := context.Background()
// Fetch PullRequest object
pr := &v1alpha1.PullRequest{}
err := r.Client.Get(ctx, request.NamespacedName, pr)
if errors.IsNotFound(err) {
log.Printf("Could not find PullRequest %v.\n", request)
return reconcile.Result{}, nil
}
if err != nil {
log.Printf("Could not fetch PullRequest %v for %+v\n", err, request)
return reconcile.Result{}, err
}
if pr.Spec.CommitID == "" {
log.Printf("Waiting for PR %s commitID to be updated", request.NamespacedName)
return reconcile.Result{}, nil
}
dp := &appsv1.Deployment{}
err = r.Client.Get(ctx, request.NamespacedName, dp)
if err != nil {
if !errors.IsNotFound(err) {
return reconcile.Result{}, err
}
log.Printf("Could not find deployment for PullRequest %v. creating deployment", request)
dp, err = deploymentForPullRequest(pr, r.scheme)
if err != nil {
log.Printf("error creating new deployment for PullRequest: %v %v", request, err)
return reconcile.Result{}, nil
}
if err = r.Client.Create(ctx, dp); err != nil {
log.Printf("error creating new deployment for PullRequest: %v %v", request, err)
return reconcile.Result{}, err
}
}
prinfo, _ := parsePullRequestURL(pr.Spec.URL)
prinfo.commitID = pr.Spec.CommitID
if len(dp.Spec.Template.Spec.Containers[0].Args) > 5 && (pr.Spec.CommitID != dp.Spec.Template.Spec.Containers[0].Args[5]) {
// TODO(droot): publish an event when commit is updated.
// deployment is not updated with latest commit-id
dp.Spec.Template.Spec.Containers[0].Args = prinfo.godocContainerArgs()
if err = r.Client.Update(ctx, dp); err != nil {
log.Printf("error updating the deployment for key %s", request.NamespacedName)
return reconcile.Result{}, err
}
}
if pr.Status.GoDocLink == "" && dp.Status.AvailableReplicas > 0 {
log.Printf("deployment became available, updating the godoc link")
// update the status
pr.Status.GoDocLink = fmt.Sprintf("https://%s.serveo.net/pkg/%s/%s/%s", prinfo.subdomain(), prinfo.host, prinfo.org, prinfo.repo)
if err = r.Client.Update(ctx, pr); err != nil {
return reconcile.Result{}, err
}
log.Printf("godoc link updated successfully for pr %v", request.NamespacedName)
}
return reconcile.Result{}, nil
}
// deploymentForPullRequest creates a deployment object for a given PullRequest.
func deploymentForPullRequest(pr *v1alpha1.PullRequest, scheme *runtime.Scheme) (*appsv1.Deployment, error) {
// we are good with running with one replica
var replicas int32 = 1
prinfo, err := parsePullRequestURL(pr.Spec.URL)
if err != nil {
return nil, err
}
prinfo.commitID = pr.Spec.CommitID
labels := map[string]string{
"org": prinfo.org,
"repo": prinfo.repo,
}
tunnelArgs := "80:localhost:6060"
tunnelArgs = fmt.Sprintf("%s:%s", prinfo.subdomain(), tunnelArgs)
dep := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: pr.Name,
Namespace: pr.Namespace,
},
Spec: appsv1.DeploymentSpec{
Replicas: &replicas,
Selector: &metav1.LabelSelector{
MatchLabels: labels,
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: labels,
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Image: "gcr.io/sunilarora-sandbox/godoc:0.0.1",
Name: "godoc",
ImagePullPolicy: "Always",
Command: []string{"/bin/bash"},
Args: prinfo.godocContainerArgs(),
},
{
Image: "gcr.io/sunilarora-sandbox/ssh-client:0.0.2",
Name: "ssh",
ImagePullPolicy: "Always",
Command: []string{"ssh"},
Args: []string{"-tt", "-o", "StrictHostKeyChecking=no", "-R", tunnelArgs, "serveo.net"},
},
},
},
},
},
}
controllerutil.SetControllerReference(pr, dep, scheme)
return dep, nil
}
// prInfo is an structure to represent PullRequest info. It will be used
// internally to more as an convenience for passing it around.
type prInfo struct {
host string
org string
repo string
pr int64
commitID string
}
// parsePullRequestURL parses given PullRequest URL into prInfo instance.
// An example pull request URL looks like:
// https://github.com/kubernetes-sigs/controller-runtime/pull/15
func parsePullRequestURL(prURL string) (*prInfo, error) {
u, err := url.Parse(prURL)
if err != nil {
return nil, err
}
parts := strings.Split(strings.TrimPrefix(u.Path, "/"), "/")
if len(parts) < 4 || parts[2] != "pull" {
return nil, fmt.Errorf("pr info missing in the URL")
}
prNum, err := strconv.ParseInt(parts[3], 10, 64)
if err != nil {
return nil, err
}
return &prInfo{
host: u.Hostname(),
org: parts[0],
repo: parts[1],
pr: prNum,
}, nil
}
// helper function to generate subdomain for the prinfo.
func (pr *prInfo) subdomain() string {
return fmt.Sprintf("%s-%s-pr-%d", pr.org, pr.repo, pr.pr)
}
func (pr *prInfo) godocContainerArgs() []string {
return []string{"fetch_serve.sh", pr.host, pr.org, pr.repo, strconv.FormatInt(pr.pr, 10), pr.commitID}
}