blob: c36e7cda5f76ab50d2ac1661cf2df9a414658f7c [file] [log] [blame]
Victor Ryzhenkinef34a022018-06-22 19:36:13 +04001/**
2 * Update kuberentes cluster
3 *
4 * Expected parameters:
Victor Ryzhenkineb543bf2019-01-18 06:34:26 +04005 * SALT_MASTER_CREDENTIALS Credentials to the Salt API.
6 * SALT_MASTER_URL Full Salt API address [https://10.10.10.1:8000].
7 * KUBERNETES_HYPERKUBE_SOURCE Versioned hyperkube binary to update control plane from. Should be null if update rolling via reclass-system level
8 * KUBERNETES_HYPERKUBE_SOURCE_HASH Versioned hyperkube binary to update control plane from. Should be null if update rolling via reclass-system level
9 * KUBERNETES_PAUSE_IMAGE Kubernetes pause image should have same version as hyperkube. May be null in case of reclass-system rollout
10 * TARGET_UPDATES Comma separated list of nodes to update (Valid values are ctl,cmp)
11 * CTL_TARGET Salt targeted kubernetes CTL nodes (ex. I@kubernetes:master). Kubernetes control plane
12 * CMP_TARGET Salt targeted compute nodes (ex. cmp* and 'I@kubernetes:pool') Kubernetes computes
13 * PER_NODE Target nodes will be managed one by one (bool)
14 * SIMPLE_UPGRADE Use previous version of upgrade without conron/drain abilities
15 * CONFORMANCE_RUN_AFTER Run Kubernetes conformance tests after update
16 * CONFORMANCE_RUN_BEFORE Run Kubernetes conformance tests before update
17 * TEST_K8S_API_SERVER Kubernetes API server address for test execution
18 * ARTIFACTORY_URL Artifactory URL where docker images located. Needed to correctly fetch conformance images.
19 * UPGRADE_CALICO_V2_TO_V3 Perform Calico upgrade from v2 to v3.
20 * KUBERNETES_CALICO_IMAGE Target calico/node image. May be null in case of reclass-system rollout.
21 * KUBERNETES_CALICO_CALICOCTL_SOURCE Versioned calico/ctl binary. Should be null if update rolling via reclass-system level
22 * KUBERNETES_CALICO_CALICOCTL_SOURCE_HASH Calico/ctl binary md5 hash. Should be null if update rolling via reclass-system level
23 * KUBERNETES_CALICO_CNI_SOURCE Versioned calico/cni binary. Should be null if update rolling via reclass-system level
24 * KUBERNETES_CALICO_CNI_SOURCE_HASH Сalico/cni binary hash. Should be null if update rolling via reclass-system level
25 * KUBERNETES_CALICO_BIRDCL_SOURCE Versioned calico/bird binary. Should be null if update rolling via reclass-system level
26 * KUBERNETES_CALICO_BIRDCL_SOURCE_HASH Сalico/bird binary hash. Should be null if update rolling via reclass-system level
27 * KUBERNETES_CALICO_CNI_IPAM_SOURCE Versioned calico/ipam binary. Should be null if update rolling via reclass-system level
28 * KUBERNETES_CALICO_CNI_IPAM_SOURCE_HASH Сalico/ipam binary hash. Should be null if update rolling via reclass-system level
29 * KUBERNETES_CALICO_KUBE_CONTROLLERS_IMAGE Target calico/kube-controllers image. May be null in case of reclass-system rollout.
30 * CALICO_UPGRADE_VERSION Version of "calico-upgrade" utility to be used ("v1.0.5" for Calico v3.1.3 target).
ashestakovc030dac2019-01-11 11:34:54 +020031 * KUBERNETES_ETCD_SOURCE Target etcd binary. May be null in case of reclass-system rollout.
32 * KUBERNETES_ETCD_SOURCE_HASH Target etcd binary checksum. May be null in case of reclass-system rollout.
Victor Ryzhenkinef34a022018-06-22 19:36:13 +040033 *
34**/
Aleksei Kasatkin9ce11842018-11-23 14:27:33 +010035import groovy.json.JsonSlurper
36
Victor Ryzhenkinef34a022018-06-22 19:36:13 +040037def common = new com.mirantis.mk.Common()
38def salt = new com.mirantis.mk.Salt()
39def python = new com.mirantis.mk.Python()
Victor Ryzhenkin723bd062018-12-11 17:09:06 +040040def test = new com.mirantis.mk.Test()
Victor Ryzhenkinef34a022018-06-22 19:36:13 +040041
42def updates = TARGET_UPDATES.tokenize(",").collect{it -> it.trim()}
43def pepperEnv = "pepperEnv"
44
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +020045def POOL = "I@kubernetes:pool"
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +020046
Aleksei Kasatkin1f4f5ba2018-11-20 18:30:36 +010047ETCD_ENDPOINTS = ""
48
Victor Ryzhenkinef34a022018-06-22 19:36:13 +040049def overrideKubernetesImage(pepperEnv) {
50 def salt = new com.mirantis.mk.Salt()
51
52 def k8sSaltOverrides = """
Victor Ryzhenkineb543bf2019-01-18 06:34:26 +040053 kubernetes_hyperkube_source: ${KUBERNETES_HYPERKUBE_SOURCE}
54 kubernetes_hyperkube_source_hash: ${KUBERNETES_HYPERKUBE_SOURCE_HASH}
Victor Ryzhenkinef34a022018-06-22 19:36:13 +040055 kubernetes_pause_image: ${KUBERNETES_PAUSE_IMAGE}
56 """
57 stage("Override kubernetes images to target version") {
58 salt.setSaltOverrides(pepperEnv, k8sSaltOverrides)
59 }
60}
61
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +020062def overrideCalicoImages(pepperEnv) {
63 def salt = new com.mirantis.mk.Salt()
64
65 def calicoSaltOverrides = """
66 kubernetes_calico_image: ${KUBERNETES_CALICO_IMAGE}
Victor Ryzhenkineb543bf2019-01-18 06:34:26 +040067 kubernetes_calico_calicoctl_source: ${KUBERNETES_CALICO_CALICOCTL_SOURCE}
68 kubernetes_calico_calicoctl_source_hash: ${KUBERNETES_CALICO_CALICOCTL_SOURCE_HASH}
69 kubernetes_calico_birdcl_source: ${KUBERNETES_CALICO_BIRDCL_SOURCE}
70 kubernetes_calico_birdcl_source_hash: ${KUBERNETES_CALICO_BIRDCL_SOURCE_HASH}
71 kubernetes_calico_cni_source: ${KUBERNETES_CALICO_CNI_SOURCE}
72 kubernetes_calico_cni_source_hash: ${KUBERNETES_CALICO_CNI_SOURCE_HASH}
73 kubernetes_calico_cni_ipam_source: ${KUBERNETES_CALICO_CNI_IPAM_SOURCE}
74 kubernetes_calico_cni_ipam_source_hash: ${KUBERNETES_CALICO_CNI_IPAM_SOURCE_HASH}
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +020075 kubernetes_calico_kube_controllers_image: ${KUBERNETES_CALICO_KUBE_CONTROLLERS_IMAGE}
76 """
77 stage("Override calico images to target version") {
78 salt.setSaltOverrides(pepperEnv, calicoSaltOverrides)
79 }
80}
81
82def downloadCalicoUpgrader(pepperEnv, target) {
83 def salt = new com.mirantis.mk.Salt()
84
85 stage("Downloading calico-upgrade utility") {
86 salt.cmdRun(pepperEnv, target, "rm -f ./calico-upgrade")
87 salt.cmdRun(pepperEnv, target, "wget https://github.com/projectcalico/calico-upgrade/releases/download/${CALICO_UPGRADE_VERSION}/calico-upgrade")
88 salt.cmdRun(pepperEnv, target, "chmod +x ./calico-upgrade")
89 }
90}
91
ashestakovc030dac2019-01-11 11:34:54 +020092def overrideEtcdSource(pepperEnv) {
93 def salt = new com.mirantis.mk.Salt()
94
95 def k8sSaltOverrides = """
96 kubernetes_etcd_source: ${KUBERNETES_ETCD_SOURCE}
97 kubernetes_etcd_source_hash: ${KUBERNETES_ETCD_SOURCE_HASH}
98 """
99 stage("Override etcd binaries to target version") {
100 salt.setSaltOverrides(pepperEnv, k8sSaltOverrides)
101 }
102}
103
104def performEtcdUpdateAndServicesRestart(pepperEnv, target) {
105 def salt = new com.mirantis.mk.Salt()
106
107 stage("Performing etcd update and services restart on ${target}") {
108 salt.enforceState(pepperEnv, target, "etcd.server.service")
109 salt.cmdRun(pepperEnv, target, ". /var/lib/etcd/configenv && etcdctl cluster-health")
110 }
111}
112
Victor Ryzhenkinef34a022018-06-22 19:36:13 +0400113def performKubernetesComputeUpdate(pepperEnv, target) {
114 def salt = new com.mirantis.mk.Salt()
115
116 stage("Execute Kubernetes compute update on ${target}") {
117 salt.enforceState(pepperEnv, target, 'kubernetes.pool')
118 salt.runSaltProcessStep(pepperEnv, target, 'service.restart', ['kubelet'])
119 }
120}
121
122def performKubernetesControlUpdate(pepperEnv, target) {
123 def salt = new com.mirantis.mk.Salt()
124
125 stage("Execute Kubernetes control plane update on ${target}") {
126 salt.enforceStateWithExclude(pepperEnv, target, "kubernetes", "kubernetes.master.setup")
127 // Restart kubelet
128 salt.runSaltProcessStep(pepperEnv, target, 'service.restart', ['kubelet'])
129 }
130}
131
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200132def startCalicoUpgrade(pepperEnv, target) {
133 def salt = new com.mirantis.mk.Salt()
134
135 stage("Starting upgrade using calico-upgrade: migrate etcd schema and lock Calico") {
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200136 def cmd = "export APIV1_ETCD_ENDPOINTS=${ETCD_ENDPOINTS} && " +
137 "export APIV1_ETCD_CA_CERT_FILE=/var/lib/etcd/ca.pem && " +
138 "export APIV1_ETCD_CERT_FILE=/var/lib/etcd/etcd-client.crt && " +
139 "export APIV1_ETCD_KEY_FILE=/var/lib/etcd/etcd-client.key && " +
140 "export ETCD_ENDPOINTS=${ETCD_ENDPOINTS} && " +
141 "export ETCD_CA_CERT_FILE=/var/lib/etcd/ca.pem && " +
142 "export ETCD_CERT_FILE=/var/lib/etcd/etcd-client.crt && " +
143 "export ETCD_KEY_FILE=/var/lib/etcd/etcd-client.key && " +
144 "rm /root/upg_complete -f && " +
145 "./calico-upgrade start --no-prompts --ignore-v3-data > upgrade-start.log && " +
146 "until [ -f /root/upg_complete ]; do sleep 0.1; done && " +
147 "./calico-upgrade complete --no-prompts > upgrade-complete.log && " +
148 "rm /root/upg_complete -f"
149 // "saltArgs = ['async']" doesn't work, so we have to run "cmd.run --async"
150 salt.cmdRun(pepperEnv, "I@salt:master", "salt -C '${target}' cmd.run '${cmd}' --async")
151 salt.cmdRun(pepperEnv, target, "until [ -f /root/upgrade-start.log ]; do sleep 0.1; done")
152 }
153}
154
155def completeCalicoUpgrade(pepperEnv, target) {
156 def salt = new com.mirantis.mk.Salt()
157
158 stage("Complete upgrade using calico-upgrade: unlock Calico") {
159 salt.cmdRun(pepperEnv, target, "echo 'true' > /root/upg_complete")
160 salt.cmdRun(pepperEnv, target, "while [ -f /root/upg_complete ]; do sleep 0.1; done")
161 salt.cmdRun(pepperEnv, target, "cat /root/upgrade-start.log")
162 salt.cmdRun(pepperEnv, target, "cat /root/upgrade-complete.log")
163 }
164}
165
Aleksei Kasatkind9d682e2018-12-12 14:51:59 +0100166def performCalicoConfigurationUpdateAndServicesRestart(pepperEnv, target, ctl_node) {
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200167 def salt = new com.mirantis.mk.Salt()
168
169 stage("Performing Calico configuration update and services restart") {
Aleksei Kasatkind9d682e2018-12-12 14:51:59 +0100170 if (containerDenabled(pepperEnv, ctl_node)) {
171 salt.enforceState(pepperEnv, target, "kubernetes.pool")
172 } else {
173 salt.enforceState(pepperEnv, target, "kubernetes.pool.calico")
174 }
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200175 salt.runSaltProcessStep(pepperEnv, target, 'service.restart', ['kubelet'])
176 }
177}
178
Victor Ryzhenkin42e4b382018-09-11 17:57:56 +0400179def cordonNode(pepperEnv, target) {
180 def salt = new com.mirantis.mk.Salt()
181 def originalTarget = "I@kubernetes:master and not ${target}"
182
183 stage("Cordoning ${target} kubernetes node") {
184 def nodeShortName = target.tokenize(".")[0]
185 salt.cmdRun(pepperEnv, originalTarget, "kubectl cordon ${nodeShortName}", true, 1)
186 }
187}
188
189def uncordonNode(pepperEnv, target) {
190 def salt = new com.mirantis.mk.Salt()
191 def originalTarget = "I@kubernetes:master and not ${target}"
192
193 stage("Uncordoning ${target} kubernetes node") {
194 def nodeShortName = target.tokenize(".")[0]
195 salt.cmdRun(pepperEnv, originalTarget, "kubectl uncordon ${nodeShortName}", true, 1)
196 }
197}
198
199def drainNode(pepperEnv, target) {
200 def salt = new com.mirantis.mk.Salt()
201 def originalTarget = "I@kubernetes:master and not ${target}"
202
203 stage("Draining ${target} kubernetes node") {
204 def nodeShortName = target.tokenize(".")[0]
205 salt.cmdRun(pepperEnv, originalTarget, "kubectl drain --force --ignore-daemonsets --grace-period 100 --timeout 300s --delete-local-data ${nodeShortName}", true, 1)
206 }
207}
208
209def regenerateCerts(pepperEnv, target) {
210 def salt = new com.mirantis.mk.Salt()
211
212 stage("Regenerate certs for ${target}") {
213 salt.enforceState(pepperEnv, target, 'salt.minion.cert')
214 }
215}
216
Victor Ryzhenkinae909182018-10-02 17:49:18 +0400217def updateAddons(pepperEnv, target) {
218 def salt = new com.mirantis.mk.Salt()
219
220 stage("Upgrading Addons at ${target}") {
Victor Ryzhenkin40625bc2018-10-04 16:15:27 +0400221 salt.enforceState(pepperEnv, target, "kubernetes.master.kube-addons")
Victor Ryzhenkinfd9677f2018-10-16 16:14:40 +0400222 }
223}
224
225def updateAddonManager(pepperEnv, target) {
226 def salt = new com.mirantis.mk.Salt()
227
228 stage("Upgrading AddonManager at ${target}") {
Victor Ryzhenkinae909182018-10-02 17:49:18 +0400229 salt.enforceState(pepperEnv, target, "kubernetes.master.setup")
230 }
231}
232
Victor Ryzhenkin42e4b382018-09-11 17:57:56 +0400233def upgradeDocker(pepperEnv, target) {
234 def salt = new com.mirantis.mk.Salt()
235
236 stage("Upgrading docker at ${target}") {
237 salt.enforceState(pepperEnv, target, 'docker.host')
238 }
239}
Victor Ryzhenkinef34a022018-06-22 19:36:13 +0400240
Victor Ryzhenkinae22a5a2018-10-12 15:52:27 +0400241def runConformance(pepperEnv, target, k8s_api, image) {
242 def salt = new com.mirantis.mk.Salt()
243 def containerName = 'conformance_tests'
244 output_file = image.replaceAll('/', '-') + '.output'
245 def output_file_full_path = "/tmp/" + image.replaceAll('/', '-') + '.output'
246 def artifacts_dir = '_artifacts/'
247 salt.cmdRun(pepperEnv, target, "docker rm -f ${containerName}", false)
248 salt.cmdRun(pepperEnv, target, "docker run -d --name ${containerName} --net=host -e API_SERVER=${k8s_api} ${image}")
249 sleep(10)
250
251 print("Waiting for tests to run...")
252 salt.runSaltProcessStep(pepperEnv, target, 'cmd.run', ["docker wait ${containerName}"], null, false)
253
254 print("Writing test results to output file...")
255 salt.runSaltProcessStep(pepperEnv, target, 'cmd.run', ["docker logs -t ${containerName} > ${output_file_full_path}"])
256 print("Conformance test output saved in " + output_file_full_path)
257
258 // collect output
259 sh "mkdir -p ${artifacts_dir}"
260 file_content = salt.getFileContent(pepperEnv, target, '/tmp/' + output_file)
261 writeFile file: "${artifacts_dir}${output_file}", text: file_content
262 sh "cat ${artifacts_dir}${output_file}"
263 try {
264 sh "cat ${artifacts_dir}${output_file} | grep 'Test Suite Failed' && exit 1 || exit 0"
265 } catch (Throwable e) {
266 print("Conformance tests failed. Please check output")
267 currentBuild.result = "FAILURE"
268 currentBuild.description = currentBuild.description ? e.message + " " + currentBuild.description : e.message
269 throw e
270 }
271}
272
273def buildImageURL(pepperEnv, target, mcp_repo) {
274 def salt = new com.mirantis.mk.Salt()
275 def raw_version = salt.cmdRun(pepperEnv, target, "kubectl version --short -o json")['return'][0].values()[0].replaceAll('Salt command execution success','')
276 print("Kubernetes version: " + raw_version)
277 def serialized_version = readJSON text: raw_version
278 def short_version = (serialized_version.serverVersion.gitVersion =~ /([v])(\d+\.)(\d+\.)(\d+\-)(\d+)/)[0][0]
279 print("Kubernetes short version: " + short_version)
280 def conformance_image = mcp_repo + "/mirantis/kubernetes/k8s-conformance:" + short_version
281 return conformance_image
282}
283
284def executeConformance(pepperEnv, target, k8s_api, mcp_repo) {
285 stage("Running conformance tests") {
286 def image = buildImageURL(pepperEnv, target, mcp_repo)
287 print("Using image: " + image)
288 runConformance(pepperEnv, target, k8s_api, image)
289 }
290}
291
Victor Ryzhenkin723bd062018-12-11 17:09:06 +0400292def containerDinstalled(pepperEnv, target) {
293 def salt = new com.mirantis.mk.Salt()
294 return salt.cmdRun(pepperEnv, target, "containerd --version 2>1 1>/dev/null && echo 'true' || echo 'false'"
295 )['return'][0].values()[0].replaceAll('Salt command execution success','').trim().toBoolean()
296}
297
298def containerDenabled(pepperEnv, target) {
299 def salt = new com.mirantis.mk.Salt()
Victor Ryzhenkin71ecdf42018-12-11 22:22:50 +0400300 return salt.getPillar(pepperEnv, target, "kubernetes:common:containerd:enabled"
Victor Ryzhenkin723bd062018-12-11 17:09:06 +0400301 )["return"][0].values()[0].toBoolean()
302}
303
304def conformancePodDefExists(pepperEnv, target) {
305 def salt = new com.mirantis.mk.Salt()
306 return salt.cmdRun(pepperEnv, target, "test -e /srv/kubernetes/conformance.yml && echo 'true' || echo 'false'"
307 )['return'][0].values()[0].replaceAll('Salt command execution success','').trim().toBoolean()
308}
309
Victor Ryzhenkineb543bf2019-01-18 06:34:26 +0400310def printVersionInfo(pepperEnv, target) {
311 def salt = new com.mirantis.mk.Salt()
312 def common = new com.mirantis.mk.Common()
313
314 stage("Gather version and runtime information") {
315 common.infoMsg("Version and runtime info:")
316 salt.cmdRun(pepperEnv, target, "kubectl get no -o wide")
317 common.infoMsg("Cluster health info:")
318 salt.cmdRun(pepperEnv, target, "kubectl get cs")
319 common.infoMsg("ETCD health info:")
Victor Ryzhenkin7fda5c42019-01-18 22:17:57 +0400320 salt.cmdRun(pepperEnv, target, ". /var/lib/etcd/configenv && etcdctl cluster-health")
Victor Ryzhenkineb543bf2019-01-18 06:34:26 +0400321 common.infoMsg("Calico peers info:")
322 salt.cmdRun(pepperEnv, target, "calicoctl node status")
323 }
324}
325
Aleksei Kasatkin5ccea272018-12-06 17:34:58 +0100326def calicoEnabled(pepperEnv, target) {
327 def salt = new com.mirantis.mk.Salt()
328 return salt.getPillar(pepperEnv, target, "kubernetes:pool:network:calico:enabled"
329 )["return"][0].values()[0].toBoolean()
330}
331
332def checkCalicoClusterState(pepperEnv, target) {
333 def common = new com.mirantis.mk.Common()
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200334 def salt = new com.mirantis.mk.Salt()
335
Aleksei Kasatkin5ccea272018-12-06 17:34:58 +0100336 stage("Checking Calico cluster state after upgrade") {
337 // check Calico cluster and cli clients versions
338 def checkVer = [
339 "Client Version:": [verStr: "", dif: false, wrong: false],
340 "Cluster Version:": [verStr: "", dif: false, wrong: false]
341 ]
342 def checkVerPassed = true
343 def versionResults = salt.cmdRun(pepperEnv, target, "calicoctl version | grep -i version")['return'][0]
344 versionResults.each { k, v ->
345 // println("Node:\n${k}\nResult:\n${v}")
346 for (verLine in v.split("\n")) {
347 for (verType in checkVer.keySet()) {
348 if (verLine.contains(verType)) {
349 def verRec = checkVer[verType]
350 ver = (verLine - verType).trim()
351 if (!verRec.verStr) {
352 verRec.verStr = ver
353 }
354 if (verRec.verStr != ver) {
355 verRec.dif = true
356 checkVerPassed = false
357 }
358 version = ver.tokenize(".")
359 if ((version.size() < 3) || (version[0] != "v3")) {
360 verRec.wrong = true
361 checkVerPassed = false
362 }
363 checkVer[verType] = verRec
364 }
365 }
366 }
367 }
368 if (checkVerPassed) {
369 common.infoMsg("Calico version verification passed")
370 }
371 else {
372 def warningMsg = "Calico version verification failed.\n"
373 checkVer.each { k, rec ->
374 if (rec.dif) {
375 warningMsg += "${k} versions are different across nodes.\n"
376 }
377 if (rec.wrong) {
378 warningMsg += "${k} (some) versions are wrong - should be v3.x.\n"
379 }
380 }
381 common.warningMsg(warningMsg)
382 currentBuild.description += "<br><b>${warningMsg}</b><br><br>"
383 }
384
385 // check Calico nodes' statuses
386 def nodeStatusResults = salt.cmdRun(pepperEnv, target, "calicoctl node status")['return'][0]
387 def nodesRunning = true
388 def peersNotFound = []
389 def peersNotOnline = []
390 nodeStatusResults.each { k, v ->
391 // println("Node:\n${k}\nResult:\n${v}")
392 if (!v.contains("Calico process is running")) {
393 nodesRunning = false
394 def warningMsg = "Node ${k}: Calico node is not running."
395 common.warningMsg(warningMsg)
396 currentBuild.description += "<br><b>${warningMsg}</b><br><br>"
397 }
398 def nodePeersFound = false
399 def nodePeersOnline = true
400 for (nodeLine in v.split("\n")) {
401 if (nodeLine.contains("|") && (!nodeLine.contains("STATE"))) {
402 def col = nodeLine.tokenize("|").collect{it.trim()}
403 if (col.size() == 5) {
404 nodePeersFound = true
405 if ((col[2] != "up") || (col[4] != "Established")) {
406 def warningMsg = "Node ${k}: BGP peer '${col[0]}' is out of reach. Peer state: '${col[2]}', connection info: '${col[4]}'."
407 common.warningMsg(warningMsg)
408 currentBuild.description += "<br><b>${warningMsg}</b><br><br>"
409 nodePeersOnline = false
410 }
411 }
412 }
413 }
414 if (!nodePeersFound) {
415 peersNotFound += k
416 }
417 if (!nodePeersOnline) {
418 peersNotOnline += k
419 }
420 }
421 if (nodesRunning) {
422 common.infoMsg("All the Calico nodes are running")
423 }
424 if (peersNotFound) {
425 def warningMsg = "BGP peers not found for the node(s): " + peersNotFound.join(', ') + "."
426 common.warningMsg(warningMsg)
427 currentBuild.description += "<br><b>${warningMsg}</b><br><br>"
428 } else {
429 common.infoMsg("BGP peers were found for all the nodes")
430 }
431 if (!peersNotOnline) {
432 common.infoMsg("All reported BGP peers are reachable")
433 }
434
435 // check that 'calico-kube-controllers' is running
436 // one CTL node will be used to get pod's state using kubectl
437 def ctl_node = salt.getMinionsSorted(pepperEnv, CTL_TARGET)[0]
438 def kubeCtrlResult = salt.cmdRun(
439 pepperEnv, ctl_node, "kubectl get pod -n kube-system --selector=k8s-app=calico-kube-controllers"
440 )['return'][0].values()[0].toString()
441 if (kubeCtrlResult.contains("calico-kube-controllers")) {
442 for (line in kubeCtrlResult.split("\n")) {
443 if (line.contains("calico-kube-controllers")) {
444 col = line.tokenize(" ")
445 if ((col[1] != "1/1") || (col[2] != "Running")) {
446 def warningMsg = "Calico kube-controllers pod is not running properly."
447 common.warningMsg(warningMsg)
448 currentBuild.description += "<br><b>${warningMsg}</b><br><br>"
449 }
450 else {
451 common.infoMsg("Calico kube-controllers pod is running.")
452 }
453 break
454 }
455 }
456 } else {
457 def warningMsg = "Calico kube-controllers pod was not scheduled."
458 common.warningMsg(warningMsg)
459 currentBuild.description += "<br><b>${warningMsg}</b><br><br>"
460 }
Aleksei Kasatkin1f4f5ba2018-11-20 18:30:36 +0100461 }
462}
463
464def checkCalicoUpgradePossibility(pepperEnv, target) {
465 def salt = new com.mirantis.mk.Salt()
466
467 stage("Verification of Calico upgrade possibility") {
468 // check Calico version
469 def versionResult = salt.cmdRun(
470 pepperEnv, target, "calicoctl version | grep 'Cluster Version'"
471 )['return'][0].values()[0].split("\n")[0].trim()
472 versionStr = (versionResult - "Cluster Version:").trim()
473 version = versionStr.tokenize(".")
474 if ((version.size() < 3) || (version[0] != "v2") || (version[1] != "6") || (version[2].toInteger() < 5)) {
475 error(
476 "Current Calico ${versionStr} cannot be upgraded to v3.x. " +
477 "Calico v2.6.x starting from v2.6.5 can be upgraded. " +
478 "For earlier versions, please update to v2.6.5 first."
479 )
480 }
481 print("Calico version was determined: ${versionStr}")
482
483 // check Calico is switched on
484 def readinessResult = salt.cmdRun(
485 pepperEnv, target, ". /var/lib/etcd/configenv && etcdctl get /calico/v1/Ready"
486 )['return'][0].values()[0].split("\n")[0].trim()
487 print("Calico readiness check result: ${readinessResult}")
488 if (readinessResult != "true") {
489 // try set it to true
490 readinessResult = salt.cmdRun(
491 pepperEnv, target, ". /var/lib/etcd/configenv && etcdctl set /calico/v1/Ready true"
492 )['return'][0].values()[0].split("\n")[0].trim()
493 print("Calico readiness result 2nd attempt: ${readinessResult}")
494 if (readinessResult != "true") {
495 error("Calico is not ready. '/calico/v1/Ready': '${readinessResult}'")
496 }
497 }
498
499 // Calico data upgrade dry-run
500 def cmd = "export APIV1_ETCD_ENDPOINTS=${ETCD_ENDPOINTS} && " +
501 "export APIV1_ETCD_CA_CERT_FILE=/var/lib/etcd/ca.pem && " +
502 "export APIV1_ETCD_CERT_FILE=/var/lib/etcd/etcd-client.crt && " +
503 "export APIV1_ETCD_KEY_FILE=/var/lib/etcd/etcd-client.key && " +
504 "export ETCD_ENDPOINTS=${ETCD_ENDPOINTS} && " +
505 "export ETCD_CA_CERT_FILE=/var/lib/etcd/ca.pem && " +
506 "export ETCD_CERT_FILE=/var/lib/etcd/etcd-client.crt && " +
507 "export ETCD_KEY_FILE=/var/lib/etcd/etcd-client.key && " +
508 "./calico-upgrade dry-run --ignore-v3-data"
509 def dryRunResult = salt.cmdRun(pepperEnv, target, cmd)['return'][0].values()[0]
510 // check dry-run result
511 def validationSuccessStr = "Successfully validated v1 to v3 conversion"
512 if (!dryRunResult.contains(validationSuccessStr)) {
513 error("Calico data upgrade dry-run has failed")
514 }
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200515 }
516}
Victor Ryzhenkinae22a5a2018-10-12 15:52:27 +0400517
Aleksei Kasatkin9ce11842018-11-23 14:27:33 +0100518def checkCalicoPolicySetting(pepperEnv, target) {
519 def common = new com.mirantis.mk.Common()
520 def salt = new com.mirantis.mk.Salt()
521
522 stage("Checking of Calico network policy setting") {
523 // check Calico policy enabled
524 def cniPolicy = false
525 def addonsPolicy = false
526 def kubeCtrlRunning = false
527
528 // check CNI config
529 def cniCfgResult = salt.cmdRun(
530 pepperEnv, target, "cat /etc/cni/net.d/10-calico.conf"
531 )['return'][0].values()[0].toString()
532 def cniCfg = new JsonSlurper().parseText(cniCfgResult)
533 if (cniCfg.get("policy") != null) {
534 if (cniCfg["policy"].get("type") == "k8s") {
535 cniPolicy = true
536 } else {
537 common.warningMsg("Calico policy type is unknown or not set.")
538 }
539 }
540
541 // check k8s addons
542 def addonsResult = salt.cmdRun(
543 pepperEnv, target, "ls /etc/kubernetes/addons"
544 )['return'][0].values()[0].toString()
545 if (addonsResult.contains("calico_policy")) {
546 addonsPolicy = true
547 }
548
549 // check kube-controllers is running
550 def kubeCtrlResult = salt.cmdRun(
551 pepperEnv, target, "kubectl get pod -n kube-system --selector=k8s-app=calico-kube-controllers"
552 )['return'][0].values()[0].toString()
553 if (kubeCtrlResult.contains("Running")) {
554 kubeCtrlRunning = true
555 }
556
557 // It's safe to enable Calico policy any time, but it may be unsafe to disable it.
558 // So, no need to disable Calico policy for v3.x if it's not in use currently.
559 // But if Calico policy is in use already, it should be enabled after upgrade as well.
560
561 // check for consistency
562 if ((cniPolicy != addonsPolicy) || (addonsPolicy != kubeCtrlRunning)) {
563 caution = "ATTENTION. Calico policy setting cannot be determined reliably (enabled in CNI config: ${cniPolicy}, " +
564 "presence in k8s addons: ${addonsPolicy}, kube-controllers is running: ${kubeCtrlRunning})."
565 currentBuild.description += "<br><b>${caution}</b><br><br>"
566 common.warningMsg(caution)
567 } else {
568 common.infoMsg("Current Calico policy state is detected as: ${cniPolicy}")
569 if (cniPolicy) {
570 // Calico policy is in use. Check policy setting for v3.x.
571 common.infoMsg("Calico policy is in use. It should be enabled for v3.x as well.")
572 def saltPolicyResult = salt.getPillar(
573 pepperEnv, target, "kubernetes:pool:network:calico:policy"
574 )["return"][0].values()[0].toString()
575
576 common.infoMsg("kubernetes.pool.network.calico.policy: ${saltPolicyResult}")
577 if (saltPolicyResult.toLowerCase().contains("true")) {
578 common.infoMsg("Calico policy setting for v3.x is detected as: true")
579 } else {
580 caution = "ATTENTION. Currently, Calico is running with policy switched on. " +
581 "Calico policy setting for v3.x is not set to true. " +
582 "After upgrade is completed, Calico policy will be switched off. " +
583 "You will need to switch it on manually if required."
584 currentBuild.description += "<br><b>${caution}</b><br><br>"
585 common.warningMsg(caution)
586 }
587 }
588 }
589
590 if (addonsPolicy) {
591 // Remove v2.6.x policy-related addons on masters to not interfere with v3.x kube-controllers
592 salt.cmdRun(pepperEnv, CTL_TARGET, "rm -rf /etc/kubernetes/addons/calico_policy")
593 }
594 }
595}
596
Victor Ryzhenkinef34a022018-06-22 19:36:13 +0400597timeout(time: 12, unit: 'HOURS') {
598 node() {
599 try {
600
601 stage("Setup virtualenv for Pepper") {
602 python.setupPepperVirtualenv(pepperEnv, SALT_MASTER_URL, SALT_MASTER_CREDENTIALS)
603 }
604
Victor Ryzhenkinae22a5a2018-10-12 15:52:27 +0400605 if (CONFORMANCE_RUN_BEFORE.toBoolean()) {
606 def target = CTL_TARGET
607 def mcp_repo = ARTIFACTORY_URL
608 def k8s_api = TEST_K8S_API_SERVER
609 firstTarget = salt.getFirstMinion(pepperEnv, target)
Victor Ryzhenkin723bd062018-12-11 17:09:06 +0400610 def containerd_enabled = containerDenabled(pepperEnv, firstTarget)
611 def containerd_installed = containerDinstalled(pepperEnv, firstTarget)
612 def conformance_pod_ready = conformancePodDefExists(pepperEnv, firstTarget)
613 if (containerd_enabled && containerd_installed && conformance_pod_ready) {
614 def config = ['master': pepperEnv,
615 'target': firstTarget,
616 'junitResults': false,
617 'autodetect': true]
618 test.executeConformance(config)
619 } else {
620 executeConformance(pepperEnv, firstTarget, k8s_api, mcp_repo)
621 }
Victor Ryzhenkinae22a5a2018-10-12 15:52:27 +0400622 }
623
Victor Ryzhenkinef34a022018-06-22 19:36:13 +0400624 if ((common.validInputParam('KUBERNETES_HYPERKUBE_IMAGE')) && (common.validInputParam('KUBERNETES_PAUSE_IMAGE'))) {
625 overrideKubernetesImage(pepperEnv)
626 }
627
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200628 if ((common.validInputParam('KUBERNETES_CALICO_IMAGE'))
Victor Ryzhenkineb543bf2019-01-18 06:34:26 +0400629 && (common.validInputParam('KUBERNETES_CALICO_CALICOCTL_SOURCE'))
630 && (common.validInputParam('KUBERNETES_CALICO_CALICOCTL_SOURCE_HASH'))
631 && (common.validInputParam('KUBERNETES_CALICO_CNI_SOURCE'))
632 && (common.validInputParam('KUBERNETES_CALICO_CNI_SOURCE_HASH'))
633 && (common.validInputParam('KUBERNETES_CALICO_BIRDCL_SOURCE'))
634 && (common.validInputParam('KUBERNETES_CALICO_BIRDCL_SOURCE_HASH'))
635 && (common.validInputParam('KUBERNETES_CALICO_CNI_IPAM_SOURCE'))
636 && (common.validInputParam('KUBERNETES_CALICO_CNI_IPAM_SOURCE_HASH'))
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200637 && (common.validInputParam('KUBERNETES_CALICO_KUBE_CONTROLLERS_IMAGE'))
638 ) {
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200639 overrideCalicoImages(pepperEnv)
640 }
641
Victor Ryzhenkinef34a022018-06-22 19:36:13 +0400642 /*
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200643 * Execute Calico upgrade if needed (only for v2 to v3 upgrade).
644 * This part causes workloads operations downtime.
645 * It is only required for Calico v2.x to v3.x upgrade when etcd is in use for Calico
646 * as Calico etcd schema has different formats for Calico v2.x and Calico v3.x.
647 */
648 if (UPGRADE_CALICO_V2_TO_V3.toBoolean()) {
649 // one CTL node will be used for running upgrade of Calico etcd schema
650 def ctl_node = salt.getMinionsSorted(pepperEnv, CTL_TARGET)[0]
651
Aleksei Kasatkin1f4f5ba2018-11-20 18:30:36 +0100652 // get ETCD_ENDPOINTS in use by Calico
653 def ep_str = salt.cmdRun(pepperEnv, ctl_node, "cat /etc/calico/calicoctl.cfg | grep etcdEndpoints")['return'][0].values()[0]
654 ETCD_ENDPOINTS = ep_str.split("\n")[0].tokenize(' ')[1]
655 print("ETCD_ENDPOINTS in use by Calico: '${ETCD_ENDPOINTS}'")
656
657 // download calico-upgrade utility
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200658 downloadCalicoUpgrader(pepperEnv, ctl_node)
Aleksei Kasatkin1f4f5ba2018-11-20 18:30:36 +0100659
660 // check the possibility of upgrading of Calico
661 checkCalicoUpgradePossibility(pepperEnv, ctl_node)
662
Aleksei Kasatkin9ce11842018-11-23 14:27:33 +0100663 // check and adjust Calico policy setting
664 checkCalicoPolicySetting(pepperEnv, ctl_node)
665
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200666 // this sequence implies workloads operations downtime
667 startCalicoUpgrade(pepperEnv, ctl_node)
Aleksei Kasatkind9d682e2018-12-12 14:51:59 +0100668 performCalicoConfigurationUpdateAndServicesRestart(pepperEnv, POOL, ctl_node)
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200669 completeCalicoUpgrade(pepperEnv, ctl_node)
Aleksei Kasatkin5ccea272018-12-06 17:34:58 +0100670 // no downtime is expected after this point
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200671 }
672
673 /*
ashestakovc030dac2019-01-11 11:34:54 +0200674 * Execute etcd update
675 */
676 if ((common.validInputParam('KUBERNETES_ETCD_SOURCE')) && (common.validInputParam('KUBERNETES_ETCD_SOURCE_HASH'))) {
677 overrideEtcdSource(pepperEnv)
678 }
679 def targetHosts = salt.getMinionsSorted(pepperEnv, "I@etcd:server")
680 for (t in targetHosts) {
681 performEtcdUpdateAndServicesRestart(pepperEnv, t)
682 }
683
684 /*
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200685 * Execute k8s update
Victor Ryzhenkinef34a022018-06-22 19:36:13 +0400686 */
687 if (updates.contains("ctl")) {
688 def target = CTL_TARGET
689
690 if (PER_NODE.toBoolean()) {
691 def targetHosts = salt.getMinionsSorted(pepperEnv, target)
692
693 for (t in targetHosts) {
Victor Ryzhenkin42e4b382018-09-11 17:57:56 +0400694 if (SIMPLE_UPGRADE.toBoolean()) {
695 performKubernetesControlUpdate(pepperEnv, t)
696 } else {
697 cordonNode(pepperEnv, t)
698 drainNode(pepperEnv, t)
699 regenerateCerts(pepperEnv, t)
Victor Ryzhenkin42e4b382018-09-11 17:57:56 +0400700 performKubernetesControlUpdate(pepperEnv, t)
Victor Ryzhenkinfd9677f2018-10-16 16:14:40 +0400701 updateAddonManager(pepperEnv, t)
Victor Ryzhenkin42e4b382018-09-11 17:57:56 +0400702 uncordonNode(pepperEnv, t)
703 }
Victor Ryzhenkinef34a022018-06-22 19:36:13 +0400704 }
705 } else {
706 performKubernetesControlUpdate(pepperEnv, target)
707 }
Victor Ryzhenkinfd9677f2018-10-16 16:14:40 +0400708 if (!SIMPLE_UPGRADE.toBoolean()) {
Aleksei Kasatkinff9d5b52018-10-26 11:47:46 +0200709 // Addons upgrade should be performed after all nodes will be upgraded
Victor Ryzhenkinfd9677f2018-10-16 16:14:40 +0400710 updateAddons(pepperEnv, target)
711 // Wait for 90 sec for addons reconciling
712 sleep(90)
713 }
Victor Ryzhenkinef34a022018-06-22 19:36:13 +0400714 }
715
716 if (updates.contains("cmp")) {
717 def target = CMP_TARGET
718
719 if (PER_NODE.toBoolean()) {
720 def targetHosts = salt.getMinionsSorted(pepperEnv, target)
721
722 for (t in targetHosts) {
Victor Ryzhenkin42e4b382018-09-11 17:57:56 +0400723 if (SIMPLE_UPGRADE.toBoolean()) {
724 performKubernetesComputeUpdate(pepperEnv, t)
725 } else {
726 cordonNode(pepperEnv, t)
727 drainNode(pepperEnv, t)
728 regenerateCerts(pepperEnv, t)
Victor Ryzhenkin42e4b382018-09-11 17:57:56 +0400729 performKubernetesComputeUpdate(pepperEnv, t)
730 uncordonNode(pepperEnv, t)
731 }
Victor Ryzhenkinef34a022018-06-22 19:36:13 +0400732 }
733 } else {
734 performKubernetesComputeUpdate(pepperEnv, target)
735 }
736 }
Victor Ryzhenkinae22a5a2018-10-12 15:52:27 +0400737
Aleksei Kasatkin5ccea272018-12-06 17:34:58 +0100738 def ctl_node = salt.getMinionsSorted(pepperEnv, CTL_TARGET)[0]
739 if (calicoEnabled(pepperEnv, ctl_node)) {
740 checkCalicoClusterState(pepperEnv, POOL)
741 }
Victor Ryzhenkineb543bf2019-01-18 06:34:26 +0400742 printVersionInfo(pepperEnv, ctl_node)
Aleksei Kasatkin5ccea272018-12-06 17:34:58 +0100743
Victor Ryzhenkinae22a5a2018-10-12 15:52:27 +0400744 if (CONFORMANCE_RUN_AFTER.toBoolean()) {
745 def target = CTL_TARGET
746 def mcp_repo = ARTIFACTORY_URL
747 def k8s_api = TEST_K8S_API_SERVER
748 firstTarget = salt.getFirstMinion(pepperEnv, target)
Victor Ryzhenkin723bd062018-12-11 17:09:06 +0400749 def containerd_enabled = containerDenabled(pepperEnv, firstTarget)
750 def containerd_installed = containerDinstalled(pepperEnv, firstTarget)
751 def conformance_pod_ready = conformancePodDefExists(pepperEnv, firstTarget)
752 if (containerd_enabled && containerd_installed && conformance_pod_ready) {
753 def config = ['master': pepperEnv,
754 'target': firstTarget,
755 'junitResults': false,
756 'autodetect': true]
757 test.executeConformance(config)
758 } else {
759 executeConformance(pepperEnv, firstTarget, k8s_api, mcp_repo)
760 }
Victor Ryzhenkinae22a5a2018-10-12 15:52:27 +0400761 }
Victor Ryzhenkinef34a022018-06-22 19:36:13 +0400762 } catch (Throwable e) {
763 // If there was an error or exception thrown, the build failed
764 currentBuild.result = "FAILURE"
765 currentBuild.description = currentBuild.description ? e.message + " " + currentBuild.description : e.message
766 throw e
767 }
768 }
Victor Ryzhenkin7fda5c42019-01-18 22:17:57 +0400769}