monitorForm.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. valueIsSlug
  141. help={t(
  142. "Select the project which contains the recurring job you'd like to monitor."
  143. )}
  144. required
  145. />
  146. <TextField
  147. name="name"
  148. placeholder={t('My Cron Job')}
  149. label={t('Name your cron monitor')}
  150. required
  151. />
  152. </PanelBody>
  153. </Panel>
  154. <Panel>
  155. <PanelHeader>{t('Config')}</PanelHeader>
  156. <PanelBody>
  157. {monitor !== undefined && monitor.nextCheckIn && (
  158. <PanelAlert type="info">
  159. {tct(
  160. 'Any changes you make to the execution schedule will only be applied after the next expected check-in [nextCheckin].',
  161. {
  162. nextCheckin: (
  163. <strong>
  164. <TimeSince date={monitor.nextCheckIn} />
  165. </strong>
  166. ),
  167. }
  168. )}
  169. </PanelAlert>
  170. )}
  171. <NumberField
  172. name="config.max_runtime"
  173. label={t('Max Runtime')}
  174. help={t(
  175. "Set the number of minutes a recurring job is allowed to run before it's considered failed"
  176. )}
  177. placeholder="e.g. 30"
  178. />
  179. <SelectField
  180. name="config.schedule_type"
  181. label={t('Schedule Type')}
  182. options={SCHEDULE_TYPES}
  183. required
  184. />
  185. <Observer>
  186. {() => {
  187. switch (this.form.getValue('config.schedule_type')) {
  188. case 'crontab':
  189. return (
  190. <Fragment>
  191. <TextField
  192. name="config.schedule"
  193. label={t('Schedule')}
  194. placeholder="*/5 * * * *"
  195. required
  196. help={tct(
  197. 'Any schedule changes will be applied to the next check-in. See [link:Wikipedia] for crontab syntax.',
  198. {
  199. link: (
  200. <ExternalLink href="https://en.wikipedia.org/wiki/Cron" />
  201. ),
  202. }
  203. )}
  204. css={{input: {fontFamily: commonTheme.text.familyMono}}}
  205. />
  206. <SelectField
  207. name="config.timezone"
  208. label={t('Timezone')}
  209. defaultValue="UTC"
  210. options={timezoneOptions}
  211. help={tct(
  212. "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.",
  213. {code: <code />}
  214. )}
  215. />
  216. <NumberField
  217. name="config.checkin_margin"
  218. label={t('Check-in Margin')}
  219. help={t(
  220. "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."
  221. )}
  222. placeholder="e.g. 30"
  223. />
  224. </Fragment>
  225. );
  226. case 'interval':
  227. return (
  228. <Fragment>
  229. <CombinedField>
  230. <FieldGroup
  231. label={t('Frequency')}
  232. help={t(
  233. 'The amount of time between each job execution. Example, every 5 hours.'
  234. )}
  235. stacked
  236. required
  237. />
  238. <StyledNumberField
  239. name="config.schedule.frequency"
  240. label={t('Frequency')}
  241. placeholder="e.g. 1"
  242. hideLabel
  243. required
  244. />
  245. <StyledSelectField
  246. name="config.schedule.interval"
  247. label={t('Interval')}
  248. options={getIntervals(
  249. Number(this.form.getValue('config.schedule.frequency') ?? 1)
  250. )}
  251. hideLabel
  252. required
  253. />
  254. </CombinedField>
  255. <NumberField
  256. name="config.checkin_margin"
  257. label={t('Check-in Margin')}
  258. help={t(
  259. "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."
  260. )}
  261. placeholder="e.g. 30"
  262. />
  263. </Fragment>
  264. );
  265. default:
  266. return null;
  267. }
  268. }}
  269. </Observer>
  270. </PanelBody>
  271. </Panel>
  272. </Form>
  273. );
  274. }
  275. }
  276. const CombinedField = styled('div')`
  277. display: grid;
  278. grid-template-columns: 50% 1fr 1fr;
  279. align-items: center;
  280. border-bottom: 1px solid ${p => p.theme.innerBorder};
  281. `;
  282. const StyledNumberField = styled(NumberField)`
  283. padding: 0;
  284. border-bottom: none;
  285. `;
  286. const StyledSelectField = styled(SelectField)`
  287. padding-left: 0;
  288. `;
  289. export default withPageFilters(withProjects(MonitorForm));