Tools to make Jenkins jobs from templates
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

properties.py 39KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. # Copyright 2012 Hewlett-Packard Development Company, L.P.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. # License for the specific language governing permissions and limitations
  13. # under the License.
  14. """
  15. The Properties module supplies a wide range of options that are
  16. implemented as Jenkins job properties.
  17. **Component**: properties
  18. :Macro: property
  19. :Entry Point: jenkins_jobs.properties
  20. Example::
  21. job:
  22. name: test_job
  23. properties:
  24. - github:
  25. url: https://github.com/openstack-infra/jenkins-job-builder/
  26. """
  27. import logging
  28. import pkg_resources
  29. import xml.etree.ElementTree as XML
  30. from jenkins_jobs.errors import InvalidAttributeError
  31. from jenkins_jobs.errors import JenkinsJobsException
  32. from jenkins_jobs.errors import MissingAttributeError
  33. from jenkins_jobs.errors import AttributeConflictError
  34. import jenkins_jobs.modules.base
  35. import jenkins_jobs.modules.helpers as helpers
  36. def builds_chain_fingerprinter(registry, xml_parent, data):
  37. """yaml: builds-chain-fingerprinter
  38. Builds chain fingerprinter.
  39. Requires the Jenkins :jenkins-wiki:`Builds chain fingerprinter Plugin
  40. <Builds+chain+fingerprinter>`.
  41. :arg bool per-builds-chain: enable builds hierarchy fingerprinting
  42. (default false)
  43. :arg bool per-job-chain: enable jobs hierarchy fingerprinting
  44. (default false)
  45. Example:
  46. .. literalinclude:: /../../tests/properties/fixtures/fingerprinter.yaml
  47. :language: yaml
  48. """
  49. fingerprinter = XML.SubElement(xml_parent,
  50. 'org.jenkinsci.plugins.'
  51. 'buildschainfingerprinter.'
  52. 'AutomaticFingerprintJobProperty')
  53. mapping = [
  54. ('per-builds-chain', 'isPerBuildsChainEnabled', False),
  55. ('per-job-chain', 'isPerJobsChainEnabled', False),
  56. ]
  57. helpers.convert_mapping_to_xml(
  58. fingerprinter, data, mapping, fail_required=True)
  59. def ownership(registry, xml_parent, data):
  60. """yaml: ownership
  61. Plugin provides explicit ownership for jobs and slave nodes.
  62. Requires the Jenkins :jenkins-wiki:`Ownership Plugin <Ownership+Plugin>`.
  63. :arg bool enabled: whether ownership enabled (default : true)
  64. :arg str owner: the owner of job
  65. :arg list co-owners: list of job co-owners
  66. Example:
  67. .. literalinclude:: /../../tests/properties/fixtures/ownership.yaml
  68. :language: yaml
  69. """
  70. ownership_plugin = XML.SubElement(
  71. xml_parent,
  72. 'com.synopsys.arc.jenkins.plugins.ownership.jobs.JobOwnerJobProperty')
  73. ownership = XML.SubElement(ownership_plugin, 'ownership')
  74. owner = str(data.get('enabled', True)).lower()
  75. XML.SubElement(ownership, 'ownershipEnabled').text = owner
  76. XML.SubElement(ownership, 'primaryOwnerId').text = data.get('owner')
  77. coownersIds = XML.SubElement(ownership, 'coownersIds')
  78. for coowner in data.get('co-owners', []):
  79. XML.SubElement(coownersIds, 'string').text = coowner
  80. def promoted_build(registry, xml_parent, data):
  81. """yaml: promoted-build
  82. Marks a build for promotion. A promotion process with an identical
  83. name must be created via the web interface in the job in order for the job
  84. promotion to persist. Promotion processes themselves cannot be configured
  85. by jenkins-jobs due to the separate storage of plugin configuration files.
  86. Requires the Jenkins :jenkins-wiki:`Promoted Builds Plugin
  87. <Promoted+Builds+Plugin>`.
  88. :arg list names: the promoted build names (optional)
  89. Example:
  90. .. literalinclude:: /../../tests/properties/fixtures/promoted_build.yaml
  91. :language: yaml
  92. """
  93. promoted = XML.SubElement(xml_parent, 'hudson.plugins.promoted__builds.'
  94. 'JobPropertyImpl')
  95. names = data.get('names', [])
  96. if names:
  97. active_processes = XML.SubElement(promoted, 'activeProcessNames')
  98. for n in names:
  99. XML.SubElement(active_processes, 'string').text = str(n)
  100. def gitbucket(parser, xml_parent, data):
  101. """yaml: gitbucket
  102. Integrate GitBucket to Jenkins.
  103. Requires the Jenkins :jenkins-wiki:`GitBucket Plugin <GitBucket+Plugin>`.
  104. :arg str url: GitBucket URL to issue (required)
  105. :arg bool link-enabled: Enable hyperlink to issue (default false)
  106. Minimal Example:
  107. .. literalinclude:: /../../tests/properties/fixtures/gitbucket-minimal.yaml
  108. :language: yaml
  109. Full Example:
  110. .. literalinclude:: /../../tests/properties/fixtures/gitbucket-full.yaml
  111. :language: yaml
  112. """
  113. gitbucket = XML.SubElement(
  114. xml_parent, 'org.jenkinsci.plugins.gitbucket.GitBucketProjectProperty')
  115. gitbucket.set('plugin', 'gitbucket')
  116. mapping = [
  117. ('url', 'url', None),
  118. ('link-enabled', 'linkEnabled', False),
  119. ]
  120. helpers.convert_mapping_to_xml(
  121. gitbucket, data, mapping, fail_required=True)
  122. def github(registry, xml_parent, data):
  123. """yaml: github
  124. Sets the GitHub URL for the project.
  125. :arg str url: the GitHub URL (required)
  126. :arg str display-name: This value will be used as context name for commit
  127. status if status builder or status publisher is defined for this
  128. project. (>= 1.14.1) (default '')
  129. Minimal Example:
  130. .. literalinclude:: /../../tests/properties/fixtures/github-minimal.yaml
  131. :language: yaml
  132. Full Example:
  133. .. literalinclude:: /../../tests/properties/fixtures/github-full.yaml
  134. :language: yaml
  135. """
  136. github = XML.SubElement(
  137. xml_parent, 'com.coravy.hudson.plugins.github.GithubProjectProperty')
  138. github.set('plugin', 'github')
  139. mapping = [
  140. ('url', 'projectUrl', None),
  141. ('display-name', 'displayName', ''),
  142. ]
  143. helpers.convert_mapping_to_xml(github, data, mapping, fail_required=True)
  144. def gitlab(registry, xml_parent, data):
  145. """yaml: gitlab
  146. Sets the GitLab connection for the project. Configured via Jenkins Global
  147. Configuration.
  148. Requires the Jenkins :jenkins-wiki:`GitLab Plugin <GitLab+Plugin>`.
  149. :arg str connection: the GitLab connection name (required)
  150. Example:
  151. .. literalinclude:: /../../tests/properties/fixtures/gitlab.yaml
  152. :language: yaml
  153. """
  154. gitlab = XML.SubElement(xml_parent,
  155. 'com.dabsquared.gitlabjenkins.connection.'
  156. 'GitLabConnectionProperty')
  157. mapping = [
  158. ('connection', 'gitLabConnection', None),
  159. ]
  160. helpers.convert_mapping_to_xml(gitlab, data, mapping, fail_required=True)
  161. def least_load(registry, xml_parent, data):
  162. """yaml: least-load
  163. Enables the Least Load Plugin.
  164. Requires the Jenkins :jenkins-wiki:`Least Load Plugin <Least+Load+Plugin>`.
  165. :arg bool disabled: whether or not leastload is disabled (default true)
  166. Example:
  167. .. literalinclude:: /../../tests/properties/fixtures/least-load002.yaml
  168. :language: yaml
  169. """
  170. least = XML.SubElement(xml_parent,
  171. 'org.bstick12.jenkinsci.plugins.leastload.'
  172. 'LeastLoadDisabledProperty')
  173. mapping = [
  174. ('disabled', 'leastLoadDisabled', True),
  175. ]
  176. helpers.convert_mapping_to_xml(least, data, mapping, fail_required=True)
  177. def throttle(registry, xml_parent, data):
  178. """yaml: throttle
  179. Throttles the number of builds for this job.
  180. Requires the Jenkins :jenkins-wiki:`Throttle Concurrent Builds Plugin
  181. <Throttle+Concurrent+Builds+Plugin>`.
  182. :arg str option: throttle `project` (throttle the project alone)
  183. or `category` (throttle the project as part of one or more categories)
  184. :arg int max-per-node: max concurrent builds per node (default 0)
  185. :arg int max-total: max concurrent builds (default 0)
  186. :arg bool enabled: whether throttling is enabled (default true)
  187. :arg list categories: multiproject throttle categories
  188. :arg bool matrix-builds: throttle matrix master builds (default true)
  189. :arg bool matrix-configs: throttle matrix config builds (default false)
  190. :arg str parameters-limit: prevent jobs with matching parameters from
  191. running concurrently (default false)
  192. :arg list parameters-check-list: Comma-separated list of parameters
  193. to use when comparing jobs (optional)
  194. Example:
  195. .. literalinclude:: /../../tests/properties/fixtures/throttle001.yaml
  196. :language: yaml
  197. """
  198. throttle = XML.SubElement(xml_parent,
  199. 'hudson.plugins.throttleconcurrents.'
  200. 'ThrottleJobProperty')
  201. mapping = [
  202. ('max-per-node', 'maxConcurrentPerNode', '0'),
  203. ('max-total', 'maxConcurrentTotal', '0'),
  204. ('enabled', 'throttleEnabled', True),
  205. ]
  206. helpers.convert_mapping_to_xml(throttle, data, mapping, fail_required=True)
  207. cat = data.get('categories', [])
  208. if cat:
  209. cn = XML.SubElement(throttle, 'categories')
  210. for c in cat:
  211. XML.SubElement(cn, 'string').text = str(c)
  212. options_list = ('category', 'project')
  213. option = data.get('option')
  214. if option not in options_list:
  215. raise InvalidAttributeError('option', option, options_list)
  216. mapping = [
  217. ('', 'throttleOption', option),
  218. ('', 'configVersion', '1'),
  219. ('parameters-limit', 'limitOneJobWithMatchingParams', False),
  220. ]
  221. helpers.convert_mapping_to_xml(throttle, data, mapping, fail_required=True)
  222. matrixopt = XML.SubElement(throttle, 'matrixOptions')
  223. mapping = [
  224. ('matrix-builds', 'throttleMatrixBuilds', True),
  225. ('matrix-configs', 'throttleMatrixConfigurations', False),
  226. ]
  227. helpers.convert_mapping_to_xml(
  228. matrixopt, data, mapping, fail_required=True)
  229. params_to_use = data.get('parameters-check-list', [])
  230. XML.SubElement(throttle, 'paramsToUseForLimit').text = ",".join(
  231. params_to_use)
  232. def branch_api(registry, xml_parent, data):
  233. """yaml: branch-api
  234. Enforces a minimum time between builds based on the desired maximum rate.
  235. Requires the Jenkins :jenkins-wiki:`Branch API Plugin
  236. <Branch+API+Plugin>`.
  237. :arg int number-of-builds: The maximum number of builds allowed within
  238. the specified time period. (default 1)
  239. :arg str time-period: The time period within which the maximum number
  240. of builds will be enforced. (default 'Hour')
  241. :valid values: **Hour**, **Day**, **Week**, **Month**, **Year**
  242. Minimal Example:
  243. .. literalinclude::
  244. /../../tests/properties/fixtures/branch-api-minimal.yaml
  245. :language: yaml
  246. Full example:
  247. .. literalinclude::
  248. /../../tests/properties/fixtures/branch-api-full.yaml
  249. :language: yaml
  250. """
  251. branch = XML.SubElement(xml_parent, 'jenkins.branch.'
  252. 'RateLimitBranchProperty_-JobPropertyImpl')
  253. branch.set('plugin', 'branch-api')
  254. valid_time_periods = ['Hour', 'Day', 'Week', 'Month', 'Year']
  255. mapping = [
  256. ('time-period', 'durationName', 'Hour', valid_time_periods),
  257. ('number-of-builds', 'count', 1),
  258. ]
  259. helpers.convert_mapping_to_xml(branch, data, mapping, fail_required=True)
  260. def sidebar(registry, xml_parent, data):
  261. """yaml: sidebar
  262. Allows you to add links in the sidebar.
  263. Requires the Jenkins :jenkins-wiki:`Sidebar-Link Plugin
  264. <Sidebar-Link+Plugin>`.
  265. :arg str url: url to link to (optional)
  266. :arg str text: text for the link (optional)
  267. :arg str icon: path to icon (optional)
  268. Example:
  269. .. literalinclude:: /../../tests/properties/fixtures/sidebar02.yaml
  270. :language: yaml
  271. """
  272. sidebar = xml_parent.find('hudson.plugins.sidebar__link.ProjectLinks')
  273. if sidebar is None:
  274. sidebar = XML.SubElement(xml_parent,
  275. 'hudson.plugins.sidebar__link.ProjectLinks')
  276. links = XML.SubElement(sidebar, 'links')
  277. else:
  278. links = sidebar.find('links')
  279. action = XML.SubElement(links, 'hudson.plugins.sidebar__link.LinkAction')
  280. mapping = [
  281. ('url', 'url', ''),
  282. ('text', 'text', ''),
  283. ('icon', 'icon', ''),
  284. ]
  285. helpers.convert_mapping_to_xml(action, data, mapping, fail_required=True)
  286. def inject(registry, xml_parent, data):
  287. """yaml: inject
  288. Allows you to inject environment variables into the build.
  289. Requires the Jenkins :jenkins-wiki:`Env Inject Plugin <EnvInject+Plugin>`.
  290. :arg str properties-file: file to read with properties (optional)
  291. :arg str properties-content: key=value properties (optional)
  292. :arg str script-file: file with script to run (optional)
  293. :arg str script-content: script to run (optional)
  294. :arg str groovy-content: groovy script to run (optional)
  295. :arg bool load-from-master: load files from master (default false)
  296. :arg bool enabled: injection enabled (default true)
  297. :arg bool keep-system-variables: keep system variables (default true)
  298. :arg bool keep-build-variables: keep build variable (default true)
  299. :arg bool override-build-parameters: override build parameters
  300. (default false)
  301. Example:
  302. .. literalinclude:: /../../tests/properties/fixtures/inject001.yaml
  303. :language: yaml
  304. """
  305. inject = XML.SubElement(xml_parent,
  306. 'EnvInjectJobProperty')
  307. info = XML.SubElement(inject, 'info')
  308. mapping = [
  309. ('properties-file', 'propertiesFilePath', None),
  310. ('properties-content', 'propertiesContent', None),
  311. ('script-file', 'scriptFilePath', None),
  312. ('script-content', 'scriptContent', None),
  313. ('groovy-content', 'groovyScriptContent', None),
  314. ('load-from-master', 'loadFilesFromMaster', False),
  315. ]
  316. helpers.convert_mapping_to_xml(info, data, mapping, fail_required=False)
  317. mapping = [
  318. ('enabled', 'on', True),
  319. ('keep-system-variables', 'keepJenkinsSystemVariables', True),
  320. ('keep-build-variables', 'keepBuildVariables', True),
  321. ('override-build-parameters', 'overrideBuildParameters', False),
  322. ]
  323. helpers.convert_mapping_to_xml(inject, data, mapping, fail_required=True)
  324. def authenticated_build(registry, xml_parent, data):
  325. """yaml: authenticated-build
  326. Specifies an authorization matrix where only authenticated users
  327. may trigger a build.
  328. .. deprecated:: 0.1.0. Please use :ref:`authorization <authorization>`.
  329. Example:
  330. .. literalinclude::
  331. /../../tests/properties/fixtures/authenticated_build.yaml
  332. :language: yaml
  333. """
  334. # TODO: generalize this
  335. security = XML.SubElement(xml_parent,
  336. 'hudson.security.'
  337. 'AuthorizationMatrixProperty')
  338. XML.SubElement(security, 'permission').text = (
  339. 'hudson.model.Item.Build:authenticated')
  340. def authorization(registry, xml_parent, data):
  341. """yaml: authorization
  342. Specifies an authorization matrix
  343. .. _authorization:
  344. :arg list <name>: `<name>` is the name of the group or user, containing
  345. the list of rights to grant.
  346. :<name> rights:
  347. * **credentials-create**
  348. * **credentials-delete**
  349. * **credentials-manage-domains**
  350. * **credentials-update**
  351. * **credentials-view**
  352. * **job-build**
  353. * **job-cancel**
  354. * **job-configure**
  355. * **job-delete**
  356. * **job-discover**
  357. * **job-extended-read**
  358. * **job-move**
  359. * **job-read**
  360. * **job-status**
  361. * **job-workspace**
  362. * **ownership-jobs**
  363. * **run-delete**
  364. * **run-replay**
  365. * **run-update**
  366. * **scm-tag**
  367. Example:
  368. .. literalinclude:: /../../tests/properties/fixtures/authorization.yaml
  369. :language: yaml
  370. """
  371. credentials = 'com.cloudbees.plugins.credentials.CredentialsProvider.'
  372. ownership = 'com.synopsys.arc.jenkins.plugins.ownership.OwnershipPlugin.'
  373. mapping = {
  374. 'credentials-create': ''.join((credentials, 'Create')),
  375. 'credentials-delete': ''.join((credentials, 'Delete')),
  376. 'credentials-manage-domains': ''.join((credentials, 'ManageDomains')),
  377. 'credentials-update': ''.join((credentials, 'Update')),
  378. 'credentials-view': ''.join((credentials, 'View')),
  379. 'job-build': 'hudson.model.Item.Build',
  380. 'job-cancel': 'hudson.model.Item.Cancel',
  381. 'job-configure': 'hudson.model.Item.Configure',
  382. 'job-delete': 'hudson.model.Item.Delete',
  383. 'job-discover': 'hudson.model.Item.Discover',
  384. 'job-extended-read': 'hudson.model.Item.ExtendedRead',
  385. 'job-move': 'hudson.model.Item.Move',
  386. 'job-read': 'hudson.model.Item.Read',
  387. 'job-status': 'hudson.model.Item.ViewStatus',
  388. 'job-workspace': 'hudson.model.Item.Workspace',
  389. 'ownership-jobs': ''.join((ownership, 'Jobs')),
  390. 'run-delete': 'hudson.model.Run.Delete',
  391. 'run-replay': 'hudson.model.Run.Replay',
  392. 'run-update': 'hudson.model.Run.Update',
  393. 'scm-tag': 'hudson.scm.SCM.Tag',
  394. }
  395. if data:
  396. matrix = XML.SubElement(xml_parent,
  397. 'hudson.security.AuthorizationMatrixProperty')
  398. for (username, perms) in data.items():
  399. for perm in perms:
  400. pe = XML.SubElement(matrix, 'permission')
  401. try:
  402. pe.text = "{0}:{1}".format(mapping[perm], username)
  403. except KeyError:
  404. raise InvalidAttributeError(username, perm, mapping.keys())
  405. def priority_sorter(registry, xml_parent, data):
  406. """yaml: priority-sorter
  407. Allows simple ordering of builds, using a configurable job priority.
  408. Requires the Jenkins :jenkins-wiki:`Priority Sorter Plugin
  409. <Priority+Sorter+Plugin>`.
  410. :arg int priority: Priority of the job. Higher value means higher
  411. priority, with 3 as the default priority. (required)
  412. Example:
  413. .. literalinclude::
  414. /../../tests/properties/fixtures/priority_sorter002.yaml
  415. :language: yaml
  416. """
  417. plugin_info = registry.get_plugin_info('PrioritySorter')
  418. version = pkg_resources.parse_version(plugin_info.get('version', '0'))
  419. if version >= pkg_resources.parse_version("2.0"):
  420. priority_sorter_tag = XML.SubElement(xml_parent,
  421. 'jenkins.advancedqueue.priority.'
  422. 'strategy.PriorityJobProperty')
  423. mapping = [
  424. ('use', 'useJobPriority', True),
  425. ('priority', 'priority', None)
  426. ]
  427. else:
  428. priority_sorter_tag = XML.SubElement(xml_parent,
  429. 'hudson.queueSorter.'
  430. 'PrioritySorterJobProperty')
  431. mapping = [
  432. ('priority', 'priority', None),
  433. ]
  434. helpers.convert_mapping_to_xml(
  435. priority_sorter_tag, data, mapping, fail_required=True)
  436. def build_blocker(registry, xml_parent, data):
  437. """yaml: build-blocker
  438. This plugin keeps the actual job in the queue
  439. if at least one name of currently running jobs
  440. is matching with one of the given regular expressions.
  441. Requires the Jenkins :jenkins-wiki:`Build Blocker Plugin
  442. <Build+Blocker+Plugin>`.
  443. :arg bool use-build-blocker: Enable or disable build blocker (default true)
  444. :arg list blocking-jobs: One regular expression per line to select
  445. blocking jobs by their names. (required)
  446. :arg str block-level: block build globally ('GLOBAL') or per node ('NODE')
  447. (default 'GLOBAL')
  448. :arg str queue-scanning: scan build queue for all builds ('ALL') or only
  449. buildable builds ('BUILDABLE') (default 'DISABLED'))
  450. Example:
  451. .. literalinclude::
  452. /../../tests/properties/fixtures/build-blocker01.yaml
  453. :language: yaml
  454. """
  455. blocker = XML.SubElement(xml_parent,
  456. 'hudson.plugins.'
  457. 'buildblocker.BuildBlockerProperty')
  458. if data is None or 'blocking-jobs' not in data:
  459. raise JenkinsJobsException('blocking-jobs field is missing')
  460. elif data.get('blocking-jobs', None) is None:
  461. raise JenkinsJobsException('blocking-jobs list must not be empty')
  462. jobs = ''
  463. for value in data['blocking-jobs']:
  464. jobs = jobs + value + '\n'
  465. mapping = [
  466. ('use-build-blocker', 'useBuildBlocker', True),
  467. ('', 'blockingJobs', jobs),
  468. ('blocking-level', 'blockLevel', 'GLOBAL', ('GLOBAL', 'NODE')),
  469. ('queue-scanning', 'scanQueueFor', 'DISABLED',
  470. ('DISABLED', 'ALL', 'BUILDABLE')),
  471. ]
  472. helpers.convert_mapping_to_xml(blocker, data, mapping, fail_required=True)
  473. def copyartifact(registry, xml_parent, data):
  474. """yaml: copyartifact
  475. Specify a list of projects that have access to copy the artifacts of
  476. this project.
  477. Requires the Jenkins :jenkins-wiki:`Copy Artifact plugin
  478. <Copy+Artifact+Plugin>`.
  479. :arg str projects: comma separated list of projects that can copy
  480. artifacts of this project. Wild card character '*' is available.
  481. Example:
  482. .. literalinclude::
  483. /../../tests/properties/fixtures/copyartifact.yaml
  484. :language: yaml
  485. """
  486. copyartifact = XML.SubElement(xml_parent,
  487. 'hudson.plugins.'
  488. 'copyartifact.'
  489. 'CopyArtifactPermissionProperty',
  490. plugin='copyartifact')
  491. if not data or not data.get('projects', None):
  492. raise JenkinsJobsException("projects string must exist and "
  493. "not be empty")
  494. projectlist = XML.SubElement(copyartifact, 'projectNameList')
  495. for project in str(data.get('projects')).split(','):
  496. XML.SubElement(projectlist, 'string').text = project
  497. def batch_tasks(registry, xml_parent, data):
  498. """yaml: batch-tasks
  499. Batch tasks can be tasks for events like releases, integration, archiving,
  500. etc. In this way, anyone in the project team can execute them in a way that
  501. leaves a record.
  502. A batch task consists of a shell script and a name. When you execute
  503. a build, the shell script gets run on the workspace, just like a build.
  504. Batch tasks and builds "lock" the workspace, so when one of those
  505. activities is in progress, all the others will block in the queue.
  506. Requires the Jenkins :jenkins-wiki:`Batch Task Plugin <Batch+Task+Plugin>`.
  507. :arg list batch-tasks: Batch tasks.
  508. :Tasks:
  509. * **name** (`str`) Task name.
  510. * **script** (`str`) Task script.
  511. Example:
  512. .. literalinclude:: /../../tests/properties/fixtures/batch-task.yaml
  513. :language: yaml
  514. """
  515. pdef = XML.SubElement(xml_parent,
  516. 'hudson.plugins.batch__task.BatchTaskProperty')
  517. tasks = XML.SubElement(pdef, 'tasks')
  518. for task in data:
  519. batch_task = XML.SubElement(tasks,
  520. 'hudson.plugins.batch__task.BatchTask')
  521. mapping = [
  522. ('name', 'name', None),
  523. ('script', 'script', None),
  524. ]
  525. helpers.convert_mapping_to_xml(
  526. batch_task, task, mapping, fail_required=True)
  527. def heavy_job(registry, xml_parent, data):
  528. """yaml: heavy-job
  529. This plugin allows you to define "weight" on each job,
  530. and making each job consume that many executors
  531. Requires the Jenkins :jenkins-wiki:`Heavy Job Plugin <Heavy+Job+Plugin>`.
  532. :arg int weight: Specify the total number of executors
  533. that this job should occupy (default 1)
  534. Example:
  535. .. literalinclude:: /../../tests/properties/fixtures/heavy-job.yaml
  536. :language: yaml
  537. """
  538. heavyjob = XML.SubElement(xml_parent,
  539. 'hudson.plugins.'
  540. 'heavy__job.HeavyJobProperty')
  541. mapping = [
  542. ('weight', 'weight', 1),
  543. ]
  544. helpers.convert_mapping_to_xml(heavyjob, data, mapping, fail_required=True)
  545. def slave_utilization(registry, xml_parent, data):
  546. """yaml: slave-utilization
  547. This plugin allows you to specify the percentage of a slave's capacity a
  548. job wants to use.
  549. Requires the Jenkins :jenkins-wiki:`Slave Utilization Plugin
  550. <Slave+Utilization+Plugin>`.
  551. :arg int slave-percentage: Specify the percentage of a slave's execution
  552. slots that this job should occupy (default 0)
  553. :arg bool single-instance-per-slave: Control whether concurrent instances
  554. of this job will be permitted to run in parallel on a single slave
  555. (default false)
  556. Example:
  557. .. literalinclude::
  558. /../../tests/properties/fixtures/slave-utilization1.yaml
  559. :language: yaml
  560. """
  561. utilization = XML.SubElement(
  562. xml_parent, 'com.suryagaddipati.jenkins.SlaveUtilizationProperty')
  563. percent = int(data.get('slave-percentage', 0))
  564. exclusive_node_access = True if percent else False
  565. mapping = [
  566. ('', 'needsExclusiveAccessToNode', exclusive_node_access),
  567. ('', 'slaveUtilizationPercentage', percent),
  568. ('single-instance-per-slave', 'singleInstancePerSlave', False),
  569. ]
  570. helpers.convert_mapping_to_xml(
  571. utilization, data, mapping, fail_required=True)
  572. def delivery_pipeline(registry, xml_parent, data):
  573. """yaml: delivery-pipeline
  574. Requires the Jenkins :jenkins-wiki:`Delivery Pipeline Plugin
  575. <Delivery+Pipeline+Plugin>`.
  576. :arg str stage: Name of the stage for this job (default '')
  577. :arg str task: Name of the task for this job (default '')
  578. :arg str description: task description template for this job
  579. (default '')
  580. Minimal Example:
  581. .. literalinclude::
  582. /../../tests/properties/fixtures/delivery-pipeline-minimal.yaml
  583. :language: yaml
  584. Full Example:
  585. .. literalinclude::
  586. /../../tests/properties/fixtures/delivery-pipeline-full.yaml
  587. :language: yaml
  588. """
  589. pipeline = XML.SubElement(
  590. xml_parent, 'se.diabol.jenkins.pipeline.PipelineProperty')
  591. pipeline.set('plugin', 'delivery-pipeline-plugin')
  592. mapping = [
  593. ('stage', 'stageName', ''),
  594. ('task', 'taskName', ''),
  595. ('description', 'descriptionTemplate', ''),
  596. ]
  597. helpers.convert_mapping_to_xml(pipeline, data, mapping, fail_required=True)
  598. def zeromq_event(registry, xml_parent, data):
  599. """yaml: zeromq-event
  600. This is a Jenkins plugin that will publish Jenkins Job run events
  601. (start, complete, finish) to a ZMQ PUB socket.
  602. Requires the Jenkins `ZMQ Event Publisher.
  603. <https://git.openstack.org/cgit/openstack-infra/zmq-event-publisher>`_
  604. Example:
  605. .. literalinclude::
  606. /../../tests/properties/fixtures/zeromq-event.yaml
  607. :language: yaml
  608. """
  609. zmq_event = XML.SubElement(xml_parent,
  610. 'org.jenkinsci.plugins.'
  611. 'ZMQEventPublisher.HudsonNotificationProperty')
  612. mapping = [
  613. ('', 'enabled', True),
  614. ]
  615. helpers.convert_mapping_to_xml(
  616. zmq_event, data, mapping, fail_required=True)
  617. def slack(registry, xml_parent, data):
  618. """yaml: slack
  619. Requires the Jenkins :jenkins-wiki:`Slack Plugin <Slack+Plugin>`
  620. When using Slack Plugin version < 2.0, Slack Plugin itself requires a
  621. publisher aswell as properties please note that you have to add the
  622. publisher to your job configuration aswell. When using Slack Plugin
  623. version >= 2.0, you should only configure the publisher.
  624. :arg bool notify-start: Send notification when the job starts
  625. (default false)
  626. :arg bool notify-success: Send notification on success. (default false)
  627. :arg bool notify-aborted: Send notification when job is aborted. (
  628. default false)
  629. :arg bool notify-not-built: Send notification when job set to NOT_BUILT
  630. status. (default false)
  631. :arg bool notify-unstable: Send notification when job becomes unstable.
  632. (default false)
  633. :arg bool notify-failure: Send notification when job fails.
  634. (default false)
  635. :arg bool notify-back-to-normal: Send notification when job is
  636. succeeding again after being unstable or failed. (default false)
  637. :arg bool 'notify-repeated-failure': Send notification when job is
  638. still failing after last failure. (default false)
  639. :arg bool include-test-summary: Include the test summary. (default
  640. False)
  641. :arg bool include-custom-message: Include a custom message into the
  642. notification. (default false)
  643. :arg str custom-message: Custom message to be included. (default '')
  644. :arg str room: A comma separated list of rooms / channels to send
  645. the notifications to. (default '')
  646. Example:
  647. .. literalinclude::
  648. /../../tests/properties/fixtures/slack001.yaml
  649. :language: yaml
  650. """
  651. logger = logging.getLogger(__name__)
  652. plugin_info = registry.get_plugin_info('Slack Notification Plugin')
  653. plugin_ver = pkg_resources.parse_version(plugin_info.get('version', "0"))
  654. if plugin_ver >= pkg_resources.parse_version("2.0"):
  655. logger.warning(
  656. "properties section is not used with plugin version >= 2.0",
  657. )
  658. mapping = (
  659. ('notify-start', 'startNotification', False),
  660. ('notify-success', 'notifySuccess', False),
  661. ('notify-aborted', 'notifyAborted', False),
  662. ('notify-not-built', 'notifyNotBuilt', False),
  663. ('notify-unstable', 'notifyUnstable', False),
  664. ('notify-failure', 'notifyFailure', False),
  665. ('notify-back-to-normal', 'notifyBackToNormal', False),
  666. ('notify-repeated-failure', 'notifyRepeatedFailure', False),
  667. ('include-test-summary', 'includeTestSummary', False),
  668. ('include-custom-message', 'includeCustomMessage', False),
  669. ('custom-message', 'customMessage', ''),
  670. ('room', 'room', ''),
  671. )
  672. slack = XML.SubElement(
  673. xml_parent,
  674. 'jenkins.plugins.slack.SlackNotifier_-SlackJobProperty',
  675. )
  676. # Ensure that custom-message is set when include-custom-message is set
  677. # to true.
  678. if data.get('include-custom-message', False):
  679. if not data.get('custom-message', ''):
  680. raise MissingAttributeError('custom-message')
  681. helpers.convert_mapping_to_xml(slack, data, mapping, fail_required=True)
  682. def rebuild(registry, xml_parent, data):
  683. """yaml: rebuild
  684. This plug-in allows the user to rebuild a parameterized build without
  685. entering the parameters again.It will also allow the user to edit the
  686. parameters before rebuilding.
  687. Requires the Jenkins :jenkins-wiki:`Rebuild Plugin <Rebuild+Plugin>`.
  688. :arg bool auto-rebuild: Rebuild without asking for parameters
  689. (default false)
  690. :arg bool rebuild-disabled: Disable rebuilding for this job
  691. (default false)
  692. Minimal Example:
  693. .. literalinclude:: /../../tests/properties/fixtures/rebuild-minimal.yaml
  694. :language: yaml
  695. Full Example:
  696. .. literalinclude:: /../../tests/properties/fixtures/rebuild-full.yaml
  697. :language: yaml
  698. """
  699. sub_element = XML.SubElement(xml_parent,
  700. 'com.sonyericsson.rebuild.RebuildSettings')
  701. sub_element.set('plugin', 'rebuild')
  702. mapping = [
  703. ('auto-rebuild', 'autoRebuild', False),
  704. ('rebuild-disabled', 'rebuildDisabled', False),
  705. ]
  706. helpers.convert_mapping_to_xml(
  707. sub_element, data, mapping, fail_required=True)
  708. def build_discarder(registry, xml_parent, data):
  709. """yaml: build-discarder
  710. :arg int days-to-keep: Number of days to keep builds for (default -1)
  711. :arg int num-to-keep: Number of builds to keep (default -1)
  712. :arg int artifact-days-to-keep: Number of days to keep builds with
  713. artifacts (default -1)
  714. :arg int artifact-num-to-keep: Number of builds with artifacts to keep
  715. (default -1)
  716. Example:
  717. .. literalinclude::
  718. /../../tests/properties/fixtures/build-discarder-001.yaml
  719. :language: yaml
  720. .. literalinclude::
  721. /../../tests/properties/fixtures/build-discarder-002.yaml
  722. :language: yaml
  723. """
  724. base_sub = XML.SubElement(xml_parent,
  725. 'jenkins.model.BuildDiscarderProperty')
  726. strategy = XML.SubElement(base_sub, 'strategy')
  727. strategy.set('class', 'hudson.tasks.LogRotator')
  728. mappings = [
  729. ('days-to-keep', 'daysToKeep', -1),
  730. ('num-to-keep', 'numToKeep', -1),
  731. ('artifact-days-to-keep', 'artifactDaysToKeep', -1),
  732. ('artifact-num-to-keep', 'artifactNumToKeep', -1),
  733. ]
  734. helpers.convert_mapping_to_xml(
  735. strategy, data, mappings, fail_required=True)
  736. def slave_prerequisites(registry, xml_parent, data):
  737. """yaml: slave-prerequisites
  738. This plugin allows you to check prerequisites on slave before
  739. a job can run a build on it
  740. Requires the Jenkins :jenkins-wiki:`Slave Prerequisites Plugin
  741. <Slave+Prerequisites+Plugin>`.
  742. :arg str script: A script to be executed on slave node.
  743. If returning non 0 status, the node will be vetoed from hosting
  744. the build. (required)
  745. :arg str interpreter: Command line interpreter to be used for executing
  746. the prerequisite script - either `shell` for Unix shell or `cmd` for
  747. Windows batch script. (default shell)
  748. Example:
  749. .. literalinclude::
  750. /../../tests/properties/fixtures/slave-prerequisites-minimal.yaml
  751. :language: yaml
  752. .. literalinclude::
  753. /../../tests/properties/fixtures/slave-prerequisites-full.yaml
  754. :language: yaml
  755. """
  756. prereqs = XML.SubElement(xml_parent,
  757. 'com.cloudbees.plugins.JobPrerequisites')
  758. mappings = [
  759. ('script', 'script', None),
  760. ('interpreter', 'interpreter', 'shell', {
  761. 'cmd': 'windows batch command',
  762. 'shell': 'shell script'}),
  763. ]
  764. helpers.convert_mapping_to_xml(prereqs, data, mappings, fail_required=True)
  765. def groovy_label(registry, xml_parent, data):
  766. """yaml: groovy-label
  767. This plugin allows you to use Groovy script to restrict where this project
  768. can be run.
  769. Requires the Jenkins :jenkins-wiki:`Groovy Label Assignment Plugin
  770. <Groovy+Label+Assignment+plugin>`.
  771. Return value from Groovy script is treated as Label Expression.
  772. It is treated as followings:
  773. - A non-string value will be converted to a string using toString()
  774. - When null or blank string is returned, node restriction does not take
  775. effect (or is not overwritten).
  776. - When exception occurred or Label Expression is not parsed correctly,
  777. builds are canceled.
  778. :arg str script: Groovy script (default '')
  779. :arg bool sandbox: Use Groovy Sandbox. (default false)
  780. If checked, run this Groovy script in a sandbox with limited abilities.
  781. If unchecked, and you are not a Jenkins administrator, you will need to
  782. wait for an administrator to approve the script
  783. :arg list classpath: Additional classpath entries accessible from
  784. the script, each of which should be an absolute local path or
  785. URL to a JAR file, according to "The file URI Scheme" (optional)
  786. Minimal Example:
  787. .. literalinclude::
  788. /../../tests/properties/fixtures/groovy-label-minimal.yaml
  789. :language: yaml
  790. Full Example:
  791. .. literalinclude::
  792. /../../tests/properties/fixtures/groovy-label-full.yaml
  793. :language: yaml
  794. """
  795. sub_element = XML.SubElement(xml_parent,
  796. 'jp.ikedam.jenkins.plugins.'
  797. 'groovy__label__assignment.'
  798. 'GroovyLabelAssignmentProperty')
  799. sub_element.set('plugin', 'groovy-label-assignment')
  800. security = XML.SubElement(sub_element, 'secureGroovyScript')
  801. security.set('plugin', 'script-security')
  802. mapping = [
  803. ('script', 'script', ''),
  804. ('sandbox', 'sandbox', False),
  805. ]
  806. helpers.convert_mapping_to_xml(security, data, mapping, fail_required=True)
  807. if data and 'classpath' in data:
  808. classpath = XML.SubElement(security, 'classpath')
  809. for value in data['classpath']:
  810. entry = XML.SubElement(classpath, 'entry')
  811. XML.SubElement(entry, 'url').text = value
  812. def lockable_resources(registry, xml_parent, data):
  813. """yaml: lockable-resources
  814. Requires the Jenkins :jenkins-wiki:`Lockable Resources Plugin
  815. <Lockable+Resources+Plugin>`.
  816. :arg str resources: List of required resources, space separated.
  817. (required, mutual exclusive with label)
  818. :arg str label: If you have created a pool of resources, i.e. a label,
  819. you can take it into use here. The build will select the resource(s)
  820. from the pool that includes all resources sharing the given label.
  821. (required, mutual exclusive with resources)
  822. :arg str var-name: Name for the Jenkins variable to store the reserved
  823. resources in. Leave empty to disable. (default '')
  824. :arg int number: Number of resources to request, empty value or 0 means
  825. all. This is useful, if you have a pool of similar resources,
  826. from which you want one or more to be reserved. (default 0)
  827. Example:
  828. .. literalinclude::
  829. /../../tests/properties/fixtures/lockable_resources_minimal.yaml
  830. :language: yaml
  831. .. literalinclude::
  832. /../../tests/properties/fixtures/lockable_resources_label.yaml
  833. :language: yaml
  834. .. literalinclude::
  835. /../../tests/properties/fixtures/lockable_resources_full.yaml
  836. :language: yaml
  837. """
  838. lockable_resources = XML.SubElement(
  839. xml_parent,
  840. 'org.jenkins.plugins.lockableresources.RequiredResourcesProperty')
  841. if data.get('resources') and data.get('label'):
  842. raise AttributeConflictError('resources', ('label',))
  843. mapping = [
  844. ('resources', 'resourceNames', ''),
  845. ('var-name', 'resourceNamesVar', ''),
  846. ('number', 'resourceNumber', 0),
  847. ('label', 'labelName', ''),
  848. ]
  849. helpers.convert_mapping_to_xml(
  850. lockable_resources, data, mapping, fail_required=True)
  851. def docker_container(registry, xml_parent, data):
  852. """yaml: docker-container
  853. Requires the Jenkins: :jenkins-wiki:`Docker Plugin<Docker+Plugin>`.
  854. :arg bool commit-on-success: When a job completes, the docker slave
  855. instance is committed with repository based on the job name and build
  856. number as tag. (default false)
  857. :arg str additional-tag: Additional tag to apply to the docker slave
  858. instance when committing it. (default '')
  859. :arg bool push-on-success: Also push the resulting image when committing
  860. the docker slave instance. (default false)
  861. :arg bool clean-local-images: Clean images from the local daemon after
  862. building. (default true)
  863. Minimal Example:
  864. .. literalinclude::
  865. /../../tests/properties/fixtures/docker-container-minimal.yaml
  866. :language: yaml
  867. Full Example:
  868. .. literalinclude::
  869. /../../tests/properties/fixtures/docker-container-full.yaml
  870. :language: yaml
  871. """
  872. xml_docker = XML.SubElement(
  873. xml_parent, 'com.nirima.jenkins.plugins.docker.DockerJobProperty')
  874. mapping = [
  875. ('commit-on-success', 'tagOnCompletion', False),
  876. ('additional-tag', 'additionalTag', ''),
  877. ('push-on-success', 'pushOnSuccess', False),
  878. ('clean-local-images', 'cleanImages', True),
  879. ]
  880. helpers.convert_mapping_to_xml(
  881. xml_docker, data, mapping, fail_required=True)
  882. class Properties(jenkins_jobs.modules.base.Base):
  883. sequence = 20
  884. component_type = 'property'
  885. component_list_type = 'properties'
  886. def gen_xml(self, xml_parent, data):
  887. properties = xml_parent.find('properties')
  888. if properties is None:
  889. properties = XML.SubElement(xml_parent, 'properties')
  890. for prop in data.get('properties', []):
  891. self.registry.dispatch('property', properties, prop)