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