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