monitorForm.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import {Component, Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import {Observer} from 'mobx-react';
  4. import FieldGroup from 'sentry/components/forms/fieldGroup';
  5. import NumberField from 'sentry/components/forms/fields/numberField';
  6. import SelectField from 'sentry/components/forms/fields/selectField';
  7. import SentryProjectSelectorField from 'sentry/components/forms/fields/sentryProjectSelectorField';
  8. import TextField from 'sentry/components/forms/fields/textField';
  9. import Form, {FormProps} from 'sentry/components/forms/form';
  10. import FormModel from 'sentry/components/forms/model';
  11. import ExternalLink from 'sentry/components/links/externalLink';
  12. import {Panel, PanelAlert, PanelBody, PanelHeader} from 'sentry/components/panels';
  13. import TextCopyInput from 'sentry/components/textCopyInput';
  14. import TimeSince from 'sentry/components/timeSince';
  15. import {timezoneOptions} from 'sentry/data/timezones';
  16. import {t, tct, tn} from 'sentry/locale';
  17. import {PageFilters, Project, SelectValue} from 'sentry/types';
  18. import commonTheme from 'sentry/utils/theme';
  19. import withPageFilters from 'sentry/utils/withPageFilters';
  20. import withProjects from 'sentry/utils/withProjects';
  21. import {IntervalConfig, Monitor, MonitorConfig, MonitorType, ScheduleType} from './types';
  22. const SCHEDULE_TYPES: SelectValue<ScheduleType>[] = [
  23. {value: ScheduleType.CRONTAB, label: 'Crontab'},
  24. {value: ScheduleType.INTERVAL, label: 'Interval'},
  25. ];
  26. const DEFAULT_MONITOR_TYPE = 'cron_job';
  27. const getIntervals = (n: number): SelectValue<string>[] => [
  28. {value: 'minute', label: tn('minute', 'minutes', n)},
  29. {value: 'hour', label: tn('hour', 'hours', n)},
  30. {value: 'day', label: tn('day', 'days', n)},
  31. {value: 'week', label: tn('week', 'weeks', n)},
  32. {value: 'month', label: tn('month', 'months', n)},
  33. {value: 'year', label: tn('year', 'years', n)},
  34. ];
  35. type Props = {
  36. apiEndpoint: string;
  37. apiMethod: FormProps['apiMethod'];
  38. onSubmitSuccess: FormProps['onSubmitSuccess'];
  39. projects: Project[];
  40. selection: PageFilters;
  41. monitor?: Monitor;
  42. submitLabel?: string;
  43. };
  44. type TransformedData = {
  45. config?: Partial<MonitorConfig>;
  46. };
  47. function transformData(_data: Record<string, any>, model: FormModel) {
  48. return model.fields.toJSON().reduce<TransformedData>((data, [k, v]) => {
  49. // We're only concerned with transforming the config
  50. if (!k.startsWith('config.')) {
  51. data[k] = v;
  52. return data;
  53. }
  54. // Default to empty object
  55. data.config ??= {};
  56. if (k === 'config.schedule.frequency' || k === 'config.schedule.interval') {
  57. if (!Array.isArray(data.config.schedule)) {
  58. data.config.schedule = [1, 'hour'];
  59. }
  60. }
  61. if (Array.isArray(data.config.schedule) && k === 'config.schedule.frequency') {
  62. data.config.schedule![0] = parseInt(v as string, 10);
  63. return data;
  64. }
  65. if (Array.isArray(data.config.schedule) && k === 'config.schedule.interval') {
  66. data.config.schedule![1] = v as IntervalConfig['schedule'][1];
  67. return data;
  68. }
  69. data.config[k.substr(7)] = v;
  70. return data;
  71. }, {});
  72. }
  73. class MonitorForm extends Component<Props> {
  74. form = new FormModel({transformData});
  75. formDataFromConfig(type: MonitorType, config: MonitorConfig) {
  76. const rv = {};
  77. switch (type) {
  78. case 'cron_job':
  79. rv['config.schedule_type'] = config.schedule_type;
  80. rv['config.checkin_margin'] = config.checkin_margin;
  81. rv['config.max_runtime'] = config.max_runtime;
  82. switch (config.schedule_type) {
  83. case 'interval':
  84. rv['config.schedule.frequency'] = config.schedule[0];
  85. rv['config.schedule.interval'] = config.schedule[1];
  86. break;
  87. case 'crontab':
  88. default:
  89. rv['config.schedule'] = config.schedule;
  90. rv['config.timezone'] = config.timezone;
  91. }
  92. break;
  93. default:
  94. }
  95. return rv;
  96. }
  97. render() {
  98. const {monitor, submitLabel} = this.props;
  99. const selectedProjectId = this.props.selection.projects[0];
  100. const selectedProject = selectedProjectId
  101. ? this.props.projects.find(p => p.id === selectedProjectId + '')
  102. : null;
  103. return (
  104. <Form
  105. allowUndo
  106. requireChanges
  107. apiEndpoint={this.props.apiEndpoint}
  108. apiMethod={this.props.apiMethod}
  109. model={this.form}
  110. initialData={
  111. monitor
  112. ? {
  113. name: monitor.name,
  114. type: monitor.type ?? DEFAULT_MONITOR_TYPE,
  115. project: monitor.project.slug,
  116. ...this.formDataFromConfig(monitor.type, monitor.config),
  117. }
  118. : {
  119. project: selectedProject ? selectedProject.slug : null,
  120. type: DEFAULT_MONITOR_TYPE,
  121. }
  122. }
  123. onSubmitSuccess={this.props.onSubmitSuccess}
  124. submitLabel={submitLabel}
  125. >
  126. <Panel>
  127. <PanelHeader>{t('Details')}</PanelHeader>
  128. <PanelBody>
  129. {monitor && (
  130. <FieldGroup label={t('ID')}>
  131. <div className="controls">
  132. <TextCopyInput>{monitor.id}</TextCopyInput>
  133. </div>
  134. </FieldGroup>
  135. )}
  136. <SentryProjectSelectorField
  137. name="project"
  138. label={t('Project')}
  139. projects={this.props.projects.filter(project => project.isMember)}
  140. disabled={!!monitor}
  141. disabledReason={t('Existing monitors cannot be moved between projects')}
  142. valueIsSlug
  143. help={t(
  144. "Select the project which contains the recurring job you'd like to monitor."
  145. )}
  146. required
  147. />
  148. <TextField
  149. name="name"
  150. placeholder={t('My Cron Job')}
  151. label={t('Name your cron monitor')}
  152. required
  153. />
  154. </PanelBody>
  155. </Panel>
  156. <Panel>
  157. <PanelHeader>{t('Config')}</PanelHeader>
  158. <PanelBody>
  159. {monitor !== undefined && monitor.nextCheckIn && (
  160. <PanelAlert type="info">
  161. {tct(
  162. 'Any changes you make to the execution schedule will only be applied after the next expected check-in [nextCheckin].',
  163. {
  164. nextCheckin: (
  165. <strong>
  166. <TimeSince date={monitor.nextCheckIn} />
  167. </strong>
  168. ),
  169. }
  170. )}
  171. </PanelAlert>
  172. )}
  173. <NumberField
  174. name="config.max_runtime"
  175. label={t('Max Runtime')}
  176. help={t(
  177. "Set the number of minutes a recurring job is allowed to run before it's considered failed"
  178. )}
  179. placeholder="e.g. 30"
  180. />
  181. <SelectField
  182. name="config.schedule_type"
  183. label={t('Schedule Type')}
  184. options={SCHEDULE_TYPES}
  185. defaultValue={ScheduleType.CRONTAB}
  186. required
  187. />
  188. <Observer>
  189. {() => {
  190. switch (this.form.getValue('config.schedule_type')) {
  191. case 'crontab':
  192. return (
  193. <Fragment>
  194. <TextField
  195. name="config.schedule"
  196. label={t('Schedule')}
  197. placeholder="*/5 * * * *"
  198. required
  199. help={tct(
  200. 'Any schedule changes will be applied to the next check-in. See [link:Wikipedia] for crontab syntax.',
  201. {
  202. link: (
  203. <ExternalLink href="https://en.wikipedia.org/wiki/Cron" />
  204. ),
  205. }
  206. )}
  207. css={{input: {fontFamily: commonTheme.text.familyMono}}}
  208. />
  209. <SelectField
  210. name="config.timezone"
  211. label={t('Timezone')}
  212. defaultValue="UTC"
  213. options={timezoneOptions}
  214. help={tct(
  215. "The timezone of your execution environment. Be sure to set this correctly, otherwise the schedule may be mismatched and check-ins will be marked as missed! Use [code:timedatectl] or similar to determine your machine's timezone.",
  216. {code: <code />}
  217. )}
  218. />
  219. <NumberField
  220. name="config.checkin_margin"
  221. label={t('Check-in Margin')}
  222. help={t(
  223. "The max error margin (in minutes) before a check-in is considered missed. If you don't expect your job to start immediately at the scheduled time, expand this margin to account for delays."
  224. )}
  225. placeholder="e.g. 30"
  226. />
  227. </Fragment>
  228. );
  229. case 'interval':
  230. return (
  231. <Fragment>
  232. <CombinedField>
  233. <FieldGroup
  234. label={t('Frequency')}
  235. help={t(
  236. 'The amount of time between each job execution. Example, every 5 hours.'
  237. )}
  238. stacked
  239. required
  240. />
  241. <StyledNumberField
  242. name="config.schedule.frequency"
  243. label={t('Frequency')}
  244. placeholder="e.g. 1"
  245. hideLabel
  246. required
  247. />
  248. <StyledSelectField
  249. name="config.schedule.interval"
  250. label={t('Interval')}
  251. options={getIntervals(
  252. Number(this.form.getValue('config.schedule.frequency') ?? 1)
  253. )}
  254. hideLabel
  255. required
  256. />
  257. </CombinedField>
  258. <NumberField
  259. name="config.checkin_margin"
  260. label={t('Check-in Margin')}
  261. help={t(
  262. "The max error margin (in minutes) before a check-in is considered missed. If you don't expect your job to start immediately at the scheduled time, expand this margin to account for delays."
  263. )}
  264. placeholder="e.g. 30"
  265. />
  266. </Fragment>
  267. );
  268. default:
  269. return null;
  270. }
  271. }}
  272. </Observer>
  273. </PanelBody>
  274. </Panel>
  275. </Form>
  276. );
  277. }
  278. }
  279. const CombinedField = styled('div')`
  280. display: grid;
  281. grid-template-columns: 50% 1fr 1fr;
  282. align-items: center;
  283. border-bottom: 1px solid ${p => p.theme.innerBorder};
  284. `;
  285. const StyledNumberField = styled(NumberField)`
  286. padding: 0;
  287. border-bottom: none;
  288. `;
  289. const StyledSelectField = styled(SelectField)`
  290. padding-left: 0;
  291. `;
  292. export default withPageFilters(withProjects(MonitorForm));