blob: 03ab2445289b4c7acf86bd0c1028603492594cdb [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.
Tomáš Kukrál91e49252017-05-09 14:40:26 +02006 * EMAIL_ADDRESS Email to send a created tar file
Sergey Galkin8b87f6e2018-10-24 18:40:13 +04007 * CREDENTIALS_ID Credentials id for git
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
azvyagintsevb8ddb492018-09-12 14:59:45 +030018slaveNode = env.SLAVE_NODE ?: 'python&&docker'
Ivan Berezovskiy46b7bbc2018-10-30 22:32:13 +040019gerritCredentials = env.CREDENTIALS_ID ?: 'gerrit'
azvyagintsevf252b592018-08-13 18:39:14 +030020
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +000021timeout(time: 1, unit: 'HOURS') {
azvyagintsev636493c2018-09-12 17:17:05 +030022 node(slaveNode) {
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +000023 def templateEnv = "${env.WORKSPACE}/template"
24 def modelEnv = "${env.WORKSPACE}/model"
25 def testEnv = "${env.WORKSPACE}/test"
26 def pipelineEnv = "${env.WORKSPACE}/pipelines"
Tomáš Kukrál9f6260f2017-03-29 23:58:26 +020027
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +000028 try {
29 def templateContext = readYaml text: env.COOKIECUTTER_TEMPLATE_CONTEXT
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +000030 // TODO add check's for critical var's
31 def context = templateContext['default_context']
32 // Use mcpVersion git tag if not specified branch for cookiecutter-templates
azvyagintsevab3f48c2018-11-05 15:16:07 +020033 if (!context.get('cookiecutter_template_branch', false)) {
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +000034 context['cookiecutter_template_branch'] = context['mcp_version']
35 // Don't have nightly/testing/stable for cookiecutter-templates repo, therefore use master
36 if (["nightly", "testing", "stable"].contains(context['mcp_version'])) {
37 common.warningMsg("Fetching cookiecutterTemplate from master!")
38 context['cookiecutter_template_branch'] = 'master'
azvyagintsev636493c2018-09-12 17:17:05 +030039 }
azvyagintsevd209f7c2018-10-25 18:36:31 +030040 }
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +000041 // Use context['mcp_version'] git tag if not specified branch for reclass-system
azvyagintsevab3f48c2018-11-05 15:16:07 +020042 if (!context.get('shared_reclass_branch', false)) {
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +000043 context['shared_reclass_branch'] = context['mcp_version']
44 // Don't have nightly/testing for reclass-system repo, therefore use master
45 if (["nightly", "testing", "stable"].contains(context['mcp_version'])) {
46 common.warningMsg("Fetching reclass-system from master!")
47 context['shared_reclass_branch'] = 'master'
48 }
49 }
50 //
51 distribRevision = context['mcp_version']
52 if (['master'].contains(context['mcp_version'])) {
53 distribRevision = 'nightly'
54 }
55 if (distribRevision.contains('/')) {
56 distribRevision = distribRevision.split('/')[-1]
57 }
58 //
59 def cutterEnv = "${env.WORKSPACE}/cutter"
60 def systemEnv = "${modelEnv}/classes/system"
61 def testResult = false
62 def user
63 wrap([$class: 'BuildUser']) {
64 user = env.BUILD_USER_ID
65 }
66 currentBuild.description = context['cluster_name']
67 common.infoMsg("Using context:\n" + context)
68 print prettyPrint(toJson(context))
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +000069 stage('Download Cookiecutter template') {
70 sh(script: 'find . -mindepth 1 -delete > /dev/null || true')
71 checkout([
72 $class : 'GitSCM',
73 branches : [[name: 'FETCH_HEAD'],],
74 extensions : [[$class: 'RelativeTargetDirectory', relativeTargetDir: templateEnv]],
75 userRemoteConfigs: [[url: context['cookiecutter_template_url'], refspec: context['cookiecutter_template_branch'], credentialsId: gerritCredentials],],
76 ])
77 }
78 stage('Create empty reclass model') {
79 dir(path: modelEnv) {
80 sh "rm -rfv .git; git init"
81 sshagent(credentials: [gerritCredentials]) {
82 sh "git submodule add ${context['shared_reclass_url']} 'classes/system'"
83 }
84 }
85 checkout([
86 $class : 'GitSCM',
87 branches : [[name: 'FETCH_HEAD'],],
88 extensions : [[$class: 'RelativeTargetDirectory', relativeTargetDir: systemEnv]],
89 userRemoteConfigs: [[url: context['shared_reclass_url'], refspec: context['shared_reclass_branch'], credentialsId: gerritCredentials],],
90 ])
91 git.commitGitChanges(modelEnv, "Added new shared reclass submodule", "${user}@localhost", "${user}")
92 }
93
94 stage('Generate model') {
95 python.setupCookiecutterVirtualenv(cutterEnv)
azvyagintsevab3f48c2018-11-05 15:16:07 +020096 // FIXME refactor generateModel
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +000097 python.generateModel(common2.dumpYAML(['default_context': context]), 'default_context', context['salt_master_hostname'], cutterEnv, modelEnv, templateEnv, false)
98 git.commitGitChanges(modelEnv, "Create model ${context['cluster_name']}", "${user}@localhost", "${user}")
99 }
100
101 stage("Test") {
102 if (env.TEST_MODEL.toBoolean()) {
103 // Check if we are going to test bleeding-edge release, which doesn't have binary release yet
azvyagintsev0a38ec22018-11-19 19:18:02 +0200104 if (!common.checkRemoteBinary([mcp_version: distribRevision]).linux_system_repo_url) {
Aleksey Zvyagintsevb16902d2018-10-29 12:33:48 +0000105 common.errorMsg("Binary release: ${distribRevision} not exist. Fallback to 'proposed'! ")
106 distribRevision = 'proposed'
107 }
108 sh("cp -r ${modelEnv} ${testEnv}")
109 def DockerCName = "${env.JOB_NAME.toLowerCase()}_${env.BUILD_TAG.toLowerCase()}"
110 common.infoMsg("Attempt to run test against distribRevision: ${distribRevision}")
111 try {
112 def config = [
113 'dockerHostname' : "${context['salt_master_hostname']}.${context['cluster_domain']}",
114 'reclassEnv' : testEnv,
115 'distribRevision' : distribRevision,
116 'dockerContainerName': DockerCName,
117 'testContext' : 'salt-model-node'
118 ]
119 testResult = saltModelTesting.testNode(config)
120 common.infoMsg("Test finished: SUCCESS")
121 } catch (Exception ex) {
122 common.warningMsg("Test finished: FAILED")
123 testResult = false
124 }
125 } else {
126 common.warningMsg("Test stage has been skipped!")
127 }
128 }
129 stage("Generate config drives") {
130 // apt package genisoimage is required for this stage
131
132 // download create-config-drive
133 // FIXME: that should be refactored, to use git clone - to be able download it from custom repo.
134 def mcpCommonScriptsBranch = context['mcp_common_scripts_branch']
135 if (mcpCommonScriptsBranch == '') {
136 mcpCommonScriptsBranch = context['mcp_version']
137 // Don't have n/t/s for mcp-common-scripts repo, therefore use master
138 if (["nightly", "testing", "stable"].contains(context['mcp_version'])) {
139 common.warningMsg("Fetching mcp-common-scripts from master!")
140 mcpCommonScriptsBranch = 'master'
141 }
142 }
143 def commonScriptsRepoUrl = context['mcp_common_scripts_repo'] ?: 'ssh://gerrit.mcp.mirantis.com:29418/mcp/mcp-common-scripts'
144 checkout([
145 $class : 'GitSCM',
146 branches : [[name: 'FETCH_HEAD'],],
147 extensions : [[$class: 'RelativeTargetDirectory', relativeTargetDir: 'mcp-common-scripts']],
148 userRemoteConfigs: [[url: commonScriptsRepoUrl, refspec: mcpCommonScriptsBranch, credentialsId: gerritCredentials],],
149 ])
150
151 sh 'cp mcp-common-scripts/config-drive/create_config_drive.sh create-config-drive && chmod +x create-config-drive'
152 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'
153
154 sh "git clone --mirror https://github.com/Mirantis/mk-pipelines.git ${pipelineEnv}/mk-pipelines"
155 sh "git clone --mirror https://github.com/Mirantis/pipeline-library.git ${pipelineEnv}/pipeline-library"
156 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"
157
158 // load data from model
159 def smc = [:]
160 smc['SALT_MASTER_MINION_ID'] = "${context['salt_master_hostname']}.${context['cluster_domain']}"
161 smc['SALT_MASTER_DEPLOY_IP'] = context['salt_master_management_address']
162 smc['DEPLOY_NETWORK_GW'] = context['deploy_network_gateway']
163 smc['DEPLOY_NETWORK_NETMASK'] = context['deploy_network_netmask']
164 if (context.get('deploy_network_mtu')) {
165 smc['DEPLOY_NETWORK_MTU'] = context['deploy_network_mtu']
166 }
167 smc['DNS_SERVERS'] = context['dns_server01']
168 smc['MCP_VERSION'] = "${context['mcp_version']}"
169 if (context['local_repositories'] == 'True') {
170 def localRepoIP = context['local_repo_url']
171 smc['MCP_SALT_REPO_KEY'] = "http://${localRepoIP}/public.gpg"
172 smc['MCP_SALT_REPO_URL'] = "http://${localRepoIP}/ubuntu-xenial"
173 smc['PIPELINES_FROM_ISO'] = 'false'
174 smc['PIPELINE_REPO_URL'] = "http://${localRepoIP}:8088"
175 smc['LOCAL_REPOS'] = 'true'
176 }
177 if (context['upstream_proxy_enabled'] == 'True') {
178 if (context['upstream_proxy_auth_enabled'] == 'True') {
179 smc['http_proxy'] = 'http://' + context['upstream_proxy_user'] + ':' + context['upstream_proxy_password'] + '@' + context['upstream_proxy_address'] + ':' + context['upstream_proxy_port']
180 smc['https_proxy'] = 'http://' + context['upstream_proxy_user'] + ':' + context['upstream_proxy_password'] + '@' + context['upstream_proxy_address'] + ':' + context['upstream_proxy_port']
181 } else {
182 smc['http_proxy'] = 'http://' + context['upstream_proxy_address'] + ':' + context['upstream_proxy_port']
183 smc['https_proxy'] = 'http://' + context['upstream_proxy_address'] + ':' + context['upstream_proxy_port']
184 }
185 }
186
187 for (i in common.entries(smc)) {
188 sh "sed -i 's,${i[0]}=.*,${i[0]}=${i[1]},' user_data"
189 }
190
191 // create cfg config-drive
192 sh "./create-config-drive ${args}"
193 sh("mkdir output-${context['cluster_name']} && mv ${context['salt_master_hostname']}.${context['cluster_domain']}-config.iso output-${context['cluster_name']}/")
194
195 // save cfg iso to artifacts
196 archiveArtifacts artifacts: "output-${context['cluster_name']}/${context['salt_master_hostname']}.${context['cluster_domain']}-config.iso"
197
198 if (context['local_repositories'] == 'True') {
199 def aptlyServerHostname = context.aptly_server_hostname
200 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"
201
202 def smc_apt = [:]
203 smc_apt['SALT_MASTER_DEPLOY_IP'] = context['salt_master_management_address']
204 smc_apt['APTLY_DEPLOY_IP'] = context['aptly_server_deploy_address']
205 smc_apt['APTLY_DEPLOY_NETMASK'] = context['deploy_network_netmask']
206 smc_apt['APTLY_MINION_ID'] = "${aptlyServerHostname}.${context['cluster_domain']}"
207
208 for (i in common.entries(smc_apt)) {
209 sh "sed -i \"s,export ${i[0]}=.*,export ${i[0]}=${i[1]},\" mirror_config"
210 }
211
212 // create apt config-drive
213 sh "./create-config-drive --user-data mirror_config --hostname ${aptlyServerHostname} ${aptlyServerHostname}.${context['cluster_domain']}-config.iso"
214 sh("mv ${aptlyServerHostname}.${context['cluster_domain']}-config.iso output-${context['cluster_name']}/")
215
216 // save apt iso to artifacts
217 archiveArtifacts artifacts: "output-${context['cluster_name']}/${aptlyServerHostname}.${context['cluster_domain']}-config.iso"
218 }
219 }
220
221 stage('Save changes reclass model') {
222 sh(returnStatus: true, script: "tar -czf output-${context['cluster_name']}/${context['cluster_name']}.tar.gz --exclude='*@tmp' -C ${modelEnv} .")
223 archiveArtifacts artifacts: "output-${context['cluster_name']}/${context['cluster_name']}.tar.gz"
224
225 if (EMAIL_ADDRESS != null && EMAIL_ADDRESS != "") {
226 emailext(to: EMAIL_ADDRESS,
227 attachmentsPattern: "output-${context['cluster_name']}/*",
228 body: "Mirantis Jenkins\n\nRequested reclass model ${context['cluster_name']} has been created and attached to this email.\nEnjoy!\n\nMirantis",
229 subject: "Your Salt model ${context['cluster_name']}")
230 }
231 dir("output-${context['cluster_name']}") {
232 deleteDir()
233 }
234 }
235
236 // Fail, but leave possibility to get failed artifacts
237 if (!testResult && env.TEST_MODEL.toBoolean()) {
238 common.warningMsg('Test finished: FAILURE. Please check logs and\\or debug failed model manually!')
239 error('Test stage finished: FAILURE')
240 }
241
242 } catch (Throwable e) {
243 currentBuild.result = "FAILURE"
244 currentBuild.description = currentBuild.description ? e.message + " " + currentBuild.description : e.message
245 throw e
246 } finally {
247 stage('Clean workspace directories') {
248 sh(script: 'find . -mindepth 1 -delete > /dev/null || true')
249 }
250 // common.sendNotification(currentBuild.result,"",["slack"])
Ruslan Kamaldinov6feef402017-08-02 16:55:58 +0400251 }
Tomáš Kukrál7ded3642017-03-27 15:52:51 +0200252 }
Mikhail Ivanov9f812922017-11-07 18:52:02 +0400253}