This repository has been archived by the owner on Nov 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
build.go
238 lines (207 loc) · 6.21 KB
/
build.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
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
cpy "github.com/otiai10/copy"
"github.com/pkg/errors"
apiv1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// Build builds a chaincode on Kubernetes
func Build(ctx context.Context, cfg Config) error {
log.Println("Procedure: build")
if len(os.Args) != 4 {
return errors.New("build requires exactly three arguments")
}
sourceDir := os.Args[1]
metadataDir := os.Args[2]
outputDir := os.Args[3]
// Get metadata
metadata, err := getMetadata(metadataDir)
if err != nil {
return errors.Wrap(err, "getting metadata for chaincode")
}
metadata.Label = strings.ToLower(metadata.Label)
// Create transfer directory
copyOpts := cpy.Options{AddPermission: os.ModePerm}
prefix, _ := os.Hostname()
transferdir, err := ioutil.TempDir(cfg.TransferVolume.Path, prefix)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("creating directory %s on transfer volume", cfg.TransferVolume.Path))
}
defer os.RemoveAll(transferdir) // Cleanup transfer directory when this process ends
// Setup transfer
transferSrc := filepath.Join(transferdir, "src")
transferSrcMeta := filepath.Join(sourceDir, "META-INF")
transferBld := filepath.Join(transferdir, "bld")
buildInfoFile := filepath.Join(outputDir, "k8scc_buildinfo.json")
// Copy source
err = cpy.Copy(sourceDir, transferSrc, copyOpts)
if err != nil {
return errors.Wrap(err, "copy source dir in the transfer dir")
}
// Create output directory
err = os.Mkdir(transferBld, os.ModePerm)
if err != nil {
return errors.Wrap(err, "create output dir in the transfer dir")
}
err = os.Chmod(transferBld, os.ModePerm)
if err != nil {
return errors.Wrap(err, "chmod on output dir in the transfer dir")
}
// Create builder Pod
pod, err := createBuilderPod(ctx, cfg, metadata, filepath.Base(transferdir))
if err != nil {
return errors.Wrap(err, "creating builder pod")
}
defer cleanupPodSilent(pod)
// Watch builder Pod for completion or failure
podSucceeded, err := watchPodUntilCompletion(ctx, pod)
if err != nil {
return errors.Wrap(err, "watching builder pod")
}
if !podSucceeded {
return fmt.Errorf("build of Chaincode %s in Pod %s failed", metadata.Label, pod.Name)
}
// Copy data from transfer pv to original output destination
err = cpy.Copy(transferBld, outputDir)
if err != nil {
return errors.Wrap(err, "copy build artifacts from transfer")
}
// Copy META-INF, if available
if _, err := os.Stat(transferSrcMeta); !os.IsNotExist(err) {
err = cpy.Copy(transferSrcMeta, outputDir)
if err != nil {
return errors.Wrap(err, "copy META-INF to output dir")
}
}
// Create build information
buildInformation := BuildInformation{
Image: pod.Spec.Containers[0].Image,
Platform: metadata.Type,
}
bi, err := json.Marshal(buildInformation)
if err != nil {
return errors.Wrap(err, "marshaling BuildInformation")
}
err = ioutil.WriteFile(buildInfoFile, bi, os.ModePerm)
if err != nil {
return errors.Wrap(err, "writing BuildInformation")
}
err = os.Chmod(buildInfoFile, os.ModePerm)
if err != nil {
return errors.Wrap(err, "changing permissions of BuildInformation")
}
return nil
}
func createBuilderPod(ctx context.Context,
cfg Config, metadata *ChaincodeMetadata, transferPVPrefix string) (*apiv1.Pod, error) {
// Setup kubernetes client
clientset, err := getKubernetesClientset()
if err != nil {
return nil, errors.Wrap(err, "getting kubernetes clientset")
}
// Get builder image
image, ok := cfg.Images[metadata.Type]
if !ok {
return nil, fmt.Errorf("no builder image available for %q", metadata.Type)
}
// Get platform informations from hyperledger
plt := GetPlatform(metadata.Type)
if plt == nil {
return nil, fmt.Errorf("platform %q not supported by Hyperledger Fabric", metadata.Type)
}
buildOpts, err := plt.DockerBuildOptions(metadata.Path)
if err != nil {
return nil, errors.Wrap(err, "getting build options for platform")
}
envvars := []apiv1.EnvVar{}
for _, env := range buildOpts.Env {
s := strings.SplitN(env, "=", 2)
envvars = append(envvars, apiv1.EnvVar{
Name: s[0],
Value: s[1],
})
}
// Get peer Pod
myself, _ := os.Hostname()
myselfPod, err := clientset.CoreV1().Pods(cfg.Namespace).Get(ctx, myself, metav1.GetOptions{})
if err != nil {
return nil, errors.Wrap(err, "getting myself Pod")
}
// Set resources
limits := apiv1.ResourceList{}
if limit := cfg.Builder.Resources.LimitMemory; limit != "" {
limits["memory"] = resource.MustParse(limit)
}
if limit := cfg.Builder.Resources.LimitCPU; limit != "" {
limits["cpu"] = resource.MustParse(limit)
}
// Pod
podname := fmt.Sprintf("%s-ccbuild-%s", myself, metadata.MetadataID)
pod := &apiv1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: podname,
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: "v1",
Kind: "Pod",
Name: myselfPod.Name,
UID: myselfPod.UID,
BlockOwnerDeletion: BoolRef(true),
},
},
Labels: map[string]string{
"externalcc-type": "builder",
},
},
Spec: apiv1.PodSpec{
Containers: []apiv1.Container{
{
Name: "builder",
Image: image,
ImagePullPolicy: apiv1.PullIfNotPresent,
Command: []string{
"/bin/sh", "-c", buildOpts.Cmd,
},
Env: envvars,
Resources: apiv1.ResourceRequirements{Limits: limits},
VolumeMounts: []apiv1.VolumeMount{
{
Name: "transfer-pv",
MountPath: "/chaincode/input/",
SubPath: transferPVPrefix + "/src/",
ReadOnly: true,
},
{
Name: "transfer-pv",
MountPath: "/chaincode/output/",
SubPath: transferPVPrefix + "/bld/",
ReadOnly: false,
},
},
},
},
EnableServiceLinks: BoolRef(false),
RestartPolicy: apiv1.RestartPolicyNever,
Volumes: []apiv1.Volume{
{
Name: "transfer-pv",
VolumeSource: apiv1.VolumeSource{
PersistentVolumeClaim: &apiv1.PersistentVolumeClaimVolumeSource{
ClaimName: cfg.TransferVolume.Claim,
},
},
},
},
},
}
return clientset.CoreV1().Pods(cfg.Namespace).Create(ctx, pod, metav1.CreateOptions{})
}