-
Notifications
You must be signed in to change notification settings - Fork 90
/
schemahero.go
80 lines (64 loc) · 2.32 KB
/
schemahero.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
package kotsadm
import (
"bytes"
"time"
"github.com/pkg/errors"
"github.com/replicatedhq/kots/pkg/logger"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
)
func getMigrationsYAML(deployOptions DeployOptions) (map[string][]byte, error) {
docs := map[string][]byte{}
s := json.NewYAMLSerializer(json.DefaultMetaFactory, scheme.Scheme, scheme.Scheme)
var pod bytes.Buffer
if err := s.Encode(migrationsPod(deployOptions), &pod); err != nil {
return nil, errors.Wrap(err, "failed to marshal migrations pod")
}
docs["migrations.yaml"] = pod.Bytes()
return docs, nil
}
func runSchemaHeroMigrations(deployOptions DeployOptions, clientset *kubernetes.Clientset) error {
// we don't deploy the operator because that would require too high of
// a priv. so we just deploy database migrations here, at deployment time
// find a ready postgres container
log := logger.NewLogger()
log.ChildActionWithSpinner("Waiting for datastore to be ready")
_, err := waitForHealthyPostgres(deployOptions.Namespace, clientset)
if err != nil {
return errors.Wrap(err, "failed to find healthy postgres pod")
}
log.FinishChildSpinner()
// Deploy the migration pod with an informer attached to clean it up
if err := createSchemaHeroPod(deployOptions, clientset); err != nil {
return errors.Wrap(err, "failed to create schemahero pod")
}
return nil
}
func waitForHealthyPostgres(namespace string, clientset *kubernetes.Clientset) (string, error) {
start := time.Now()
for {
pods, err := clientset.CoreV1().Pods(namespace).List(metav1.ListOptions{LabelSelector: "app=kotsadm-postgres"})
if err != nil {
return "", errors.Wrap(err, "failed to list pods")
}
for _, pod := range pods.Items {
if pod.Status.Phase == corev1.PodRunning {
return pod.Name, nil
}
}
time.Sleep(time.Second)
if time.Now().Sub(start) > time.Duration(time.Minute) {
return "", errors.New("timeout waiting for postgres pod")
}
}
}
func createSchemaHeroPod(deployOptions DeployOptions, clientset *kubernetes.Clientset) error {
_, err := clientset.CoreV1().Pods(deployOptions.Namespace).Create(migrationsPod(deployOptions))
if err != nil {
return errors.Wrap(err, "failed to create pod")
}
return nil
}