monitorForm.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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 timezones 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 {Monitor, MonitorConfig, MonitorTypes, ScheduleType} from './types';
  22. const SCHEDULE_TYPES: SelectValue<ScheduleType>[] = [
  23. {value: 'crontab', label: 'Crontab'},
  24. {value: '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. if (k.indexOf('config.') !== 0) {
  50. data[k] = v;
  51. return data;
  52. }
  53. if (!data.config) {
  54. data.config = {};
  55. }
  56. if (k === 'config.schedule.frequency' || k === 'config.schedule.interval') {
  57. if (!Array.isArray(data.config.schedule)) {
  58. data.config.schedule = [null, null];
  59. }
  60. }
  61. if (k === 'config.schedule.frequency') {
  62. data.config!.schedule![0] = parseInt(v as string, 10);
  63. } else if (k === 'config.schedule.interval') {
  64. data.config!.schedule![1] = v;
  65. } else {
  66. data.config[k.substr(7)] = v;
  67. }
  68. return data;
  69. }, {});
  70. }
  71. class MonitorForm extends Component<Props> {
  72. form = new FormModel({transformData});
  73. formDataFromConfig(type: MonitorTypes, config: MonitorConfig) {
  74. const rv = {};
  75. switch (type) {
  76. case 'cron_job':
  77. rv['config.schedule_type'] = config.schedule_type;
  78. rv['config.checkin_margin'] = config.checkin_margin;
  79. rv['config.max_runtime'] = config.max_runtime;
  80. switch (config.schedule_type) {
  81. case 'interval':
  82. rv['config.schedule.frequency'] = config.schedule[0];
  83. rv['config.schedule.interval'] = config.schedule[1];
  84. break;
  85. case 'crontab':
  86. default:
  87. rv['config.schedule'] = config.schedule;
  88. rv['config.timezone'] = config.timezone;
  89. }
  90. break;
  91. default:
  92. }
  93. return rv;
  94. }
  95. render() {
  96. const {monitor, submitLabel} = this.props;
  97. const selectedProjectId = this.props.selection.projects[0];
  98. const selectedProject = selectedProjectId
  99. ? this.props.projects.find(p => p.id === selectedProjectId + '')
  100. : null;
  101. return (
  102. <Form
  103. allowUndo
  104. requireChanges
  105. apiEndpoint={this.props.apiEndpoint}
  106. apiMethod={this.props.apiMethod}
  107. model={this.form}
  108. initialData={
  109. monitor
  110. ? {
  111. name: monitor.name,
  112. type: monitor.type ?? DEFAULT_MONITOR_TYPE,
  113. project: monitor.project.slug,
  114. ...this.formDataFromConfig(monitor.type, monitor.config),
  115. }
  116. : {
  117. project: selectedProject ? selectedProject.slug : null,
  118. type: DEFAULT_MONITOR_TYPE,
  119. }
  120. }
  121. onSubmitSuccess={this.props.onSubmitSuccess}
  122. submitLabel={submitLabel}
  123. >
  124. <Panel>
  125. <PanelHeader>{t('Details')}</PanelHeader>
  126. <PanelBody>
  127. {monitor && (
  128. <FieldGroup label={t('ID')}>
  129. <div className="controls">
  130. <TextCopyInput>{monitor.id}</TextCopyInput>
  131. </div>
  132. </FieldGroup>
  133. )}
  134. <SentryProjectSelectorField
  135. name="project"
  136. label={t('Project')}
  137. projects={this.props.projects.filter(project => project.isMember)}
  138. valueIsSlug
  139. help={t(
  140. "Select the project which contains the recurring job you'd like to monitor."
  141. )}
  142. required
  143. />
  144. <TextField
  145. name="name"
  146. placeholder={t('My Cron Job')}
  147. label={t('Name your cron monitor')}
  148. required
  149. />
  150. </PanelBody>
  151. </Panel>
  152. <Panel>
  153. <PanelHeader>{t('Config')}</PanelHeader>
  154. <PanelBody>
  155. {monitor !== undefined && monitor.nextCheckIn && (
  156. <PanelAlert type="info">
  157. {tct(
  158. 'Any changes you make to the execution schedule will only be applied after the next expected check-in [nextCheckin].',
  159. {
  160. nextCheckin: (
  161. <strong>
  162. <TimeSince date={monitor.nextCheckIn} />
  163. </strong>
  164. ),
  165. }
  166. )}
  167. </PanelAlert>
  168. )}
  169. <NumberField
  170. name="config.max_runtime"
  171. label={t('Max Runtime')}
  172. help={t(
  173. "Set the number of minutes a recurring job is allowed to run before it's considered failed"
  174. )}
  175. placeholder="e.g. 30"
  176. />
  177. <SelectField
  178. name="config.schedule_type"
  179. label={t('Schedule Type')}
  180. options={SCHEDULE_TYPES}
  181. required
  182. />
  183. <Observer>
  184. {() => {
  185. switch (this.form.getValue('config.schedule_type')) {
  186. case 'crontab':
  187. return (
  188. <Fragment>
  189. <TextField
  190. name="config.schedule"
  191. label={t('Schedule')}
  192. placeholder="*/5 * * * *"
  193. required
  194. help={tct(
  195. 'Any schedule changes will be applied to the next check-in. See [link:Wikipedia] for crontab syntax.',
  196. {
  197. link: (
  198. <ExternalLink href="https://en.wikipedia.org/wiki/Cron" />
  199. ),
  200. }
  201. )}
  202. css={{input: {fontFamily: commonTheme.text.familyMono}}}
  203. />
  204. <SelectField
  205. name="config.timezone"
  206. label={t('Timezone')}
  207. defaultValue="UTC"
  208. options={timezones.map(([value, label]) => ({value, label}))}
  209. help={tct(
  210. "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.",
  211. {code: <code />}
  212. )}
  213. />
  214. <NumberField
  215. name="config.checkin_margin"
  216. label={t('Check-in Margin')}
  217. help={t(
  218. "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."
  219. )}
  220. placeholder="e.g. 30"
  221. />
  222. </Fragment>
  223. );
  224. case 'interval':
  225. return (
  226. <Fragment>
  227. <CombinedField>
  228. <FieldGroup
  229. label={t('Frequency')}
  230. help={t(
  231. 'The amount of time between each job execution. Example, every 5 hours.'
  232. )}
  233. stacked
  234. required
  235. />
  236. <StyledNumberField
  237. name="config.schedule.frequency"
  238. label={t('Frequency')}
  239. placeholder="e.g. 1"
  240. hideLabel
  241. required
  242. />
  243. <StyledSelectField
  244. name="config.schedule.interval"
  245. label={t('Interval')}
  246. options={getIntervals(
  247. Number(this.form.getValue('config.schedule.frequency') ?? 1)
  248. )}
  249. hideLabel
  250. required
  251. />
  252. </CombinedField>
  253. <NumberField
  254. name="config.checkin_margin"
  255. label={t('Check-in Margin')}
  256. help={t(
  257. "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."
  258. )}
  259. placeholder="e.g. 30"
  260. />
  261. </Fragment>
  262. );
  263. default:
  264. return null;
  265. }
  266. }}
  267. </Observer>
  268. </PanelBody>
  269. </Panel>
  270. </Form>
  271. );
  272. }
  273. }
  274. const CombinedField = styled('div')`
  275. display: grid;
  276. grid-template-columns: 50% 1fr 1fr;
  277. align-items: center;
  278. border-bottom: 1px solid ${p => p.theme.innerBorder};
  279. `;
  280. const StyledNumberField = styled(NumberField)`
  281. padding: 0;
  282. border-bottom: none;
  283. `;
  284. const StyledSelectField = styled(SelectField)`
  285. padding-left: 0;
  286. `;
  287. export default withPageFilters(withProjects(MonitorForm));