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

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