blob: 62a6e002c00b632a982db5fc81e18088c36e9648 [file] [log] [blame]
Tomáš Kukrál7ded3642017-03-27 15:52:51 +02001/**
2 * Generate cookiecutter cluster by individual products
3 *
4 * Expected parameters:
Tomáš Kukrál7ded3642017-03-27 15:52:51 +02005 * COOKIECUTTER_TEMPLATE_CONTEXT Context parameters for the template generation.
Sergey Galkin8b87f6e2018-10-24 18:40:13 +04006 * CREDENTIALS_ID Credentials id for git
azvyagintsev6d678da2018-11-28 21:19:06 +02007 * TEST_MODEL Run syntax tests for model
azvyagintsev3ed704f2018-07-09 15:49:27 +03008 **/
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +00009import static groovy.json.JsonOutput.toJson
10import static groovy.json.JsonOutput.prettyPrint
Tomáš Kukrál7ded3642017-03-27 15:52:51 +020011
12common = new com.mirantis.mk.Common()
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +000013common2 = new com.mirantis.mcp.Common()
Tomáš Kukrál7ded3642017-03-27 15:52:51 +020014git = new com.mirantis.mk.Git()
15python = new com.mirantis.mk.Python()
chnyda89191012017-05-29 15:38:35 +020016saltModelTesting = new com.mirantis.mk.SaltModelTesting()
Tomáš Kukrál7ded3642017-03-27 15:52:51 +020017
azvyagintsev6d678da2018-11-28 21:19:06 +020018slaveNode = env.getProperty('SLAVE_NODE') ?: 'python&&docker'
19gerritCredentials = env.getProperty('CREDENTIALS_ID') ?: 'gerrit'
20runTestModel = (env.getProperty('TEST_MODEL') ?: true).toBoolean()
azvyagintsev866b19a2018-11-20 18:21:43 +020021distribRevision = 'proposed'
22gitGuessedVersion = false
23
24
25def globalVariatorsUpdate() {
26 def templateContext = readYaml text: env.COOKIECUTTER_TEMPLATE_CONTEXT
27 def context = templateContext['default_context']
28 // TODO add more check's for critical var's
29 // Since we can't pin to any '_branch' variable from context, to identify 'default git revision' -
30 // because each of them, might be 'refs/' variable, we need to add some tricky trigger of using
31 // 'release/XXX' logic. This is totall guess - so,if even those one failed, to definitely must pass
32 // correct variable finally!
33 [context.get('cookiecutter_template_branch'), context.get('shared_reclass_branch'), context.get('mcp_common_scripts_branch')].any { branch ->
34 if (branch.toString().startsWith('release/')) {
35 gitGuessedVersion = branch
36 return true
37 }
38 }
39
40 // Use mcpVersion git tag if not specified branch for cookiecutter-templates
41 if (!context.get('cookiecutter_template_branch')) {
42 context['cookiecutter_template_branch'] = gitGuessedVersion ?: context['mcp_version']
43 }
44 // Don't have n/t/s for cookiecutter-templates repo, therefore use master
45 if (["nightly", "testing", "stable"].contains(context['cookiecutter_template_branch'])) {
46 context['cookiecutter_template_branch'] = 'master'
47 }
48 if (!context.get('shared_reclass_branch')) {
49 context['shared_reclass_branch'] = gitGuessedVersion ?: context['mcp_version']
50 }
51 // Don't have nightly/testing for reclass-system repo, therefore use master
52 if (["nightly", "testing", "stable"].contains(context['shared_reclass_branch'])) {
53 context['shared_reclass_branch'] = 'master'
54 }
55 if (!context.get('mcp_common_scripts_branch')) {
56 // Pin exactly to CC branch, since it might use 'release/XXX' format
57 context['mcp_common_scripts_branch'] = gitGuessedVersion ?: context['mcp_version']
58 }
59 // Don't have n/t/s for mcp-common-scripts repo, therefore use master
60 if (["nightly", "testing", "stable"].contains(context['mcp_common_scripts_branch'])) {
61 context['mcp_common_scripts_branch'] = 'master'
62 }
63 //
64 distribRevision = context['mcp_version']
65 if (['master'].contains(context['mcp_version'])) {
66 distribRevision = 'nightly'
67 }
68 if (distribRevision.contains('/')) {
69 distribRevision = distribRevision.split('/')[-1]
70 }
71 // Check if we are going to test bleeding-edge release, which doesn't have binary release yet
72 if (!common.checkRemoteBinary([mcp_version: distribRevision]).linux_system_repo_url) {
73 common.warningMsg("Binary release: ${distribRevision} not exist. Fallback to 'proposed'! ")
74 distribRevision = 'proposed'
75 }
azvyagintsev5400d1d2018-12-11 13:19:29 +020076 // (azvyagintsev) WA for PROD-25732
77 if (context.cookiecutter_template_url.contains('gerrit.mcp.mirantis.com/mk/cookiecutter-templates')) {
78 common.warningMsg('Apply WA for PROD-25732')
79 context.cookiecutter_template_url = 'ssh://gerrit.mcp.mirantis.com:29418/mk/cookiecutter-templates.git'
80 }
azvyagintsev866b19a2018-11-20 18:21:43 +020081 common.warningMsg("Fetching:\n" +
82 "DISTRIB_REVISION from ${distribRevision}")
83 common.infoMsg("Using context:\n" + context)
84 print prettyPrint(toJson(context))
85 return context
86
87}
azvyagintsevf252b592018-08-13 18:39:14 +030088
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +000089timeout(time: 1, unit: 'HOURS') {
azvyagintsev636493c2018-09-12 17:17:05 +030090 node(slaveNode) {
azvyagintsev866b19a2018-11-20 18:21:43 +020091 def context = globalVariatorsUpdate()
azvyagintsev6d678da2018-11-28 21:19:06 +020092 def RequesterEmail = context.get('email_address', '')
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +000093 def templateEnv = "${env.WORKSPACE}/template"
94 def modelEnv = "${env.WORKSPACE}/model"
95 def testEnv = "${env.WORKSPACE}/test"
96 def pipelineEnv = "${env.WORKSPACE}/pipelines"
Tomáš Kukrál9f6260f2017-03-29 23:58:26 +020097
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +000098 try {
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +000099 //
100 def cutterEnv = "${env.WORKSPACE}/cutter"
101 def systemEnv = "${modelEnv}/classes/system"
102 def testResult = false
103 def user
104 wrap([$class: 'BuildUser']) {
105 user = env.BUILD_USER_ID
106 }
azvyagintsev6d678da2018-11-28 21:19:06 +0200107 currentBuild.description = "${context['cluster_name']} ${RequesterEmail}"
azvyagintsev866b19a2018-11-20 18:21:43 +0200108
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +0000109 stage('Download Cookiecutter template') {
110 sh(script: 'find . -mindepth 1 -delete > /dev/null || true')
111 checkout([
112 $class : 'GitSCM',
113 branches : [[name: 'FETCH_HEAD'],],
114 extensions : [[$class: 'RelativeTargetDirectory', relativeTargetDir: templateEnv]],
115 userRemoteConfigs: [[url: context['cookiecutter_template_url'], refspec: context['cookiecutter_template_branch'], credentialsId: gerritCredentials],],
116 ])
117 }
118 stage('Create empty reclass model') {
119 dir(path: modelEnv) {
120 sh "rm -rfv .git; git init"
121 sshagent(credentials: [gerritCredentials]) {
122 sh "git submodule add ${context['shared_reclass_url']} 'classes/system'"
123 }
124 }
125 checkout([
126 $class : 'GitSCM',
127 branches : [[name: 'FETCH_HEAD'],],
128 extensions : [[$class: 'RelativeTargetDirectory', relativeTargetDir: systemEnv]],
129 userRemoteConfigs: [[url: context['shared_reclass_url'], refspec: context['shared_reclass_branch'], credentialsId: gerritCredentials],],
130 ])
131 git.commitGitChanges(modelEnv, "Added new shared reclass submodule", "${user}@localhost", "${user}")
132 }
133
134 stage('Generate model') {
Dmitry Pyzhov089fb4f2018-12-11 16:58:00 +0300135 // GNUPGHOME environment variable is required for all gpg commands
136 // and for python.generateModel execution
137 withEnv(["GNUPGHOME=${env.WORKSPACE}/gpghome"]) {
138 if (context['secrets_encryption_enabled'] == 'True') {
139 sh "mkdir gpghome; chmod 700 gpghome"
Dmitry Pyzhovb5c74c72018-12-17 22:08:50 +0300140 def secretKeyID = RequesterEmail ?: "salt@${context['cluster_domain']}".toString()
Dmitry Pyzhov089fb4f2018-12-11 16:58:00 +0300141 if (!context.get('secrets_encryption_private_key')) {
142 def batchData = """
Denis Egorenko1a699c42019-05-16 14:25:40 +0400143 %echo Generating a basic OpenPGP key for Salt-Master
144 %no-protection
Dmitry Pyzhov089fb4f2018-12-11 16:58:00 +0300145 Key-Type: 1
146 Key-Length: 4096
147 Expire-Date: 0
148 Name-Real: ${context['salt_master_hostname']}.${context['cluster_domain']}
149 Name-Email: ${secretKeyID}
Denis Egorenko1a699c42019-05-16 14:25:40 +0400150 %commit
151 %echo done
Dmitry Pyzhov089fb4f2018-12-11 16:58:00 +0300152 """.stripIndent()
153 writeFile file:'gpg-batch.txt', text:batchData
154 sh "gpg --gen-key --batch < gpg-batch.txt"
155 sh "gpg --export-secret-key -a ${secretKeyID} > gpgkey.asc"
156 } else {
157 writeFile file:'gpgkey.asc', text:context['secrets_encryption_private_key']
158 sh "gpg --import gpgkey.asc"
Denis Egorenko1a699c42019-05-16 14:25:40 +0400159 secretKeyID = sh(returnStdout: true, script: 'gpg --list-secret-keys --with-colons | grep -E "^sec" | awk -F: \'{print \$5}\'').trim()
Dmitry Pyzhov089fb4f2018-12-11 16:58:00 +0300160 }
161 context['secrets_encryption_key_id'] = secretKeyID
162 }
Stanislav Riazanovda45ea02018-12-21 16:12:50 +0400163 if (context.get('cfg_failsafe_ssh_public_key')) {
164 writeFile file:'failsafe-ssh-key.pub', text:context['cfg_failsafe_ssh_public_key']
165 }
Dmitry Pyzhov089fb4f2018-12-11 16:58:00 +0300166 python.setupCookiecutterVirtualenv(cutterEnv)
167 // FIXME refactor generateModel
168 python.generateModel(common2.dumpYAML(['default_context': context]), 'default_context', context['salt_master_hostname'], cutterEnv, modelEnv, templateEnv, false)
169 git.commitGitChanges(modelEnv, "Create model ${context['cluster_name']}", "${user}@localhost", "${user}")
170 }
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +0000171 }
172
173 stage("Test") {
azvyagintsev6d678da2018-11-28 21:19:06 +0200174 if (runTestModel) {
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +0000175 // Check if we are going to test bleeding-edge release, which doesn't have binary release yet
azvyagintsev0a38ec22018-11-19 19:18:02 +0200176 if (!common.checkRemoteBinary([mcp_version: distribRevision]).linux_system_repo_url) {
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +0000177 common.errorMsg("Binary release: ${distribRevision} not exist. Fallback to 'proposed'! ")
178 distribRevision = 'proposed'
179 }
180 sh("cp -r ${modelEnv} ${testEnv}")
181 def DockerCName = "${env.JOB_NAME.toLowerCase()}_${env.BUILD_TAG.toLowerCase()}"
182 common.infoMsg("Attempt to run test against distribRevision: ${distribRevision}")
183 try {
184 def config = [
185 'dockerHostname' : "${context['salt_master_hostname']}.${context['cluster_domain']}",
186 'reclassEnv' : testEnv,
187 'distribRevision' : distribRevision,
188 'dockerContainerName': DockerCName,
189 'testContext' : 'salt-model-node'
190 ]
191 testResult = saltModelTesting.testNode(config)
192 common.infoMsg("Test finished: SUCCESS")
193 } catch (Exception ex) {
194 common.warningMsg("Test finished: FAILED")
195 testResult = false
196 }
197 } else {
198 common.warningMsg("Test stage has been skipped!")
199 }
200 }
201 stage("Generate config drives") {
202 // apt package genisoimage is required for this stage
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +0000203 // download create-config-drive
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +0000204 def commonScriptsRepoUrl = context['mcp_common_scripts_repo'] ?: 'ssh://gerrit.mcp.mirantis.com:29418/mcp/mcp-common-scripts'
205 checkout([
206 $class : 'GitSCM',
207 branches : [[name: 'FETCH_HEAD'],],
208 extensions : [[$class: 'RelativeTargetDirectory', relativeTargetDir: 'mcp-common-scripts']],
azvyagintsev866b19a2018-11-20 18:21:43 +0200209 userRemoteConfigs: [[url: commonScriptsRepoUrl, refspec: context['mcp_common_scripts_branch'], credentialsId: gerritCredentials],],
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +0000210 ])
211
212 sh 'cp mcp-common-scripts/config-drive/create_config_drive.sh create-config-drive && chmod +x create-config-drive'
213 sh '[ -f mcp-common-scripts/config-drive/master_config.sh ] && cp mcp-common-scripts/config-drive/master_config.sh user_data || cp mcp-common-scripts/config-drive/master_config.yaml user_data'
214
215 sh "git clone --mirror https://github.com/Mirantis/mk-pipelines.git ${pipelineEnv}/mk-pipelines"
216 sh "git clone --mirror https://github.com/Mirantis/pipeline-library.git ${pipelineEnv}/pipeline-library"
217 args = "--user-data user_data --hostname ${context['salt_master_hostname']} --model ${modelEnv} --mk-pipelines ${pipelineEnv}/mk-pipelines/ --pipeline-library ${pipelineEnv}/pipeline-library/ ${context['salt_master_hostname']}.${context['cluster_domain']}-config.iso"
Dmitry Pyzhov089fb4f2018-12-11 16:58:00 +0300218 if (context['secrets_encryption_enabled'] == 'True') {
219 args = "--gpg-key gpgkey.asc " + args
220 }
Stanislav Riazanovda45ea02018-12-21 16:12:50 +0400221 if (context.get('cfg_failsafe_ssh_public_key')) {
222 args = "--ssh-key failsafe-ssh-key.pub " + args
223 }
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +0000224
225 // load data from model
226 def smc = [:]
227 smc['SALT_MASTER_MINION_ID'] = "${context['salt_master_hostname']}.${context['cluster_domain']}"
228 smc['SALT_MASTER_DEPLOY_IP'] = context['salt_master_management_address']
229 smc['DEPLOY_NETWORK_GW'] = context['deploy_network_gateway']
230 smc['DEPLOY_NETWORK_NETMASK'] = context['deploy_network_netmask']
231 if (context.get('deploy_network_mtu')) {
232 smc['DEPLOY_NETWORK_MTU'] = context['deploy_network_mtu']
233 }
234 smc['DNS_SERVERS'] = context['dns_server01']
235 smc['MCP_VERSION'] = "${context['mcp_version']}"
236 if (context['local_repositories'] == 'True') {
237 def localRepoIP = context['local_repo_url']
238 smc['MCP_SALT_REPO_KEY'] = "http://${localRepoIP}/public.gpg"
239 smc['MCP_SALT_REPO_URL'] = "http://${localRepoIP}/ubuntu-xenial"
240 smc['PIPELINES_FROM_ISO'] = 'false'
241 smc['PIPELINE_REPO_URL'] = "http://${localRepoIP}:8088"
242 smc['LOCAL_REPOS'] = 'true'
243 }
244 if (context['upstream_proxy_enabled'] == 'True') {
245 if (context['upstream_proxy_auth_enabled'] == 'True') {
246 smc['http_proxy'] = 'http://' + context['upstream_proxy_user'] + ':' + context['upstream_proxy_password'] + '@' + context['upstream_proxy_address'] + ':' + context['upstream_proxy_port']
247 smc['https_proxy'] = 'http://' + context['upstream_proxy_user'] + ':' + context['upstream_proxy_password'] + '@' + context['upstream_proxy_address'] + ':' + context['upstream_proxy_port']
248 } else {
249 smc['http_proxy'] = 'http://' + context['upstream_proxy_address'] + ':' + context['upstream_proxy_port']
250 smc['https_proxy'] = 'http://' + context['upstream_proxy_address'] + ':' + context['upstream_proxy_port']
251 }
252 }
253
254 for (i in common.entries(smc)) {
255 sh "sed -i 's,${i[0]}=.*,${i[0]}=${i[1]},' user_data"
256 }
257
258 // create cfg config-drive
259 sh "./create-config-drive ${args}"
260 sh("mkdir output-${context['cluster_name']} && mv ${context['salt_master_hostname']}.${context['cluster_domain']}-config.iso output-${context['cluster_name']}/")
261
262 // save cfg iso to artifacts
263 archiveArtifacts artifacts: "output-${context['cluster_name']}/${context['salt_master_hostname']}.${context['cluster_domain']}-config.iso"
264
265 if (context['local_repositories'] == 'True') {
266 def aptlyServerHostname = context.aptly_server_hostname
267 sh "[ -f mcp-common-scripts/config-drive/mirror_config.yaml ] && cp mcp-common-scripts/config-drive/mirror_config.yaml mirror_config || cp mcp-common-scripts/config-drive/mirror_config.sh mirror_config"
268
269 def smc_apt = [:]
270 smc_apt['SALT_MASTER_DEPLOY_IP'] = context['salt_master_management_address']
271 smc_apt['APTLY_DEPLOY_IP'] = context['aptly_server_deploy_address']
272 smc_apt['APTLY_DEPLOY_NETMASK'] = context['deploy_network_netmask']
273 smc_apt['APTLY_MINION_ID'] = "${aptlyServerHostname}.${context['cluster_domain']}"
274
275 for (i in common.entries(smc_apt)) {
276 sh "sed -i \"s,export ${i[0]}=.*,export ${i[0]}=${i[1]},\" mirror_config"
277 }
278
279 // create apt config-drive
280 sh "./create-config-drive --user-data mirror_config --hostname ${aptlyServerHostname} ${aptlyServerHostname}.${context['cluster_domain']}-config.iso"
281 sh("mv ${aptlyServerHostname}.${context['cluster_domain']}-config.iso output-${context['cluster_name']}/")
282
283 // save apt iso to artifacts
284 archiveArtifacts artifacts: "output-${context['cluster_name']}/${aptlyServerHostname}.${context['cluster_domain']}-config.iso"
285 }
286 }
287
288 stage('Save changes reclass model') {
289 sh(returnStatus: true, script: "tar -czf output-${context['cluster_name']}/${context['cluster_name']}.tar.gz --exclude='*@tmp' -C ${modelEnv} .")
290 archiveArtifacts artifacts: "output-${context['cluster_name']}/${context['cluster_name']}.tar.gz"
291
azvyagintsev5400d1d2018-12-11 13:19:29 +0200292 if (RequesterEmail != '' && !RequesterEmail.contains('example')) {
azvyagintsev6d678da2018-11-28 21:19:06 +0200293 emailext(to: RequesterEmail,
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +0000294 attachmentsPattern: "output-${context['cluster_name']}/*",
295 body: "Mirantis Jenkins\n\nRequested reclass model ${context['cluster_name']} has been created and attached to this email.\nEnjoy!\n\nMirantis",
296 subject: "Your Salt model ${context['cluster_name']}")
297 }
298 dir("output-${context['cluster_name']}") {
299 deleteDir()
300 }
301 }
302
303 // Fail, but leave possibility to get failed artifacts
azvyagintsev6d678da2018-11-28 21:19:06 +0200304 if (!testResult && runTestModel) {
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +0000305 common.warningMsg('Test finished: FAILURE. Please check logs and\\or debug failed model manually!')
306 error('Test stage finished: FAILURE')
307 }
308
309 } catch (Throwable e) {
310 currentBuild.result = "FAILURE"
311 currentBuild.description = currentBuild.description ? e.message + " " + currentBuild.description : e.message
312 throw e
313 } finally {
314 stage('Clean workspace directories') {
315 sh(script: 'find . -mindepth 1 -delete > /dev/null || true')
316 }
317 // common.sendNotification(currentBuild.result,"",["slack"])
Ruslan Kamaldinov6feef402017-08-02 16:55:58 +0400318 }
Tomáš Kukrál7ded3642017-03-27 15:52:51 +0200319 }
Mikhail Ivanov9f812922017-11-07 18:52:02 +0400320}