hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
listlengths 5
5
|
---|---|---|---|---|---|
{
"id": 0,
"code_window": [
"import { axiosInstance } from '../../../../../../../core/utils';\n",
"\n",
"const ButtonWithRightMargin = styled(Button)`\n",
" margin-right: ${({ theme }) => theme.spaces[2]}; ;\n",
"`;\n",
"\n",
"export const Regenerate = ({ onRegenerate, idToRegenerate }) => {\n",
" let isLoadingConfirmation = false;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" margin-right: ${({ theme }) => theme.spaces[2]};\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/components/Regenerate/index.js",
"type": "replace",
"edit_start_line_idx": 10
} | 'use strict';
const createSection = require('./section');
/**
* Create a new section builder with its own sections registry
*/
const createSectionBuilder = () => {
const state = {
sections: new Map(),
};
return {
/**
* Create & add a section to the builder's registry
* @param {string} sectionName - The unique name of the section
* @param {SectionOptions} options - The options used to build a {@link Section}
* @return {this}
*/
createSection(sectionName, options) {
const section = createSection(options);
state.sections.set(sectionName, section);
return this;
},
/**
* Removes a section from the builder's registry using its unique name
* @param {string} sectionName - The name of the section to delete
* @return {this}
*/
deleteSection(sectionName) {
state.sections.remove(sectionName);
return this;
},
/**
* Register a handler function for a given section
* @param {string} sectionName - The name of the section
* @param {Function} handler - The handler to register
* @return {this}
*/
addHandler(sectionName, handler) {
if (state.sections.has(sectionName)) {
state.sections.get(sectionName).hooks.handlers.register(handler);
}
return this;
},
/**
* Register a matcher function for a given section
* @param {string} sectionName - The name of the section
* @param {Function} matcher - The handler to register
* @return {this}
*/
addMatcher(sectionName, matcher) {
if (state.sections.has(sectionName)) {
state.sections.get(sectionName).hooks.matchers.register(matcher);
}
return this;
},
/**
* Build a section tree based on the registered actions and the given actions
* @param {Array<Action>} actions - The actions used to build each section
* @return {Promise<any>}
*/
async build(actions = []) {
const sections = {};
for (const [sectionName, section] of state.sections.entries()) {
sections[sectionName] = await section.build(actions);
}
return sections;
},
};
};
module.exports = createSectionBuilder;
| packages/core/admin/server/services/permission/sections-builder/builder.js | 0 | https://github.com/strapi/strapi/commit/531e9babf2069c78be5c0f98a1e1cbd666686b44 | [
0.00017597764963284135,
0.00017231008678209037,
0.00016782194143161178,
0.00017310121620539576,
0.000002531282689233194
]
|
{
"id": 0,
"code_window": [
"import { axiosInstance } from '../../../../../../../core/utils';\n",
"\n",
"const ButtonWithRightMargin = styled(Button)`\n",
" margin-right: ${({ theme }) => theme.spaces[2]}; ;\n",
"`;\n",
"\n",
"export const Regenerate = ({ onRegenerate, idToRegenerate }) => {\n",
" let isLoadingConfirmation = false;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" margin-right: ${({ theme }) => theme.spaces[2]};\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/components/Regenerate/index.js",
"type": "replace",
"edit_start_line_idx": 10
} | import { setupServer } from 'msw/node';
import { rest } from 'msw';
const handlers = [
rest.get('*/email/settings', (req, res, ctx) => {
return res(
ctx.delay(100),
ctx.status(200),
ctx.json({
config: {
provider: '',
settings: { defaultFrom: '', defaultReplyTo: '', testAddress: '' },
},
})
);
}),
];
const server = setupServer(...handlers);
export default server;
| packages/core/email/admin/src/pages/Settings/tests/utils/server.js | 0 | https://github.com/strapi/strapi/commit/531e9babf2069c78be5c0f98a1e1cbd666686b44 | [
0.00017476032371632755,
0.0001712100929580629,
0.00016727174806874245,
0.00017159820708911866,
0.0000030694911856699036
]
|
{
"id": 1,
"code_window": [
" description: body.description,\n",
" type: body.type,\n",
" });\n",
" unlockApp();\n",
" setApiToken({\n",
" ...response,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" if (isCreating) {\n",
" history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });\n",
" setCurrentStep('apiTokens.success');\n",
" }\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "add",
"edit_start_line_idx": 114
} | import React, { useEffect, useState, useRef, useReducer, useMemo } from 'react';
import { useIntl } from 'react-intl';
import {
SettingsPageTitle,
useFocusWhenNavigate,
Form,
useOverlayBlocker,
useNotification,
useTracking,
useGuidedTour,
Link,
usePersistentState,
useRBAC,
} from '@strapi/helper-plugin';
import { HeaderLayout, ContentLayout } from '@strapi/design-system/Layout';
import { Main } from '@strapi/design-system/Main';
import { Button } from '@strapi/design-system/Button';
import { Flex } from '@strapi/design-system/Flex';
import Check from '@strapi/icons/Check';
import ArrowLeft from '@strapi/icons/ArrowLeft';
import { Formik } from 'formik';
import { Stack } from '@strapi/design-system/Stack';
import { Box } from '@strapi/design-system/Box';
import { Typography } from '@strapi/design-system/Typography';
import { Grid, GridItem } from '@strapi/design-system/Grid';
import { TextInput } from '@strapi/design-system/TextInput';
import { Textarea } from '@strapi/design-system/Textarea';
import { Select, Option } from '@strapi/design-system/Select';
import { get } from 'lodash';
import { useRouteMatch, useHistory } from 'react-router-dom';
import { useQuery } from 'react-query';
import { formatAPIErrors } from '../../../../../utils';
import { axiosInstance } from '../../../../../core/utils';
import { getDateOfExpiration, schema, getActionsState } from './utils';
import LoadingView from './components/LoadingView';
import HeaderContentBox from './components/ContentBox';
import Permissions from './components/Permissions';
import Regenerate from './components/Regenerate';
import adminPermissions from '../../../../../permissions';
import { ApiTokenPermissionsContextProvider } from '../../../../../contexts/ApiTokenPermissions';
import { data as permissions } from './utils/tests/dataMock';
import init from './init';
import reducer, { initialState } from './reducer';
const ApiTokenCreateView = () => {
useFocusWhenNavigate();
const { formatMessage } = useIntl();
const { lockApp, unlockApp } = useOverlayBlocker();
const toggleNotification = useNotification();
const history = useHistory();
const [apiToken, setApiToken] = useState(
history.location.state?.apiToken.accessKey
? {
...history.location.state.apiToken,
}
: null
);
const { trackUsage } = useTracking();
const trackUsageRef = useRef(trackUsage);
const { setCurrentStep } = useGuidedTour();
const {
allowedActions: { canCreate, canUpdate },
} = useRBAC(adminPermissions.settings['api-tokens']);
const [state, dispatch] = useReducer(reducer, initialState, (state) => init(state, permissions));
const [lang] = usePersistentState('strapi-admin-language', 'en');
const {
params: { id },
} = useRouteMatch('/settings/api-tokens/:id');
const isCreating = id === 'create';
useEffect(() => {
trackUsageRef.current(isCreating ? 'didAddTokenFromList' : 'didEditTokenFromList');
}, [isCreating]);
const { status } = useQuery(
['api-token', id],
async () => {
const {
data: { data },
} = await axiosInstance.get(`/admin/api-tokens/${id}`);
setApiToken({
...data,
});
return data;
},
{
enabled: !isCreating && !apiToken,
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
const handleSubmit = async (body, actions) => {
trackUsageRef.current(isCreating ? 'willCreateToken' : 'willEditToken');
lockApp();
try {
const {
data: { data: response },
} = isCreating
? await axiosInstance.post(`/admin/api-tokens`, body)
: await axiosInstance.put(`/admin/api-tokens/${id}`, {
name: body.name,
description: body.description,
type: body.type,
});
unlockApp();
setApiToken({
...response,
});
toggleNotification({
type: 'success',
message: isCreating
? formatMessage({
id: 'notification.success.tokencreated',
defaultMessage: 'API Token successfully created',
})
: formatMessage({
id: 'notification.success.tokenedited',
defaultMessage: 'API Token successfully edited',
}),
});
trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', {
type: apiToken.type,
});
if (isCreating) {
history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });
setCurrentStep('apiTokens.success');
}
} catch (err) {
const errors = formatAPIErrors(err.response.data);
actions.setErrors(errors);
toggleNotification({
type: 'warning',
message: get(err, 'response.data.message', 'notification.error'),
});
unlockApp();
}
};
const hasAllActionsSelected = useMemo(() => {
const {
modifiedData: { collectionTypes, singleTypes, custom },
} = state;
const dataToCheck = { ...collectionTypes, ...singleTypes, ...custom };
const areAllActionsSelected = getActionsState(dataToCheck, true);
return areAllActionsSelected;
}, [state]);
const hasAllActionsNotSelected = useMemo(() => {
const {
modifiedData: { collectionTypes, singleTypes, custom },
} = state;
const dataToCheck = { ...collectionTypes, ...singleTypes, ...custom };
const areAllActionsNotSelected = getActionsState(dataToCheck, false);
return areAllActionsNotSelected;
}, [state]);
const hasReadOnlyActionsSelected = useMemo(() => {
const {
modifiedData: { collectionTypes, singleTypes, custom },
} = state;
const dataToCheck = { ...collectionTypes, ...singleTypes, ...custom };
const areAllActionsReadOnly = getActionsState(dataToCheck, false, ['find', 'findOne']);
return areAllActionsReadOnly;
}, [state]);
const tokenTypeValue = useMemo(() => {
if (hasAllActionsSelected && !hasReadOnlyActionsSelected) return 'full-access';
if (hasReadOnlyActionsSelected) return 'read-only';
if (hasAllActionsNotSelected) return null;
return 'custom';
}, [hasAllActionsSelected, hasReadOnlyActionsSelected, hasAllActionsNotSelected]);
console.log('tokenType', tokenTypeValue);
const handleChangeCheckbox = ({ target: { name, value } }) => {
dispatch({
type: 'ON_CHANGE',
name,
value,
});
};
const handleChangeSelectAllCheckbox = ({ target: { name, value } }) =>
dispatch({
type: 'ON_CHANGE_SELECT_ALL',
keys: name.split('.'),
value,
});
const handleChangeSelectApiTokenType = ({ target: { value } }) => {
const { modifiedData } = state;
if (value === 'full-access') {
Object.keys(modifiedData).forEach((contentTypes) => {
Object.keys(modifiedData[contentTypes]).forEach((contentType) => {
dispatch({
type: 'ON_CHANGE_SELECT_ALL',
keys: [contentTypes, contentType],
value: true,
});
});
});
}
if (value === 'read-only') {
Object.keys(modifiedData).forEach((contentTypes) => {
Object.keys(modifiedData[contentTypes]).forEach((contentType) => {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
keys: [contentTypes, contentType],
value: false,
});
});
});
}
};
const handleRegenerate = (newKey) => {
setApiToken({
...apiToken,
accessKey: newKey,
});
};
const providerValue = {
...state,
onChange: handleChangeCheckbox,
onChangeSelectAll: handleChangeSelectAllCheckbox,
};
const canEditInputs = (canUpdate && !isCreating) || (canCreate && isCreating);
const isLoading = !isCreating && !apiToken && status !== 'success';
if (isLoading) {
return <LoadingView apiTokenName={apiToken?.name} />;
}
return (
<ApiTokenPermissionsContextProvider value={providerValue}>
<Main>
<SettingsPageTitle name="API Tokens" />
<Formik
validationSchema={schema}
validateOnChange={false}
initialValues={{
name: apiToken?.name || '',
description: apiToken?.description || '',
type: apiToken?.type,
lifespan: apiToken?.lifespan,
}}
onSubmit={handleSubmit}
>
{({ errors, handleChange, isSubmitting, values }) => {
return (
<Form>
<HeaderLayout
title={
apiToken?.name ||
formatMessage({
id: 'Settings.apiTokens.createPage.title',
defaultMessage: 'Create API Token',
})
}
primaryAction={
canEditInputs && (
<Flex justifyContent="center">
{apiToken?.name && (
<Regenerate
onRegenerate={handleRegenerate}
idToRegenerate={apiToken?.id}
/>
)}
<Button
disabled={isSubmitting}
loading={isSubmitting}
startIcon={<Check />}
type="submit"
size="S"
>
{formatMessage({
id: 'global.save',
defaultMessage: 'Save',
})}
</Button>
</Flex>
)
}
navigationAction={
<Link startIcon={<ArrowLeft />} to="/settings/api-tokens">
{formatMessage({
id: 'global.back',
defaultMessage: 'Back',
})}
</Link>
}
/>
<ContentLayout>
<Stack spacing={6}>
{Boolean(apiToken?.name) && <HeaderContentBox apiToken={apiToken.accessKey} />}
<Box
background="neutral0"
hasRadius
shadow="filterShadow"
paddingTop={6}
paddingBottom={6}
paddingLeft={7}
paddingRight={7}
>
<Stack spacing={4}>
<Typography variant="delta" as="h2">
{formatMessage({
id: 'global.details',
defaultMessage: 'Details',
})}
</Typography>
<Grid gap={5}>
<GridItem key="name" col={6} xs={12}>
<TextInput
name="name"
error={
errors.name
? formatMessage(
errors.name?.id
? errors.name
: { id: errors.name, defaultMessage: errors.name }
)
: null
}
label={formatMessage({
id: 'Settings.apiTokens.form.name',
defaultMessage: 'Name',
})}
onChange={handleChange}
value={values.name}
disabled={!canEditInputs}
required
/>
</GridItem>
<GridItem key="description" col={6} xs={12}>
<Textarea
label={formatMessage({
id: 'Settings.apiTokens.form.description',
defaultMessage: 'Description',
})}
name="description"
error={
errors.description
? formatMessage(
errors.description?.id
? errors.description
: {
id: errors.description,
defaultMessage: errors.description,
}
)
: null
}
onChange={handleChange}
disabled={!canEditInputs}
>
{values.description}
</Textarea>
</GridItem>
<GridItem key="lifespan" col={6} xs={12}>
<Select
name="lifespan"
label={formatMessage({
id: 'Settings.apiTokens.form.duration',
defaultMessage: 'Token duration',
})}
value={values.lifespan}
error={
errors.lifespan
? formatMessage(
errors.lifespan?.id
? errors.lifespan
: { id: errors.lifespan, defaultMessage: errors.lifespan }
)
: null
}
onChange={(value) => {
handleChange({ target: { name: 'lifespan', value } });
}}
required
disabled={!isCreating}
placeholder="Select"
>
<Option value={7}>
{formatMessage({
id: 'Settings.apiTokens.duration.7-days',
defaultMessage: '7 days',
})}
</Option>
<Option value={30}>
{formatMessage({
id: 'Settings.apiTokens.duration.30-days',
defaultMessage: '30 days',
})}
</Option>
<Option value={90}>
{formatMessage({
id: 'Settings.apiTokens.duration.90-days',
defaultMessage: '90 days',
})}
</Option>
<Option value={null}>
{formatMessage({
id: 'Settings.apiTokens.duration.unlimited',
defaultMessage: 'Unlimited',
})}
</Option>
</Select>
<Typography variant="pi" textColor="neutral600">
{!isCreating &&
`${formatMessage({
id: 'Settings.apiTokens.duration.expiration-date',
defaultMessage: 'Expiration date',
})}: ${getDateOfExpiration(
apiToken?.createdAt,
values.lifespan,
lang
)}`}
</Typography>
</GridItem>
<GridItem key="type" col={6} xs={12}>
<Select
name="type"
label={formatMessage({
id: 'Settings.apiTokens.form.type',
defaultMessage: 'Token type',
})}
value={values.type}
error={
errors.type
? formatMessage(
errors.type?.id
? errors.type
: { id: errors.type, defaultMessage: errors.type }
)
: null
}
onChange={(value) => {
handleChangeSelectApiTokenType({ target: { value } });
handleChange({ target: { name: 'type', value } });
}}
placeholder="Select"
required
disabled={!canEditInputs}
>
<Option value="read-only">
{formatMessage({
id: 'Settings.apiTokens.types.read-only',
defaultMessage: 'Read-only',
})}
</Option>
<Option value="full-access">
{formatMessage({
id: 'Settings.apiTokens.types.full-access',
defaultMessage: 'Full access',
})}
</Option>
<Option value="custom">
{formatMessage({
id: 'Settings.apiTokens.types.custom',
defaultMessage: 'Custom',
})}
</Option>
</Select>
</GridItem>
</Grid>
</Stack>
</Box>
<Permissions disabled={!canEditInputs} />
</Stack>
</ContentLayout>
</Form>
);
}}
</Formik>
</Main>
</ApiTokenPermissionsContextProvider>
);
};
export default ApiTokenCreateView;
| packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js | 1 | https://github.com/strapi/strapi/commit/531e9babf2069c78be5c0f98a1e1cbd666686b44 | [
0.9845874309539795,
0.02606605738401413,
0.0001619285758351907,
0.0001690808276180178,
0.1428155153989792
]
|
{
"id": 1,
"code_window": [
" description: body.description,\n",
" type: body.type,\n",
" });\n",
" unlockApp();\n",
" setApiToken({\n",
" ...response,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" if (isCreating) {\n",
" history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });\n",
" setCurrentStep('apiTokens.success');\n",
" }\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "add",
"edit_start_line_idx": 114
} | 'use strict';
module.exports = {};
| packages/generators/generators/lib/files/js/plugin/server/middlewares/index.js | 0 | https://github.com/strapi/strapi/commit/531e9babf2069c78be5c0f98a1e1cbd666686b44 | [
0.00017332073184661567,
0.00017332073184661567,
0.00017332073184661567,
0.00017332073184661567,
0
]
|
{
"id": 1,
"code_window": [
" description: body.description,\n",
" type: body.type,\n",
" });\n",
" unlockApp();\n",
" setApiToken({\n",
" ...response,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" if (isCreating) {\n",
" history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });\n",
" setCurrentStep('apiTokens.success');\n",
" }\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "add",
"edit_start_line_idx": 114
} | class Middlewares {
constructor() {
this.middlewares = [];
}
add(middleware) {
this.middlewares.push(middleware);
}
}
export default () => new Middlewares();
| packages/core/admin/admin/src/core/apis/Middlewares.js | 0 | https://github.com/strapi/strapi/commit/531e9babf2069c78be5c0f98a1e1cbd666686b44 | [
0.0006845234893262386,
0.0004282566951587796,
0.00017198987188749015,
0.0004282566951587796,
0.00025626682327128947
]
|
{
"id": 1,
"code_window": [
" description: body.description,\n",
" type: body.type,\n",
" });\n",
" unlockApp();\n",
" setApiToken({\n",
" ...response,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" if (isCreating) {\n",
" history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });\n",
" setCurrentStep('apiTokens.success');\n",
" }\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "add",
"edit_start_line_idx": 114
} | 'use strict';
const { migrate } = require('./migrate');
const { areScalarAttributesOnly } = require('./utils');
const TMP_TABLE_NAME = '__tmp__i18n_field_migration';
const batchInsertInTmpTable = async ({ updatesInfo }, { transacting: trx }) => {
const tmpEntries = [];
updatesInfo.forEach(({ entriesIdsToUpdate, attributesValues }) => {
entriesIdsToUpdate.forEach((id) => {
tmpEntries.push({ id, ...attributesValues });
});
});
await trx.batchInsert(TMP_TABLE_NAME, tmpEntries, 100);
};
const updateFromTmpTable = async ({ model, attributesToMigrate }, { transacting: trx }) => {
const { collectionName } = model;
if (model.client === 'pg') {
const substitutes = attributesToMigrate.map(() => '?? = ??.??').join(',');
const bindings = [collectionName];
attributesToMigrate.forEach((attr) => bindings.push(attr, TMP_TABLE_NAME, attr));
bindings.push(TMP_TABLE_NAME, collectionName, TMP_TABLE_NAME);
await trx.raw(`UPDATE ?? SET ${substitutes} FROM ?? WHERE ??.id = ??.id;`, bindings);
} else if (model.client === 'mysql') {
const substitutes = attributesToMigrate.map(() => '??.?? = ??.??').join(',');
const bindings = [collectionName, TMP_TABLE_NAME, collectionName, TMP_TABLE_NAME];
attributesToMigrate.forEach((attr) =>
bindings.push(collectionName, attr, TMP_TABLE_NAME, attr)
);
await trx.raw(`UPDATE ?? JOIN ?? ON ??.id = ??.id SET ${substitutes};`, bindings);
}
};
const createTmpTable = async ({ ORM, attributesToMigrate, model }) => {
const columnsToCopy = ['id', ...attributesToMigrate];
await deleteTmpTable({ ORM });
await ORM.knex.raw(`CREATE TABLE ?? AS ??`, [
TMP_TABLE_NAME,
ORM.knex.select(columnsToCopy).from(model.collectionName).whereRaw('?', 0),
]);
};
const deleteTmpTable = ({ ORM }) => ORM.knex.schema.dropTableIfExists(TMP_TABLE_NAME);
const migrateForBookshelf = async ({ ORM, model, attributesToMigrate }) => {
const onlyScalarAttrs = areScalarAttributesOnly({ model, attributes: attributesToMigrate });
// optimize migration for pg and mysql when there are only scalar attributes to migrate
if (onlyScalarAttrs && ['pg', 'mysql'].includes(model.client)) {
// create table outside of the transaction because mysql doesn't accept the creation inside
await createTmpTable({ ORM, attributesToMigrate, model });
await ORM.knex.transaction(async (transacting) => {
await migrate(
{ model, attributesToMigrate },
{ migrateFn: batchInsertInTmpTable, transacting }
);
await updateFromTmpTable({ model, attributesToMigrate }, { transacting });
});
await deleteTmpTable({ ORM });
} else {
await ORM.knex.transaction(async (transacting) => {
await migrate({ model, attributesToMigrate }, { transacting });
});
}
};
module.exports = migrateForBookshelf;
| packages/plugins/i18n/server/migrations/field/migrate-for-bookshelf.js | 0 | https://github.com/strapi/strapi/commit/531e9babf2069c78be5c0f98a1e1cbd666686b44 | [
0.00017332930292468518,
0.00017197210399899632,
0.00016917797620408237,
0.00017228415526915342,
0.0000013223628911873675
]
|
{
"id": 2,
"code_window": [
" });\n",
"\n",
" trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', {\n",
" type: apiToken.type,\n",
" });\n",
"\n",
" if (isCreating) {\n",
" history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });\n",
" setCurrentStep('apiTokens.success');\n",
" }\n",
" } catch (err) {\n",
" const errors = formatAPIErrors(err.response.data);\n",
" actions.setErrors(errors);\n",
"\n",
" toggleNotification({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 135
} | import React, { useEffect, useState, useRef, useReducer, useMemo } from 'react';
import { useIntl } from 'react-intl';
import {
SettingsPageTitle,
useFocusWhenNavigate,
Form,
useOverlayBlocker,
useNotification,
useTracking,
useGuidedTour,
Link,
usePersistentState,
useRBAC,
} from '@strapi/helper-plugin';
import { HeaderLayout, ContentLayout } from '@strapi/design-system/Layout';
import { Main } from '@strapi/design-system/Main';
import { Button } from '@strapi/design-system/Button';
import { Flex } from '@strapi/design-system/Flex';
import Check from '@strapi/icons/Check';
import ArrowLeft from '@strapi/icons/ArrowLeft';
import { Formik } from 'formik';
import { Stack } from '@strapi/design-system/Stack';
import { Box } from '@strapi/design-system/Box';
import { Typography } from '@strapi/design-system/Typography';
import { Grid, GridItem } from '@strapi/design-system/Grid';
import { TextInput } from '@strapi/design-system/TextInput';
import { Textarea } from '@strapi/design-system/Textarea';
import { Select, Option } from '@strapi/design-system/Select';
import { get } from 'lodash';
import { useRouteMatch, useHistory } from 'react-router-dom';
import { useQuery } from 'react-query';
import { formatAPIErrors } from '../../../../../utils';
import { axiosInstance } from '../../../../../core/utils';
import { getDateOfExpiration, schema, getActionsState } from './utils';
import LoadingView from './components/LoadingView';
import HeaderContentBox from './components/ContentBox';
import Permissions from './components/Permissions';
import Regenerate from './components/Regenerate';
import adminPermissions from '../../../../../permissions';
import { ApiTokenPermissionsContextProvider } from '../../../../../contexts/ApiTokenPermissions';
import { data as permissions } from './utils/tests/dataMock';
import init from './init';
import reducer, { initialState } from './reducer';
const ApiTokenCreateView = () => {
useFocusWhenNavigate();
const { formatMessage } = useIntl();
const { lockApp, unlockApp } = useOverlayBlocker();
const toggleNotification = useNotification();
const history = useHistory();
const [apiToken, setApiToken] = useState(
history.location.state?.apiToken.accessKey
? {
...history.location.state.apiToken,
}
: null
);
const { trackUsage } = useTracking();
const trackUsageRef = useRef(trackUsage);
const { setCurrentStep } = useGuidedTour();
const {
allowedActions: { canCreate, canUpdate },
} = useRBAC(adminPermissions.settings['api-tokens']);
const [state, dispatch] = useReducer(reducer, initialState, (state) => init(state, permissions));
const [lang] = usePersistentState('strapi-admin-language', 'en');
const {
params: { id },
} = useRouteMatch('/settings/api-tokens/:id');
const isCreating = id === 'create';
useEffect(() => {
trackUsageRef.current(isCreating ? 'didAddTokenFromList' : 'didEditTokenFromList');
}, [isCreating]);
const { status } = useQuery(
['api-token', id],
async () => {
const {
data: { data },
} = await axiosInstance.get(`/admin/api-tokens/${id}`);
setApiToken({
...data,
});
return data;
},
{
enabled: !isCreating && !apiToken,
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
const handleSubmit = async (body, actions) => {
trackUsageRef.current(isCreating ? 'willCreateToken' : 'willEditToken');
lockApp();
try {
const {
data: { data: response },
} = isCreating
? await axiosInstance.post(`/admin/api-tokens`, body)
: await axiosInstance.put(`/admin/api-tokens/${id}`, {
name: body.name,
description: body.description,
type: body.type,
});
unlockApp();
setApiToken({
...response,
});
toggleNotification({
type: 'success',
message: isCreating
? formatMessage({
id: 'notification.success.tokencreated',
defaultMessage: 'API Token successfully created',
})
: formatMessage({
id: 'notification.success.tokenedited',
defaultMessage: 'API Token successfully edited',
}),
});
trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', {
type: apiToken.type,
});
if (isCreating) {
history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });
setCurrentStep('apiTokens.success');
}
} catch (err) {
const errors = formatAPIErrors(err.response.data);
actions.setErrors(errors);
toggleNotification({
type: 'warning',
message: get(err, 'response.data.message', 'notification.error'),
});
unlockApp();
}
};
const hasAllActionsSelected = useMemo(() => {
const {
modifiedData: { collectionTypes, singleTypes, custom },
} = state;
const dataToCheck = { ...collectionTypes, ...singleTypes, ...custom };
const areAllActionsSelected = getActionsState(dataToCheck, true);
return areAllActionsSelected;
}, [state]);
const hasAllActionsNotSelected = useMemo(() => {
const {
modifiedData: { collectionTypes, singleTypes, custom },
} = state;
const dataToCheck = { ...collectionTypes, ...singleTypes, ...custom };
const areAllActionsNotSelected = getActionsState(dataToCheck, false);
return areAllActionsNotSelected;
}, [state]);
const hasReadOnlyActionsSelected = useMemo(() => {
const {
modifiedData: { collectionTypes, singleTypes, custom },
} = state;
const dataToCheck = { ...collectionTypes, ...singleTypes, ...custom };
const areAllActionsReadOnly = getActionsState(dataToCheck, false, ['find', 'findOne']);
return areAllActionsReadOnly;
}, [state]);
const tokenTypeValue = useMemo(() => {
if (hasAllActionsSelected && !hasReadOnlyActionsSelected) return 'full-access';
if (hasReadOnlyActionsSelected) return 'read-only';
if (hasAllActionsNotSelected) return null;
return 'custom';
}, [hasAllActionsSelected, hasReadOnlyActionsSelected, hasAllActionsNotSelected]);
console.log('tokenType', tokenTypeValue);
const handleChangeCheckbox = ({ target: { name, value } }) => {
dispatch({
type: 'ON_CHANGE',
name,
value,
});
};
const handleChangeSelectAllCheckbox = ({ target: { name, value } }) =>
dispatch({
type: 'ON_CHANGE_SELECT_ALL',
keys: name.split('.'),
value,
});
const handleChangeSelectApiTokenType = ({ target: { value } }) => {
const { modifiedData } = state;
if (value === 'full-access') {
Object.keys(modifiedData).forEach((contentTypes) => {
Object.keys(modifiedData[contentTypes]).forEach((contentType) => {
dispatch({
type: 'ON_CHANGE_SELECT_ALL',
keys: [contentTypes, contentType],
value: true,
});
});
});
}
if (value === 'read-only') {
Object.keys(modifiedData).forEach((contentTypes) => {
Object.keys(modifiedData[contentTypes]).forEach((contentType) => {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
keys: [contentTypes, contentType],
value: false,
});
});
});
}
};
const handleRegenerate = (newKey) => {
setApiToken({
...apiToken,
accessKey: newKey,
});
};
const providerValue = {
...state,
onChange: handleChangeCheckbox,
onChangeSelectAll: handleChangeSelectAllCheckbox,
};
const canEditInputs = (canUpdate && !isCreating) || (canCreate && isCreating);
const isLoading = !isCreating && !apiToken && status !== 'success';
if (isLoading) {
return <LoadingView apiTokenName={apiToken?.name} />;
}
return (
<ApiTokenPermissionsContextProvider value={providerValue}>
<Main>
<SettingsPageTitle name="API Tokens" />
<Formik
validationSchema={schema}
validateOnChange={false}
initialValues={{
name: apiToken?.name || '',
description: apiToken?.description || '',
type: apiToken?.type,
lifespan: apiToken?.lifespan,
}}
onSubmit={handleSubmit}
>
{({ errors, handleChange, isSubmitting, values }) => {
return (
<Form>
<HeaderLayout
title={
apiToken?.name ||
formatMessage({
id: 'Settings.apiTokens.createPage.title',
defaultMessage: 'Create API Token',
})
}
primaryAction={
canEditInputs && (
<Flex justifyContent="center">
{apiToken?.name && (
<Regenerate
onRegenerate={handleRegenerate}
idToRegenerate={apiToken?.id}
/>
)}
<Button
disabled={isSubmitting}
loading={isSubmitting}
startIcon={<Check />}
type="submit"
size="S"
>
{formatMessage({
id: 'global.save',
defaultMessage: 'Save',
})}
</Button>
</Flex>
)
}
navigationAction={
<Link startIcon={<ArrowLeft />} to="/settings/api-tokens">
{formatMessage({
id: 'global.back',
defaultMessage: 'Back',
})}
</Link>
}
/>
<ContentLayout>
<Stack spacing={6}>
{Boolean(apiToken?.name) && <HeaderContentBox apiToken={apiToken.accessKey} />}
<Box
background="neutral0"
hasRadius
shadow="filterShadow"
paddingTop={6}
paddingBottom={6}
paddingLeft={7}
paddingRight={7}
>
<Stack spacing={4}>
<Typography variant="delta" as="h2">
{formatMessage({
id: 'global.details',
defaultMessage: 'Details',
})}
</Typography>
<Grid gap={5}>
<GridItem key="name" col={6} xs={12}>
<TextInput
name="name"
error={
errors.name
? formatMessage(
errors.name?.id
? errors.name
: { id: errors.name, defaultMessage: errors.name }
)
: null
}
label={formatMessage({
id: 'Settings.apiTokens.form.name',
defaultMessage: 'Name',
})}
onChange={handleChange}
value={values.name}
disabled={!canEditInputs}
required
/>
</GridItem>
<GridItem key="description" col={6} xs={12}>
<Textarea
label={formatMessage({
id: 'Settings.apiTokens.form.description',
defaultMessage: 'Description',
})}
name="description"
error={
errors.description
? formatMessage(
errors.description?.id
? errors.description
: {
id: errors.description,
defaultMessage: errors.description,
}
)
: null
}
onChange={handleChange}
disabled={!canEditInputs}
>
{values.description}
</Textarea>
</GridItem>
<GridItem key="lifespan" col={6} xs={12}>
<Select
name="lifespan"
label={formatMessage({
id: 'Settings.apiTokens.form.duration',
defaultMessage: 'Token duration',
})}
value={values.lifespan}
error={
errors.lifespan
? formatMessage(
errors.lifespan?.id
? errors.lifespan
: { id: errors.lifespan, defaultMessage: errors.lifespan }
)
: null
}
onChange={(value) => {
handleChange({ target: { name: 'lifespan', value } });
}}
required
disabled={!isCreating}
placeholder="Select"
>
<Option value={7}>
{formatMessage({
id: 'Settings.apiTokens.duration.7-days',
defaultMessage: '7 days',
})}
</Option>
<Option value={30}>
{formatMessage({
id: 'Settings.apiTokens.duration.30-days',
defaultMessage: '30 days',
})}
</Option>
<Option value={90}>
{formatMessage({
id: 'Settings.apiTokens.duration.90-days',
defaultMessage: '90 days',
})}
</Option>
<Option value={null}>
{formatMessage({
id: 'Settings.apiTokens.duration.unlimited',
defaultMessage: 'Unlimited',
})}
</Option>
</Select>
<Typography variant="pi" textColor="neutral600">
{!isCreating &&
`${formatMessage({
id: 'Settings.apiTokens.duration.expiration-date',
defaultMessage: 'Expiration date',
})}: ${getDateOfExpiration(
apiToken?.createdAt,
values.lifespan,
lang
)}`}
</Typography>
</GridItem>
<GridItem key="type" col={6} xs={12}>
<Select
name="type"
label={formatMessage({
id: 'Settings.apiTokens.form.type',
defaultMessage: 'Token type',
})}
value={values.type}
error={
errors.type
? formatMessage(
errors.type?.id
? errors.type
: { id: errors.type, defaultMessage: errors.type }
)
: null
}
onChange={(value) => {
handleChangeSelectApiTokenType({ target: { value } });
handleChange({ target: { name: 'type', value } });
}}
placeholder="Select"
required
disabled={!canEditInputs}
>
<Option value="read-only">
{formatMessage({
id: 'Settings.apiTokens.types.read-only',
defaultMessage: 'Read-only',
})}
</Option>
<Option value="full-access">
{formatMessage({
id: 'Settings.apiTokens.types.full-access',
defaultMessage: 'Full access',
})}
</Option>
<Option value="custom">
{formatMessage({
id: 'Settings.apiTokens.types.custom',
defaultMessage: 'Custom',
})}
</Option>
</Select>
</GridItem>
</Grid>
</Stack>
</Box>
<Permissions disabled={!canEditInputs} />
</Stack>
</ContentLayout>
</Form>
);
}}
</Formik>
</Main>
</ApiTokenPermissionsContextProvider>
);
};
export default ApiTokenCreateView;
| packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js | 1 | https://github.com/strapi/strapi/commit/531e9babf2069c78be5c0f98a1e1cbd666686b44 | [
0.998229444026947,
0.03897508233785629,
0.00016468483954668045,
0.00018058667774312198,
0.1912739872932434
]
|
{
"id": 2,
"code_window": [
" });\n",
"\n",
" trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', {\n",
" type: apiToken.type,\n",
" });\n",
"\n",
" if (isCreating) {\n",
" history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });\n",
" setCurrentStep('apiTokens.success');\n",
" }\n",
" } catch (err) {\n",
" const errors = formatAPIErrors(err.response.data);\n",
" actions.setErrors(errors);\n",
"\n",
" toggleNotification({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 135
} | import customGlobalLinks from 'ee_else_ce/hooks/useSettingsMenu/utils/customGlobalLinks';
import defaultGlobalLinks from './defaultGlobalLinks';
export default [...defaultGlobalLinks, ...customGlobalLinks];
| packages/core/admin/admin/src/hooks/useSettingsMenu/utils/globalLinks.js | 0 | https://github.com/strapi/strapi/commit/531e9babf2069c78be5c0f98a1e1cbd666686b44 | [
0.00017517691594548523,
0.00017517691594548523,
0.00017517691594548523,
0.00017517691594548523,
0
]
|
{
"id": 2,
"code_window": [
" });\n",
"\n",
" trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', {\n",
" type: apiToken.type,\n",
" });\n",
"\n",
" if (isCreating) {\n",
" history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });\n",
" setCurrentStep('apiTokens.success');\n",
" }\n",
" } catch (err) {\n",
" const errors = formatAPIErrors(err.response.data);\n",
" actions.setErrors(errors);\n",
"\n",
" toggleNotification({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 135
} | import reducer, { initialState } from '../reducer';
describe('ADMIN | LeftMenu | reducer', () => {
describe('DEFAULT_ACTION', () => {
it('should return the initialState', () => {
const state = {
test: true,
};
expect(reducer(state, {})).toEqual(state);
});
});
describe('SET_SECTION_LINKS', () => {
it('sets the generalSectionLinks and the pluginsSectionLinks with the action', () => {
const state = { ...initialState };
const action = {
type: 'SET_SECTION_LINKS',
data: {
authorizedGeneralSectionLinks: ['authorizd', 'links'],
authorizedPluginSectionLinks: ['authorizd', 'plugin-links'],
},
};
const expected = {
...initialState,
generalSectionLinks: ['authorizd', 'links'],
pluginsSectionLinks: ['authorizd', 'plugin-links'],
};
const actual = reducer(state, action);
expect(actual).toEqual(expected);
});
});
});
| packages/core/admin/admin/src/hooks/useMenu/tests/reducer.test.js | 0 | https://github.com/strapi/strapi/commit/531e9babf2069c78be5c0f98a1e1cbd666686b44 | [
0.00017539854161441326,
0.00017283388297073543,
0.00016839099407661706,
0.00017377300537191331,
0.0000026530856302997563
]
|
{
"id": 2,
"code_window": [
" });\n",
"\n",
" trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', {\n",
" type: apiToken.type,\n",
" });\n",
"\n",
" if (isCreating) {\n",
" history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });\n",
" setCurrentStep('apiTokens.success');\n",
" }\n",
" } catch (err) {\n",
" const errors = formatAPIErrors(err.response.data);\n",
" actions.setErrors(errors);\n",
"\n",
" toggleNotification({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 135
} | {
"link": "Link",
"Settings.email.plugin.button.test-email": "Send test email",
"Settings.email.plugin.label.defaultFrom": "Default sender email",
"Settings.email.plugin.label.defaultReplyTo": "Default response email",
"Settings.email.plugin.label.provider": "Email provider",
"Settings.email.plugin.label.testAddress": "Recipient email",
"Settings.email.plugin.notification.config.error": "Failed to retrieve the email config",
"Settings.email.plugin.notification.data.loaded": "Email settings data has been loaded",
"Settings.email.plugin.notification.test.error": "Failed to send a test mail to {to}",
"Settings.email.plugin.notification.test.success": "Email test succeeded, check the {to} mailbox",
"Settings.email.plugin.placeholder.defaultFrom": "ex: Strapi No-Reply <[email protected]>",
"Settings.email.plugin.placeholder.defaultReplyTo": "ex: Strapi <[email protected]>",
"Settings.email.plugin.placeholder.testAddress": "ex: [email protected]",
"Settings.email.plugin.subTitle": "Test the settings for the Email plugin",
"Settings.email.plugin.text.configuration": "The plugin is configured through the {file} file, checkout this {link} for the documentation.",
"Settings.email.plugin.title": "Configuration",
"Settings.email.plugin.title.config": "Configuration",
"Settings.email.plugin.title.test": "Test email delivery",
"SettingsNav.link.settings": "Settings",
"SettingsNav.section-label": "Email plugin",
"components.Input.error.validation.email": "This is an invalid email"
}
| packages/core/email/admin/src/translations/en.json | 0 | https://github.com/strapi/strapi/commit/531e9babf2069c78be5c0f98a1e1cbd666686b44 | [
0.00017161719733849168,
0.00017043021216522902,
0.00016890735423658043,
0.00017076609947253019,
0.0000011314961056996253
]
|
{
"id": 0,
"code_window": [
"\tcontextmodel \"github.com/grafana/grafana/pkg/services/contexthandler/model\"\n",
"\tapimodels \"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/notifier\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/store\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n",
")\n",
"\n",
"const (\n",
"\tdefaultTestReceiversTimeout = 15 * time.Second\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/services/secrets\"\n"
],
"file_path": "pkg/services/ngalert/api/api_alertmanager.go",
"type": "add",
"edit_start_line_idx": 21
} | package api
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/go-openapi/strfmt"
alertingNotify "github.com/grafana/alerting/notify"
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/notifier"
"github.com/grafana/grafana/pkg/services/ngalert/store"
"github.com/grafana/grafana/pkg/util"
)
const (
defaultTestReceiversTimeout = 15 * time.Second
maxTestReceiversTimeout = 30 * time.Second
)
type AlertmanagerSrv struct {
log log.Logger
ac accesscontrol.AccessControl
mam *notifier.MultiOrgAlertmanager
crypto notifier.Crypto
}
type UnknownReceiverError struct {
UID string
}
func (e UnknownReceiverError) Error() string {
return fmt.Sprintf("unknown receiver: %s", e.UID)
}
func (srv AlertmanagerSrv) RouteGetAMStatus(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
return response.JSON(http.StatusOK, am.GetStatus())
}
func (srv AlertmanagerSrv) RouteCreateSilence(c *contextmodel.ReqContext, postableSilence apimodels.PostableSilence) response.Response {
err := postableSilence.Validate(strfmt.Default)
if err != nil {
srv.log.Error("silence failed validation", "error", err)
return ErrResp(http.StatusBadRequest, err, "silence failed validation")
}
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
action := accesscontrol.ActionAlertingInstanceUpdate
if postableSilence.ID == "" {
action = accesscontrol.ActionAlertingInstanceCreate
}
if !accesscontrol.HasAccess(srv.ac, c)(accesscontrol.ReqOrgAdminOrEditor, accesscontrol.EvalPermission(action)) {
errAction := "update"
if postableSilence.ID == "" {
errAction = "create"
}
return ErrResp(http.StatusUnauthorized, fmt.Errorf("user is not authorized to %s silences", errAction), "")
}
silenceID, err := am.CreateSilence(&postableSilence)
if err != nil {
if errors.Is(err, alertingNotify.ErrSilenceNotFound) {
return ErrResp(http.StatusNotFound, err, "")
}
if errors.Is(err, alertingNotify.ErrCreateSilenceBadPayload) {
return ErrResp(http.StatusBadRequest, err, "")
}
return ErrResp(http.StatusInternalServerError, err, "failed to create silence")
}
return response.JSON(http.StatusAccepted, apimodels.PostSilencesOKBody{
SilenceID: silenceID,
})
}
func (srv AlertmanagerSrv) RouteDeleteAlertingConfig(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
if err := am.SaveAndApplyDefaultConfig(c.Req.Context()); err != nil {
srv.log.Error("unable to save and apply default alertmanager configuration", "error", err)
return ErrResp(http.StatusInternalServerError, err, "failed to save and apply default Alertmanager configuration")
}
return response.JSON(http.StatusAccepted, util.DynMap{"message": "configuration deleted; the default is applied"})
}
func (srv AlertmanagerSrv) RouteDeleteSilence(c *contextmodel.ReqContext, silenceID string) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
if err := am.DeleteSilence(silenceID); err != nil {
if errors.Is(err, alertingNotify.ErrSilenceNotFound) {
return ErrResp(http.StatusNotFound, err, "")
}
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(http.StatusOK, util.DynMap{"message": "silence deleted"})
}
func (srv AlertmanagerSrv) RouteGetAlertingConfig(c *contextmodel.ReqContext) response.Response {
config, err := srv.mam.GetAlertmanagerConfiguration(c.Req.Context(), c.OrgID)
if err != nil {
if errors.Is(err, store.ErrNoAlertmanagerConfiguration) {
return ErrResp(http.StatusNotFound, err, "")
}
return ErrResp(http.StatusInternalServerError, err, err.Error())
}
return response.JSON(http.StatusOK, config)
}
func (srv AlertmanagerSrv) RouteGetAMAlertGroups(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
groups, err := am.GetAlertGroups(
c.QueryBoolWithDefault("active", true),
c.QueryBoolWithDefault("silenced", true),
c.QueryBoolWithDefault("inhibited", true),
c.QueryStrings("filter"),
c.Query("receiver"),
)
if err != nil {
if errors.Is(err, alertingNotify.ErrGetAlertGroupsBadPayload) {
return ErrResp(http.StatusBadRequest, err, "")
}
// any other error here should be an unexpected failure and thus an internal error
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(http.StatusOK, groups)
}
func (srv AlertmanagerSrv) RouteGetAMAlerts(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
alerts, err := am.GetAlerts(
c.QueryBoolWithDefault("active", true),
c.QueryBoolWithDefault("silenced", true),
c.QueryBoolWithDefault("inhibited", true),
c.QueryStrings("filter"),
c.Query("receiver"),
)
if err != nil {
if errors.Is(err, alertingNotify.ErrGetAlertsBadPayload) {
return ErrResp(http.StatusBadRequest, err, "")
}
if errors.Is(err, alertingNotify.ErrGetAlertsUnavailable) {
return ErrResp(http.StatusServiceUnavailable, err, "")
}
// any other error here should be an unexpected failure and thus an internal error
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(http.StatusOK, alerts)
}
func (srv AlertmanagerSrv) RouteGetSilence(c *contextmodel.ReqContext, silenceID string) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
gettableSilence, err := am.GetSilence(silenceID)
if err != nil {
if errors.Is(err, alertingNotify.ErrSilenceNotFound) {
return ErrResp(http.StatusNotFound, err, "")
}
// any other error here should be an unexpected failure and thus an internal error
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(http.StatusOK, gettableSilence)
}
func (srv AlertmanagerSrv) RouteGetSilences(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
gettableSilences, err := am.ListSilences(c.QueryStrings("filter"))
if err != nil {
if errors.Is(err, alertingNotify.ErrListSilencesBadPayload) {
return ErrResp(http.StatusBadRequest, err, "")
}
// any other error here should be an unexpected failure and thus an internal error
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(http.StatusOK, gettableSilences)
}
func (srv AlertmanagerSrv) RoutePostAlertingConfig(c *contextmodel.ReqContext, body apimodels.PostableUserConfig) response.Response {
currentConfig, err := srv.mam.GetAlertmanagerConfiguration(c.Req.Context(), c.OrgID)
// If a config is present and valid we proceed with the guard, otherwise we
// just bypass the guard which is okay as we are anyway in an invalid state.
if err == nil {
if err := srv.provenanceGuard(currentConfig, body); err != nil {
return ErrResp(http.StatusBadRequest, err, "")
}
}
err = srv.mam.ApplyAlertmanagerConfiguration(c.Req.Context(), c.OrgID, body)
if err == nil {
return response.JSON(http.StatusAccepted, util.DynMap{"message": "configuration created"})
}
var unknownReceiverError notifier.UnknownReceiverError
if errors.As(err, &unknownReceiverError) {
return ErrResp(http.StatusBadRequest, unknownReceiverError, "")
}
var configRejectedError notifier.AlertmanagerConfigRejectedError
if errors.As(err, &configRejectedError) {
return ErrResp(http.StatusBadRequest, configRejectedError, "")
}
if errors.Is(err, notifier.ErrNoAlertmanagerForOrg) {
return response.Error(http.StatusNotFound, err.Error(), err)
}
if errors.Is(err, notifier.ErrAlertmanagerNotReady) {
return response.Error(http.StatusConflict, err.Error(), err)
}
return ErrResp(http.StatusInternalServerError, err, "")
}
func (srv AlertmanagerSrv) RouteGetReceivers(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
rcvs := am.GetReceivers(c.Req.Context())
return response.JSON(http.StatusOK, rcvs)
}
func (srv AlertmanagerSrv) RoutePostTestReceivers(c *contextmodel.ReqContext, body apimodels.TestReceiversConfigBodyParams) response.Response {
if err := srv.crypto.LoadSecureSettings(c.Req.Context(), c.OrgID, body.Receivers); err != nil {
var unknownReceiverError UnknownReceiverError
if errors.As(err, &unknownReceiverError) {
return ErrResp(http.StatusBadRequest, err, "")
}
return ErrResp(http.StatusInternalServerError, err, "")
}
if err := body.ProcessConfig(srv.crypto.Encrypt); err != nil {
return ErrResp(http.StatusInternalServerError, err, "failed to post process Alertmanager configuration")
}
ctx, cancelFunc, err := contextWithTimeoutFromRequest(
c.Req.Context(),
c.Req,
defaultTestReceiversTimeout,
maxTestReceiversTimeout)
if err != nil {
return ErrResp(http.StatusBadRequest, err, "")
}
defer cancelFunc()
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
result, err := am.TestReceivers(ctx, body)
if err != nil {
if errors.Is(err, alertingNotify.ErrNoReceivers) {
return response.Error(http.StatusBadRequest, "", err)
}
return response.Error(http.StatusInternalServerError, "", err)
}
return response.JSON(statusForTestReceivers(result.Receivers), newTestReceiversResult(result))
}
// contextWithTimeoutFromRequest returns a context with a deadline set from the
// Request-Timeout header in the HTTP request. If the header is absent then the
// context will use the default timeout. The timeout in the Request-Timeout
// header cannot exceed the maximum timeout.
func contextWithTimeoutFromRequest(ctx context.Context, r *http.Request, defaultTimeout, maxTimeout time.Duration) (context.Context, context.CancelFunc, error) {
timeout := defaultTimeout
if s := strings.TrimSpace(r.Header.Get("Request-Timeout")); s != "" {
// the timeout is measured in seconds
v, err := strconv.ParseInt(s, 10, 16)
if err != nil {
return nil, nil, err
}
if d := time.Duration(v) * time.Second; d < maxTimeout {
timeout = d
} else {
return nil, nil, fmt.Errorf("exceeded maximum timeout of %d seconds", maxTimeout)
}
}
ctx, cancelFunc := context.WithTimeout(ctx, timeout)
return ctx, cancelFunc, nil
}
func newTestReceiversResult(r *notifier.TestReceiversResult) apimodels.TestReceiversResult {
v := apimodels.TestReceiversResult{
Alert: apimodels.TestReceiversConfigAlertParams{
Annotations: r.Alert.Annotations,
Labels: r.Alert.Labels,
},
Receivers: make([]apimodels.TestReceiverResult, len(r.Receivers)),
NotifiedAt: r.NotifedAt,
}
for ix, next := range r.Receivers {
configs := make([]apimodels.TestReceiverConfigResult, len(next.Configs))
for jx, config := range next.Configs {
configs[jx].Name = config.Name
configs[jx].UID = config.UID
configs[jx].Status = config.Status
if config.Error != nil {
configs[jx].Error = config.Error.Error()
}
}
v.Receivers[ix].Configs = configs
v.Receivers[ix].Name = next.Name
}
return v
}
// statusForTestReceivers returns the appropriate status code for the response
// for the results.
//
// It returns an HTTP 200 OK status code if notifications were sent to all receivers,
// an HTTP 400 Bad Request status code if all receivers contain invalid configuration,
// an HTTP 408 Request Timeout status code if all receivers timed out when sending
// a test notification or an HTTP 207 Multi Status.
func statusForTestReceivers(v []notifier.TestReceiverResult) int {
var (
numBadRequests int
numTimeouts int
numUnknownErrors int
)
for _, receiver := range v {
for _, next := range receiver.Configs {
if next.Error != nil {
var (
invalidReceiverErr notifier.InvalidReceiverError
receiverTimeoutErr alertingNotify.ReceiverTimeoutError
)
if errors.As(next.Error, &invalidReceiverErr) {
numBadRequests += 1
} else if errors.As(next.Error, &receiverTimeoutErr) {
numTimeouts += 1
} else {
numUnknownErrors += 1
}
}
}
}
if numBadRequests == len(v) {
// if all receivers contain invalid configuration
return http.StatusBadRequest
} else if numTimeouts == len(v) {
// if all receivers contain valid configuration but timed out
return http.StatusRequestTimeout
} else if numBadRequests+numTimeouts+numUnknownErrors > 0 {
return http.StatusMultiStatus
} else {
// all receivers were sent a notification without error
return http.StatusOK
}
}
func (srv AlertmanagerSrv) AlertmanagerFor(orgID int64) (Alertmanager, *response.NormalResponse) {
am, err := srv.mam.AlertmanagerFor(orgID)
if err == nil {
return am, nil
}
if errors.Is(err, notifier.ErrNoAlertmanagerForOrg) {
return nil, response.Error(http.StatusNotFound, err.Error(), err)
}
if errors.Is(err, notifier.ErrAlertmanagerNotReady) {
return am, response.Error(http.StatusConflict, err.Error(), err)
}
srv.log.Error("unable to obtain the org's Alertmanager", "error", err)
return nil, response.Error(http.StatusInternalServerError, "unable to obtain org's Alertmanager", err)
}
| pkg/services/ngalert/api/api_alertmanager.go | 1 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.9979168772697449,
0.0508807934820652,
0.00016544392565265298,
0.00020135137310717255,
0.2141840159893036
]
|
{
"id": 0,
"code_window": [
"\tcontextmodel \"github.com/grafana/grafana/pkg/services/contexthandler/model\"\n",
"\tapimodels \"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/notifier\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/store\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n",
")\n",
"\n",
"const (\n",
"\tdefaultTestReceiversTimeout = 15 * time.Second\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/services/secrets\"\n"
],
"file_path": "pkg/services/ngalert/api/api_alertmanager.go",
"type": "add",
"edit_start_line_idx": 21
} | import { ThunkResult } from 'app/types';
import { validateVariableSelectionState } from '../state/actions';
import { toKeyedAction } from '../state/keyedVariablesReducer';
import { KeyedVariableIdentifier } from '../state/types';
import { toVariablePayload } from '../utils';
import { createCustomOptionsFromQuery } from './reducer';
export const updateCustomVariableOptions = (identifier: KeyedVariableIdentifier): ThunkResult<void> => {
return async (dispatch) => {
const { rootStateKey } = identifier;
await dispatch(toKeyedAction(rootStateKey, createCustomOptionsFromQuery(toVariablePayload(identifier))));
await dispatch(validateVariableSelectionState(identifier));
};
};
| public/app/features/variables/custom/actions.ts | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.0001753672695485875,
0.00017289718380197883,
0.00017042708350345492,
0.00017289718380197883,
0.0000024700930225662887
]
|
{
"id": 0,
"code_window": [
"\tcontextmodel \"github.com/grafana/grafana/pkg/services/contexthandler/model\"\n",
"\tapimodels \"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/notifier\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/store\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n",
")\n",
"\n",
"const (\n",
"\tdefaultTestReceiversTimeout = 15 * time.Second\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/services/secrets\"\n"
],
"file_path": "pkg/services/ngalert/api/api_alertmanager.go",
"type": "add",
"edit_start_line_idx": 21
} | import { find, map, reduce, remove } from 'lodash';
import { DataQuery, DataSourceApi, rangeUtil } from '@grafana/data';
import { getBackendSrv } from '@grafana/runtime';
import coreModule from 'app/angular/core_module';
import { promiseToDigest } from 'app/angular/promiseToDigest';
import appEvents from 'app/core/app_events';
import config from 'app/core/config';
import { QueryPart } from 'app/features/alerting/state/query_part';
import { PanelModel } from 'app/features/dashboard/state';
import { CoreEvents } from 'app/types';
import { ShowConfirmModalEvent } from '../../types/events';
import { DashboardSrv } from '../dashboard/services/DashboardSrv';
import { DatasourceSrv } from '../plugins/datasource_srv';
import { getDefaultCondition } from './getAlertingValidationMessage';
import { ThresholdMapper } from './state/ThresholdMapper';
import alertDef from './state/alertDef';
export class AlertTabCtrl {
panel: PanelModel;
panelCtrl: any;
subTabIndex: number;
conditionTypes: any;
alert: any;
conditionModels: any;
evalFunctions: any;
evalOperators: any;
noDataModes: any;
executionErrorModes: any;
addNotificationSegment: any;
notifications: any;
alertNotifications: any;
error?: string;
appSubUrl: string;
alertHistory: any;
newAlertRuleTag: any;
alertingMinIntervalSecs: number;
alertingMinInterval: string;
frequencyWarning: any;
static $inject = ['$scope', 'dashboardSrv', 'uiSegmentSrv', 'datasourceSrv'];
constructor(
private $scope: any,
private dashboardSrv: DashboardSrv,
private uiSegmentSrv: any,
private datasourceSrv: DatasourceSrv
) {
this.panelCtrl = $scope.ctrl;
this.panel = this.panelCtrl.panel;
this.$scope.ctrl = this;
this.subTabIndex = 0;
this.evalFunctions = alertDef.evalFunctions;
this.evalOperators = alertDef.evalOperators;
this.conditionTypes = alertDef.conditionTypes;
this.noDataModes = alertDef.noDataModes;
this.executionErrorModes = alertDef.executionErrorModes;
this.appSubUrl = config.appSubUrl;
this.panelCtrl._enableAlert = this.enable;
this.alertingMinIntervalSecs = config.alertingMinInterval;
this.alertingMinInterval = rangeUtil.secondsToHms(config.alertingMinInterval);
}
$onInit() {
this.addNotificationSegment = this.uiSegmentSrv.newPlusButton();
// subscribe to graph threshold handle changes
const thresholdChangedEventHandler = this.graphThresholdChanged.bind(this);
this.panelCtrl.events.on(CoreEvents.thresholdChanged, thresholdChangedEventHandler);
// set panel alert edit mode
this.$scope.$on('$destroy', () => {
this.panelCtrl.events.off(CoreEvents.thresholdChanged, thresholdChangedEventHandler);
this.panelCtrl.editingThresholds = false;
this.panelCtrl.render();
});
// build notification model
this.notifications = [];
this.alertNotifications = [];
this.alertHistory = [];
return promiseToDigest(this.$scope)(
getBackendSrv()
.get('/api/alert-notifications/lookup')
.then((res: any) => {
this.notifications = res;
this.initModel();
this.validateModel();
})
);
}
getAlertHistory() {
promiseToDigest(this.$scope)(
getBackendSrv()
.get(`/api/annotations?dashboardId=${this.panelCtrl.dashboard.id}&panelId=${this.panel.id}&limit=50&type=alert`)
.then((res: any) => {
this.alertHistory = map(res, (ah) => {
ah.time = this.dashboardSrv.getCurrent()?.formatDate(ah.time, 'MMM D, YYYY HH:mm:ss');
ah.stateModel = alertDef.getStateDisplayModel(ah.newState);
ah.info = alertDef.getAlertAnnotationInfo(ah);
return ah;
});
})
);
}
getNotificationIcon(type: string): string {
switch (type) {
case 'email':
return 'envelope';
case 'slack':
return 'slack';
case 'victorops':
return 'fa fa-pagelines';
case 'webhook':
return 'cube';
case 'pagerduty':
return 'fa fa-bullhorn';
case 'opsgenie':
return 'bell';
case 'hipchat':
return 'fa fa-mail-forward';
case 'pushover':
return 'mobile-android';
case 'kafka':
return 'arrow-random';
case 'teams':
return 'fa fa-windows';
}
return 'bell';
}
getNotifications() {
return Promise.resolve(
this.notifications.map((item: any) => {
return this.uiSegmentSrv.newSegment(item.name);
})
);
}
notificationAdded() {
const model: any = find(this.notifications, {
name: this.addNotificationSegment.value,
});
if (!model) {
return;
}
this.alertNotifications.push({
name: model.name,
iconClass: this.getNotificationIcon(model.type),
isDefault: false,
uid: model.uid,
});
// avoid duplicates using both id and uid to be backwards compatible.
if (!find(this.alert.notifications, (n) => n.id === model.id || n.uid === model.uid)) {
this.alert.notifications.push({ uid: model.uid });
}
// reset plus button
this.addNotificationSegment.value = this.uiSegmentSrv.newPlusButton().value;
this.addNotificationSegment.html = this.uiSegmentSrv.newPlusButton().html;
this.addNotificationSegment.fake = true;
}
removeNotification(an: any) {
// remove notifiers referred to by id and uid to support notifiers added
// before and after we added support for uid
remove(this.alert.notifications, (n: any) => n.uid === an.uid || n.id === an.id);
remove(this.alertNotifications, (n: any) => n.uid === an.uid || n.id === an.id);
}
addAlertRuleTag() {
if (this.newAlertRuleTag.name) {
this.alert.alertRuleTags[this.newAlertRuleTag.name] = this.newAlertRuleTag.value;
}
this.newAlertRuleTag.name = '';
this.newAlertRuleTag.value = '';
}
removeAlertRuleTag(tagName: string) {
delete this.alert.alertRuleTags[tagName];
}
initModel() {
const alert = (this.alert = this.panel.alert);
if (!alert) {
return;
}
this.checkFrequency();
alert.conditions = alert.conditions || [];
if (alert.conditions.length === 0) {
alert.conditions.push(getDefaultCondition());
}
alert.noDataState = alert.noDataState || config.alertingNoDataOrNullValues;
alert.executionErrorState = alert.executionErrorState || config.alertingErrorOrTimeout;
alert.frequency = alert.frequency || '1m';
alert.handler = alert.handler || 1;
alert.notifications = alert.notifications || [];
alert.for = alert.for || '0m';
alert.alertRuleTags = alert.alertRuleTags || {};
const defaultName = this.panel.title + ' alert';
alert.name = alert.name || defaultName;
this.conditionModels = reduce(
alert.conditions,
(memo, value) => {
memo.push(this.buildConditionModel(value));
return memo;
},
[] as string[]
);
ThresholdMapper.alertToGraphThresholds(this.panel);
for (const addedNotification of alert.notifications) {
let identifier = addedNotification.uid;
// lookup notifier type by uid
let model: any = find(this.notifications, { uid: identifier });
// fallback using id if uid is missing
if (!model && addedNotification.id) {
identifier = addedNotification.id;
model = find(this.notifications, { id: identifier });
}
if (!model) {
appEvents.publish(
new ShowConfirmModalEvent({
title: 'Notifier with invalid identifier is detected',
text: `Do you want to delete notifier with invalid identifier: ${identifier} from the dashboard JSON?`,
text2: 'After successful deletion, make sure to save the dashboard for storing the update JSON.',
icon: 'trash-alt',
confirmText: 'Delete',
yesText: 'Delete',
onConfirm: async () => {
this.removeNotification(addedNotification);
},
})
);
}
if (model && model.isDefault === false) {
model.iconClass = this.getNotificationIcon(model.type);
this.alertNotifications.push(model);
}
}
for (const notification of this.notifications) {
if (notification.isDefault) {
notification.iconClass = this.getNotificationIcon(notification.type);
this.alertNotifications.push(notification);
}
}
this.panelCtrl.editingThresholds = true;
this.panelCtrl.render();
}
checkFrequency() {
this.frequencyWarning = '';
if (!this.alert.frequency) {
return;
}
if (!this.alert.frequency.match(/^\d+([dhms])$/)) {
this.frequencyWarning =
'Invalid frequency, has to be numeric followed by one of the following units: "d, h, m, s"';
return;
}
try {
const frequencySecs = rangeUtil.intervalToSeconds(this.alert.frequency);
if (frequencySecs < this.alertingMinIntervalSecs) {
this.frequencyWarning =
'A minimum evaluation interval of ' +
this.alertingMinInterval +
' have been configured in Grafana and will be used for this alert rule. ' +
'Please contact the administrator to configure a lower interval.';
}
} catch (err) {
this.frequencyWarning = err;
}
}
graphThresholdChanged(evt: any) {
for (const condition of this.alert.conditions) {
if (condition.type === 'query') {
condition.evaluator.params[evt.handleIndex] = evt.threshold.value;
this.evaluatorParamsChanged();
break;
}
}
}
validateModel() {
if (!this.alert) {
return;
}
let firstTarget;
let foundTarget: DataQuery | null = null;
const promises: Array<Promise<any>> = [];
for (const condition of this.alert.conditions) {
if (condition.type !== 'query') {
continue;
}
for (const target of this.panel.targets) {
if (!firstTarget) {
firstTarget = target;
}
if (condition.query.params[0] === target.refId) {
foundTarget = target;
break;
}
}
if (!foundTarget) {
if (firstTarget) {
condition.query.params[0] = firstTarget.refId;
foundTarget = firstTarget;
} else {
this.error = 'Could not find any metric queries';
return;
}
}
const datasourceName = foundTarget.datasource || this.panel.datasource;
promises.push(
this.datasourceSrv.get(datasourceName).then(
((foundTarget) => (ds: DataSourceApi) => {
if (!ds.meta.alerting) {
return Promise.reject('The datasource does not support alerting queries');
} else if (ds.targetContainsTemplate && ds.targetContainsTemplate(foundTarget)) {
return Promise.reject('Template variables are not supported in alert queries');
}
return Promise.resolve();
})(foundTarget)
)
);
}
Promise.all(promises).then(
() => {
this.error = '';
this.$scope.$apply();
},
(e) => {
this.error = e;
this.$scope.$apply();
}
);
}
buildConditionModel(source: any) {
const cm: any = { source: source, type: source.type };
cm.queryPart = new QueryPart(source.query, alertDef.alertQueryDef);
cm.reducerPart = alertDef.createReducerPart(source.reducer);
cm.evaluator = source.evaluator;
cm.operator = source.operator;
return cm;
}
handleQueryPartEvent(conditionModel: any, evt: any) {
switch (evt.name) {
case 'action-remove-part': {
break;
}
case 'get-part-actions': {
return Promise.resolve([]);
}
case 'part-param-changed': {
this.validateModel();
}
case 'get-param-options': {
const result = this.panel.targets.map((target) => {
return this.uiSegmentSrv.newSegment({ value: target.refId });
});
return Promise.resolve(result);
}
default: {
return Promise.resolve();
}
}
return Promise.resolve();
}
handleReducerPartEvent(conditionModel: any, evt: any) {
switch (evt.name) {
case 'action': {
conditionModel.source.reducer.type = evt.action.value;
conditionModel.reducerPart = alertDef.createReducerPart(conditionModel.source.reducer);
this.evaluatorParamsChanged();
break;
}
case 'get-part-actions': {
const result = [];
for (const type of alertDef.reducerTypes) {
if (type.value !== conditionModel.source.reducer.type) {
result.push(type);
}
}
return Promise.resolve(result);
}
}
return Promise.resolve();
}
addCondition(type: string) {
const condition = getDefaultCondition();
// add to persited model
this.alert.conditions.push(condition);
// add to view model
this.conditionModels.push(this.buildConditionModel(condition));
}
removeCondition(index: number) {
this.alert.conditions.splice(index, 1);
this.conditionModels.splice(index, 1);
}
delete() {
appEvents.publish(
new ShowConfirmModalEvent({
title: 'Delete Alert',
text: 'Are you sure you want to delete this alert rule?',
text2: 'You need to save dashboard for the delete to take effect',
icon: 'trash-alt',
yesText: 'Delete',
onConfirm: () => {
delete this.panel.alert;
this.alert = null;
this.panel.thresholds = [];
this.conditionModels = [];
this.panelCtrl.alertState = null;
this.panelCtrl.render();
},
})
);
}
enable = () => {
this.panel.alert = {};
this.initModel();
this.panel.alert.for = '5m'; //default value for new alerts. for existing alerts we use 0m to avoid breaking changes
};
evaluatorParamsChanged() {
ThresholdMapper.alertToGraphThresholds(this.panel);
this.panelCtrl.render();
}
evaluatorTypeChanged(evaluator: any) {
// ensure params array is correct length
switch (evaluator.type) {
case 'lt':
case 'gt': {
evaluator.params = [evaluator.params[0]];
break;
}
case 'within_range':
case 'outside_range': {
evaluator.params = [evaluator.params[0], evaluator.params[1]];
break;
}
case 'no_value': {
evaluator.params = [];
}
}
this.evaluatorParamsChanged();
}
clearHistory() {
appEvents.publish(
new ShowConfirmModalEvent({
title: 'Delete Alert History',
text: 'Are you sure you want to remove all history & annotations for this alert?',
icon: 'trash-alt',
yesText: 'Yes',
onConfirm: () => {
promiseToDigest(this.$scope)(
getBackendSrv()
.post('/api/annotations/mass-delete', {
dashboardId: this.panelCtrl.dashboard.id,
panelId: this.panel.id,
})
.then(() => {
this.alertHistory = [];
this.panelCtrl.refresh();
})
);
},
})
);
}
}
export function alertTab() {
'use strict';
return {
restrict: 'E',
scope: true,
templateUrl: 'public/app/features/alerting/partials/alert_tab.html',
controller: AlertTabCtrl,
};
}
coreModule.directive('alertTab', alertTab);
| public/app/features/alerting/AlertTabCtrl.ts | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.00038097306969575584,
0.00018205221567768604,
0.00016290717758238316,
0.0001701064466033131,
0.00003909693259629421
]
|
{
"id": 0,
"code_window": [
"\tcontextmodel \"github.com/grafana/grafana/pkg/services/contexthandler/model\"\n",
"\tapimodels \"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/notifier\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/store\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n",
")\n",
"\n",
"const (\n",
"\tdefaultTestReceiversTimeout = 15 * time.Second\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/services/secrets\"\n"
],
"file_path": "pkg/services/ngalert/api/api_alertmanager.go",
"type": "add",
"edit_start_line_idx": 21
} | package tests
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/services/live/model"
)
func TestIntegrationLiveMessage(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
storage := SetupTestStorage(t)
getQuery := &model.GetLiveMessageQuery{
OrgID: 1,
Channel: "test_channel",
}
_, ok, err := storage.GetLiveMessage(getQuery)
require.NoError(t, err)
require.False(t, ok)
saveQuery := &model.SaveLiveMessageQuery{
OrgID: 1,
Channel: "test_channel",
Data: []byte(`{}`),
}
err = storage.SaveLiveMessage(saveQuery)
require.NoError(t, err)
msg, ok, err := storage.GetLiveMessage(getQuery)
require.NoError(t, err)
require.True(t, ok)
require.Equal(t, int64(1), msg.OrgID)
require.Equal(t, "test_channel", msg.Channel)
require.Equal(t, json.RawMessage(`{}`), msg.Data)
require.NotZero(t, msg.Published)
// try saving again, should be replaced.
saveQuery2 := &model.SaveLiveMessageQuery{
OrgID: 1,
Channel: "test_channel",
Data: []byte(`{"input": "hello"}`),
}
err = storage.SaveLiveMessage(saveQuery2)
require.NoError(t, err)
getQuery2 := &model.GetLiveMessageQuery{
OrgID: 1,
Channel: "test_channel",
}
msg2, ok, err := storage.GetLiveMessage(getQuery2)
require.NoError(t, err)
require.True(t, ok)
require.Equal(t, int64(1), msg2.OrgID)
require.Equal(t, "test_channel", msg2.Channel)
require.Equal(t, json.RawMessage(`{"input": "hello"}`), msg2.Data)
require.NotZero(t, msg2.Published)
}
| pkg/services/live/database/tests/storage_test.go | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.0005605066544376314,
0.00022765285393688828,
0.0001622593408683315,
0.0001699303975328803,
0.00013639575627166778
]
|
{
"id": 1,
"code_window": [
"\t\treturn ErrResp(http.StatusInternalServerError, err, \"\")\n",
"\t}\n",
"\n",
"\tif err := body.ProcessConfig(srv.crypto.Encrypt); err != nil {\n",
"\t\treturn ErrResp(http.StatusInternalServerError, err, \"failed to post process Alertmanager configuration\")\n",
"\t}\n",
"\n",
"\tctx, cancelFunc, err := contextWithTimeoutFromRequest(\n",
"\t\tc.Req.Context(),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif err := body.ProcessConfig(func(ctx context.Context, payload []byte) ([]byte, error) {\n",
"\t\treturn srv.crypto.Encrypt(ctx, payload, secrets.WithoutScope())\n",
"\t}); err != nil {\n"
],
"file_path": "pkg/services/ngalert/api/api_alertmanager.go",
"type": "replace",
"edit_start_line_idx": 269
} | package notifier
import (
"context"
"errors"
"fmt"
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/store"
)
type UnknownReceiverError struct {
UID string
}
func (e UnknownReceiverError) Error() string {
return fmt.Sprintf("unknown receiver: %s", e.UID)
}
type AlertmanagerConfigRejectedError struct {
Inner error
}
func (e AlertmanagerConfigRejectedError) Error() string {
return fmt.Sprintf("failed to save and apply Alertmanager configuration: %s", e.Inner.Error())
}
type configurationStore interface {
GetLatestAlertmanagerConfiguration(ctx context.Context, query *models.GetLatestAlertmanagerConfigurationQuery) error
}
func (moa *MultiOrgAlertmanager) GetAlertmanagerConfiguration(ctx context.Context, org int64) (definitions.GettableUserConfig, error) {
query := models.GetLatestAlertmanagerConfigurationQuery{OrgID: org}
err := moa.configStore.GetLatestAlertmanagerConfiguration(ctx, &query)
if err != nil {
return definitions.GettableUserConfig{}, fmt.Errorf("failed to get latest configuration: %w", err)
}
cfg, err := Load([]byte(query.Result.AlertmanagerConfiguration))
if err != nil {
return definitions.GettableUserConfig{}, fmt.Errorf("failed to unmarshal alertmanager configuration: %w", err)
}
result := definitions.GettableUserConfig{
TemplateFiles: cfg.TemplateFiles,
AlertmanagerConfig: definitions.GettableApiAlertingConfig{
Config: cfg.AlertmanagerConfig.Config,
},
}
for _, recv := range cfg.AlertmanagerConfig.Receivers {
receivers := make([]*definitions.GettableGrafanaReceiver, 0, len(recv.PostableGrafanaReceivers.GrafanaManagedReceivers))
for _, pr := range recv.PostableGrafanaReceivers.GrafanaManagedReceivers {
secureFields := make(map[string]bool, len(pr.SecureSettings))
for k := range pr.SecureSettings {
decryptedValue, err := moa.Crypto.getDecryptedSecret(pr, k)
if err != nil {
return definitions.GettableUserConfig{}, fmt.Errorf("failed to decrypt stored secure setting: %w", err)
}
if decryptedValue == "" {
continue
}
secureFields[k] = true
}
gr := definitions.GettableGrafanaReceiver{
UID: pr.UID,
Name: pr.Name,
Type: pr.Type,
DisableResolveMessage: pr.DisableResolveMessage,
Settings: pr.Settings,
SecureFields: secureFields,
}
receivers = append(receivers, &gr)
}
gettableApiReceiver := definitions.GettableApiReceiver{
GettableGrafanaReceivers: definitions.GettableGrafanaReceivers{
GrafanaManagedReceivers: receivers,
},
}
gettableApiReceiver.Name = recv.Name
result.AlertmanagerConfig.Receivers = append(result.AlertmanagerConfig.Receivers, &gettableApiReceiver)
}
result, err = moa.mergeProvenance(ctx, result, org)
if err != nil {
return definitions.GettableUserConfig{}, err
}
return result, nil
}
func (moa *MultiOrgAlertmanager) ApplyAlertmanagerConfiguration(ctx context.Context, org int64, config definitions.PostableUserConfig) error {
// Get the last known working configuration
query := models.GetLatestAlertmanagerConfigurationQuery{OrgID: org}
if err := moa.configStore.GetLatestAlertmanagerConfiguration(ctx, &query); err != nil {
// If we don't have a configuration there's nothing for us to know and we should just continue saving the new one
if !errors.Is(err, store.ErrNoAlertmanagerConfiguration) {
return fmt.Errorf("failed to get latest configuration %w", err)
}
}
if err := moa.Crypto.LoadSecureSettings(ctx, org, config.AlertmanagerConfig.Receivers); err != nil {
return err
}
if err := config.ProcessConfig(moa.Crypto.Encrypt); err != nil {
return fmt.Errorf("failed to post process Alertmanager configuration: %w", err)
}
am, err := moa.AlertmanagerFor(org)
if err != nil {
// It's okay if the alertmanager isn't ready yet, we're changing its config anyway.
if !errors.Is(err, ErrAlertmanagerNotReady) {
return err
}
}
if err := am.SaveAndApplyConfig(ctx, &config); err != nil {
moa.logger.Error("unable to save and apply alertmanager configuration", "error", err)
return AlertmanagerConfigRejectedError{err}
}
return nil
}
func (moa *MultiOrgAlertmanager) mergeProvenance(ctx context.Context, config definitions.GettableUserConfig, org int64) (definitions.GettableUserConfig, error) {
if config.AlertmanagerConfig.Route != nil {
provenance, err := moa.ProvStore.GetProvenance(ctx, config.AlertmanagerConfig.Route, org)
if err != nil {
return definitions.GettableUserConfig{}, err
}
config.AlertmanagerConfig.Route.Provenance = definitions.Provenance(provenance)
}
cp := definitions.EmbeddedContactPoint{}
cpProvs, err := moa.ProvStore.GetProvenances(ctx, org, cp.ResourceType())
if err != nil {
return definitions.GettableUserConfig{}, err
}
for _, receiver := range config.AlertmanagerConfig.Receivers {
for _, contactPoint := range receiver.GrafanaManagedReceivers {
if provenance, exists := cpProvs[contactPoint.UID]; exists {
contactPoint.Provenance = definitions.Provenance(provenance)
}
}
}
tmpl := definitions.NotificationTemplate{}
tmplProvs, err := moa.ProvStore.GetProvenances(ctx, org, tmpl.ResourceType())
if err != nil {
return definitions.GettableUserConfig{}, nil
}
config.TemplateFileProvenances = make(map[string]definitions.Provenance, len(tmplProvs))
for key, provenance := range tmplProvs {
config.TemplateFileProvenances[key] = definitions.Provenance(provenance)
}
mt := definitions.MuteTimeInterval{}
mtProvs, err := moa.ProvStore.GetProvenances(ctx, org, mt.ResourceType())
if err != nil {
return definitions.GettableUserConfig{}, nil
}
config.AlertmanagerConfig.MuteTimeProvenances = make(map[string]definitions.Provenance, len(mtProvs))
for key, provenance := range mtProvs {
config.AlertmanagerConfig.MuteTimeProvenances[key] = definitions.Provenance(provenance)
}
return config, nil
}
| pkg/services/ngalert/notifier/alertmanager_config.go | 1 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.9923214316368103,
0.16321596503257751,
0.000165942867170088,
0.0026986212469637394,
0.3308033049106598
]
|
{
"id": 1,
"code_window": [
"\t\treturn ErrResp(http.StatusInternalServerError, err, \"\")\n",
"\t}\n",
"\n",
"\tif err := body.ProcessConfig(srv.crypto.Encrypt); err != nil {\n",
"\t\treturn ErrResp(http.StatusInternalServerError, err, \"failed to post process Alertmanager configuration\")\n",
"\t}\n",
"\n",
"\tctx, cancelFunc, err := contextWithTimeoutFromRequest(\n",
"\t\tc.Req.Context(),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif err := body.ProcessConfig(func(ctx context.Context, payload []byte) ([]byte, error) {\n",
"\t\treturn srv.crypto.Encrypt(ctx, payload, secrets.WithoutScope())\n",
"\t}); err != nil {\n"
],
"file_path": "pkg/services/ngalert/api/api_alertmanager.go",
"type": "replace",
"edit_start_line_idx": 269
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19,13a1,1,0,0,0-1,1v.38L16.52,12.9a2.79,2.79,0,0,0-3.93,0l-.7.7L9.41,11.12a2.85,2.85,0,0,0-3.93,0L4,12.6V7A1,1,0,0,1,5,6h7a1,1,0,0,0,0-2H5A3,3,0,0,0,2,7V19a3,3,0,0,0,3,3H17a3,3,0,0,0,3-3V14A1,1,0,0,0,19,13ZM5,20a1,1,0,0,1-1-1V15.43l2.9-2.9a.79.79,0,0,1,1.09,0l3.17,3.17,0,0L15.46,20Zm13-1a.89.89,0,0,1-.18.53L13.31,15l.7-.7a.77.77,0,0,1,1.1,0L18,17.21ZM22.71,4.29l-3-3a1,1,0,0,0-.33-.21,1,1,0,0,0-.76,0,1,1,0,0,0-.33.21l-3,3a1,1,0,0,0,1.42,1.42L18,4.41V10a1,1,0,0,0,2,0V4.41l1.29,1.3a1,1,0,0,0,1.42,0A1,1,0,0,0,22.71,4.29Z"/></svg> | public/img/icons/unicons/image-upload.svg | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.00016421472537331283,
0.00016421472537331283,
0.00016421472537331283,
0.00016421472537331283,
0
]
|
{
"id": 1,
"code_window": [
"\t\treturn ErrResp(http.StatusInternalServerError, err, \"\")\n",
"\t}\n",
"\n",
"\tif err := body.ProcessConfig(srv.crypto.Encrypt); err != nil {\n",
"\t\treturn ErrResp(http.StatusInternalServerError, err, \"failed to post process Alertmanager configuration\")\n",
"\t}\n",
"\n",
"\tctx, cancelFunc, err := contextWithTimeoutFromRequest(\n",
"\t\tc.Req.Context(),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif err := body.ProcessConfig(func(ctx context.Context, payload []byte) ([]byte, error) {\n",
"\t\treturn srv.crypto.Encrypt(ctx, payload, secrets.WithoutScope())\n",
"\t}); err != nil {\n"
],
"file_path": "pkg/services/ngalert/api/api_alertmanager.go",
"type": "replace",
"edit_start_line_idx": 269
} | import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { noop } from 'lodash';
import React from 'react';
import { SecondaryActions } from './SecondaryActions';
describe('SecondaryActions', () => {
it('should render component with three buttons', () => {
render(
<SecondaryActions
onClickAddQueryRowButton={noop}
onClickRichHistoryButton={noop}
onClickQueryInspectorButton={noop}
/>
);
expect(screen.getByRole('button', { name: /Add row button/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Rich history button/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Query inspector button/i })).toBeInTheDocument();
});
it('should not render hidden elements', () => {
render(
<SecondaryActions
addQueryRowButtonHidden={true}
richHistoryRowButtonHidden={true}
onClickAddQueryRowButton={noop}
onClickRichHistoryButton={noop}
onClickQueryInspectorButton={noop}
/>
);
expect(screen.queryByRole('button', { name: /Add row button/i })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /Rich history button/i })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: /Query inspector button/i })).toBeInTheDocument();
});
it('should disable add row button if addQueryRowButtonDisabled=true', () => {
render(
<SecondaryActions
addQueryRowButtonDisabled={true}
onClickAddQueryRowButton={noop}
onClickRichHistoryButton={noop}
onClickQueryInspectorButton={noop}
/>
);
expect(screen.getByRole('button', { name: /Add row button/i })).toBeDisabled();
expect(screen.getByRole('button', { name: /Rich history button/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Query inspector button/i })).toBeInTheDocument();
});
it('should map click handlers correctly', async () => {
const user = userEvent.setup();
const onClickAddRow = jest.fn();
const onClickHistory = jest.fn();
const onClickQueryInspector = jest.fn();
render(
<SecondaryActions
onClickAddQueryRowButton={onClickAddRow}
onClickRichHistoryButton={onClickHistory}
onClickQueryInspectorButton={onClickQueryInspector}
/>
);
await user.click(screen.getByRole('button', { name: /Add row button/i }));
expect(onClickAddRow).toBeCalledTimes(1);
await user.click(screen.getByRole('button', { name: /Rich history button/i }));
expect(onClickHistory).toBeCalledTimes(1);
await user.click(screen.getByRole('button', { name: /Query inspector button/i }));
expect(onClickQueryInspector).toBeCalledTimes(1);
});
});
| public/app/features/explore/SecondaryActions.test.tsx | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.00017749734979588538,
0.0001749861694406718,
0.00017120873962994665,
0.00017494757776148617,
0.0000018726527741819154
]
|
{
"id": 1,
"code_window": [
"\t\treturn ErrResp(http.StatusInternalServerError, err, \"\")\n",
"\t}\n",
"\n",
"\tif err := body.ProcessConfig(srv.crypto.Encrypt); err != nil {\n",
"\t\treturn ErrResp(http.StatusInternalServerError, err, \"failed to post process Alertmanager configuration\")\n",
"\t}\n",
"\n",
"\tctx, cancelFunc, err := contextWithTimeoutFromRequest(\n",
"\t\tc.Req.Context(),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif err := body.ProcessConfig(func(ctx context.Context, payload []byte) ([]byte, error) {\n",
"\t\treturn srv.crypto.Encrypt(ctx, payload, secrets.WithoutScope())\n",
"\t}); err != nil {\n"
],
"file_path": "pkg/services/ngalert/api/api_alertmanager.go",
"type": "replace",
"edit_start_line_idx": 269
} | import fs, { BigIntStats } from 'fs';
import { findModuleFiles, loadWebpackConfig } from './webpack.plugin.config';
// eslint-disable-next-line no-duplicate-imports
import * as webpackConfig from './webpack.plugin.config';
jest.mock('./webpack/loaders', () => ({
getFileLoaders: (): Array<{}> => [],
getStylesheetEntries: () => ({}),
getStyleLoaders: (): Array<{}> => [],
}));
const modulePathsMock = [
'some/path/module.ts',
'some/path/module.ts.whatever',
'some/path/module.tsx',
'some/path/module.tsx.whatever',
'some/path/anotherFile.ts',
'some/path/anotherFile.tsx',
];
describe('Plugin webpack config', () => {
describe('findModuleTs', () => {
beforeAll(() => {
jest.spyOn(fs, 'statSync').mockReturnValue({
isDirectory: () => false,
} as BigIntStats);
});
afterAll(() => {
jest.restoreAllMocks();
});
it('finds module.ts and module.tsx files', async () => {
const moduleFiles = await findModuleFiles('/', modulePathsMock);
expect(moduleFiles.length).toBe(2);
// normalize windows path - \\ -> /
expect(moduleFiles.map((p) => p.replace(/\\/g, '/'))).toEqual(['/some/path/module.ts', '/some/path/module.tsx']);
});
});
describe('loadWebpackConfig', () => {
beforeAll(() => {
jest.spyOn(webpackConfig, 'findModuleFiles').mockReturnValue(new Promise((res, _) => res([])));
});
afterAll(() => {
jest.restoreAllMocks();
});
it('uses default config if no override exists', async () => {
const spy = jest.spyOn(process, 'cwd');
spy.mockReturnValue(`${__dirname}/mocks/webpack/noOverride/`);
await loadWebpackConfig({});
});
it('calls customConfig if it exists', async () => {
const spy = jest.spyOn(process, 'cwd');
spy.mockReturnValue(`${__dirname}/mocks/webpack/overrides/`);
const config = await loadWebpackConfig({});
expect(config.name).toBe('customConfig');
});
it('loads export named getWebpackConfiguration', async () => {
const spy = jest.spyOn(process, 'cwd');
spy.mockReturnValue(`${__dirname}/mocks/webpack/overridesNamedExport/`);
const config = await loadWebpackConfig({});
expect(config.name).toBe('customConfig');
});
it('throws an error if module does not export function', async () => {
const spy = jest.spyOn(process, 'cwd');
spy.mockReturnValue(`${__dirname}/mocks/webpack/unsupportedOverride/`);
await expect(loadWebpackConfig({})).rejects.toThrowError();
});
});
});
| packages/grafana-toolkit/src/config/webpack.plugin.config.test.ts | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.0001774964912328869,
0.00017373589798808098,
0.00017125348676927388,
0.00017335140728391707,
0.0000021534092411457095
]
|
{
"id": 2,
"code_window": [
"\t\"github.com/prometheus/common/model\"\n",
"\t\"gopkg.in/yaml.v3\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/services/secrets\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n",
")\n",
"\n",
"// swagger:route POST /api/alertmanager/grafana/config/api/v1/alerts alertmanager RoutePostGrafanaAlertingConfig\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/api/tooling/definitions/alertmanager.go",
"type": "replace",
"edit_start_line_idx": 19
} | package api
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/go-openapi/strfmt"
alertingNotify "github.com/grafana/alerting/notify"
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/notifier"
"github.com/grafana/grafana/pkg/services/ngalert/store"
"github.com/grafana/grafana/pkg/util"
)
const (
defaultTestReceiversTimeout = 15 * time.Second
maxTestReceiversTimeout = 30 * time.Second
)
type AlertmanagerSrv struct {
log log.Logger
ac accesscontrol.AccessControl
mam *notifier.MultiOrgAlertmanager
crypto notifier.Crypto
}
type UnknownReceiverError struct {
UID string
}
func (e UnknownReceiverError) Error() string {
return fmt.Sprintf("unknown receiver: %s", e.UID)
}
func (srv AlertmanagerSrv) RouteGetAMStatus(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
return response.JSON(http.StatusOK, am.GetStatus())
}
func (srv AlertmanagerSrv) RouteCreateSilence(c *contextmodel.ReqContext, postableSilence apimodels.PostableSilence) response.Response {
err := postableSilence.Validate(strfmt.Default)
if err != nil {
srv.log.Error("silence failed validation", "error", err)
return ErrResp(http.StatusBadRequest, err, "silence failed validation")
}
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
action := accesscontrol.ActionAlertingInstanceUpdate
if postableSilence.ID == "" {
action = accesscontrol.ActionAlertingInstanceCreate
}
if !accesscontrol.HasAccess(srv.ac, c)(accesscontrol.ReqOrgAdminOrEditor, accesscontrol.EvalPermission(action)) {
errAction := "update"
if postableSilence.ID == "" {
errAction = "create"
}
return ErrResp(http.StatusUnauthorized, fmt.Errorf("user is not authorized to %s silences", errAction), "")
}
silenceID, err := am.CreateSilence(&postableSilence)
if err != nil {
if errors.Is(err, alertingNotify.ErrSilenceNotFound) {
return ErrResp(http.StatusNotFound, err, "")
}
if errors.Is(err, alertingNotify.ErrCreateSilenceBadPayload) {
return ErrResp(http.StatusBadRequest, err, "")
}
return ErrResp(http.StatusInternalServerError, err, "failed to create silence")
}
return response.JSON(http.StatusAccepted, apimodels.PostSilencesOKBody{
SilenceID: silenceID,
})
}
func (srv AlertmanagerSrv) RouteDeleteAlertingConfig(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
if err := am.SaveAndApplyDefaultConfig(c.Req.Context()); err != nil {
srv.log.Error("unable to save and apply default alertmanager configuration", "error", err)
return ErrResp(http.StatusInternalServerError, err, "failed to save and apply default Alertmanager configuration")
}
return response.JSON(http.StatusAccepted, util.DynMap{"message": "configuration deleted; the default is applied"})
}
func (srv AlertmanagerSrv) RouteDeleteSilence(c *contextmodel.ReqContext, silenceID string) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
if err := am.DeleteSilence(silenceID); err != nil {
if errors.Is(err, alertingNotify.ErrSilenceNotFound) {
return ErrResp(http.StatusNotFound, err, "")
}
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(http.StatusOK, util.DynMap{"message": "silence deleted"})
}
func (srv AlertmanagerSrv) RouteGetAlertingConfig(c *contextmodel.ReqContext) response.Response {
config, err := srv.mam.GetAlertmanagerConfiguration(c.Req.Context(), c.OrgID)
if err != nil {
if errors.Is(err, store.ErrNoAlertmanagerConfiguration) {
return ErrResp(http.StatusNotFound, err, "")
}
return ErrResp(http.StatusInternalServerError, err, err.Error())
}
return response.JSON(http.StatusOK, config)
}
func (srv AlertmanagerSrv) RouteGetAMAlertGroups(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
groups, err := am.GetAlertGroups(
c.QueryBoolWithDefault("active", true),
c.QueryBoolWithDefault("silenced", true),
c.QueryBoolWithDefault("inhibited", true),
c.QueryStrings("filter"),
c.Query("receiver"),
)
if err != nil {
if errors.Is(err, alertingNotify.ErrGetAlertGroupsBadPayload) {
return ErrResp(http.StatusBadRequest, err, "")
}
// any other error here should be an unexpected failure and thus an internal error
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(http.StatusOK, groups)
}
func (srv AlertmanagerSrv) RouteGetAMAlerts(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
alerts, err := am.GetAlerts(
c.QueryBoolWithDefault("active", true),
c.QueryBoolWithDefault("silenced", true),
c.QueryBoolWithDefault("inhibited", true),
c.QueryStrings("filter"),
c.Query("receiver"),
)
if err != nil {
if errors.Is(err, alertingNotify.ErrGetAlertsBadPayload) {
return ErrResp(http.StatusBadRequest, err, "")
}
if errors.Is(err, alertingNotify.ErrGetAlertsUnavailable) {
return ErrResp(http.StatusServiceUnavailable, err, "")
}
// any other error here should be an unexpected failure and thus an internal error
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(http.StatusOK, alerts)
}
func (srv AlertmanagerSrv) RouteGetSilence(c *contextmodel.ReqContext, silenceID string) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
gettableSilence, err := am.GetSilence(silenceID)
if err != nil {
if errors.Is(err, alertingNotify.ErrSilenceNotFound) {
return ErrResp(http.StatusNotFound, err, "")
}
// any other error here should be an unexpected failure and thus an internal error
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(http.StatusOK, gettableSilence)
}
func (srv AlertmanagerSrv) RouteGetSilences(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
gettableSilences, err := am.ListSilences(c.QueryStrings("filter"))
if err != nil {
if errors.Is(err, alertingNotify.ErrListSilencesBadPayload) {
return ErrResp(http.StatusBadRequest, err, "")
}
// any other error here should be an unexpected failure and thus an internal error
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(http.StatusOK, gettableSilences)
}
func (srv AlertmanagerSrv) RoutePostAlertingConfig(c *contextmodel.ReqContext, body apimodels.PostableUserConfig) response.Response {
currentConfig, err := srv.mam.GetAlertmanagerConfiguration(c.Req.Context(), c.OrgID)
// If a config is present and valid we proceed with the guard, otherwise we
// just bypass the guard which is okay as we are anyway in an invalid state.
if err == nil {
if err := srv.provenanceGuard(currentConfig, body); err != nil {
return ErrResp(http.StatusBadRequest, err, "")
}
}
err = srv.mam.ApplyAlertmanagerConfiguration(c.Req.Context(), c.OrgID, body)
if err == nil {
return response.JSON(http.StatusAccepted, util.DynMap{"message": "configuration created"})
}
var unknownReceiverError notifier.UnknownReceiverError
if errors.As(err, &unknownReceiverError) {
return ErrResp(http.StatusBadRequest, unknownReceiverError, "")
}
var configRejectedError notifier.AlertmanagerConfigRejectedError
if errors.As(err, &configRejectedError) {
return ErrResp(http.StatusBadRequest, configRejectedError, "")
}
if errors.Is(err, notifier.ErrNoAlertmanagerForOrg) {
return response.Error(http.StatusNotFound, err.Error(), err)
}
if errors.Is(err, notifier.ErrAlertmanagerNotReady) {
return response.Error(http.StatusConflict, err.Error(), err)
}
return ErrResp(http.StatusInternalServerError, err, "")
}
func (srv AlertmanagerSrv) RouteGetReceivers(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
rcvs := am.GetReceivers(c.Req.Context())
return response.JSON(http.StatusOK, rcvs)
}
func (srv AlertmanagerSrv) RoutePostTestReceivers(c *contextmodel.ReqContext, body apimodels.TestReceiversConfigBodyParams) response.Response {
if err := srv.crypto.LoadSecureSettings(c.Req.Context(), c.OrgID, body.Receivers); err != nil {
var unknownReceiverError UnknownReceiverError
if errors.As(err, &unknownReceiverError) {
return ErrResp(http.StatusBadRequest, err, "")
}
return ErrResp(http.StatusInternalServerError, err, "")
}
if err := body.ProcessConfig(srv.crypto.Encrypt); err != nil {
return ErrResp(http.StatusInternalServerError, err, "failed to post process Alertmanager configuration")
}
ctx, cancelFunc, err := contextWithTimeoutFromRequest(
c.Req.Context(),
c.Req,
defaultTestReceiversTimeout,
maxTestReceiversTimeout)
if err != nil {
return ErrResp(http.StatusBadRequest, err, "")
}
defer cancelFunc()
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
result, err := am.TestReceivers(ctx, body)
if err != nil {
if errors.Is(err, alertingNotify.ErrNoReceivers) {
return response.Error(http.StatusBadRequest, "", err)
}
return response.Error(http.StatusInternalServerError, "", err)
}
return response.JSON(statusForTestReceivers(result.Receivers), newTestReceiversResult(result))
}
// contextWithTimeoutFromRequest returns a context with a deadline set from the
// Request-Timeout header in the HTTP request. If the header is absent then the
// context will use the default timeout. The timeout in the Request-Timeout
// header cannot exceed the maximum timeout.
func contextWithTimeoutFromRequest(ctx context.Context, r *http.Request, defaultTimeout, maxTimeout time.Duration) (context.Context, context.CancelFunc, error) {
timeout := defaultTimeout
if s := strings.TrimSpace(r.Header.Get("Request-Timeout")); s != "" {
// the timeout is measured in seconds
v, err := strconv.ParseInt(s, 10, 16)
if err != nil {
return nil, nil, err
}
if d := time.Duration(v) * time.Second; d < maxTimeout {
timeout = d
} else {
return nil, nil, fmt.Errorf("exceeded maximum timeout of %d seconds", maxTimeout)
}
}
ctx, cancelFunc := context.WithTimeout(ctx, timeout)
return ctx, cancelFunc, nil
}
func newTestReceiversResult(r *notifier.TestReceiversResult) apimodels.TestReceiversResult {
v := apimodels.TestReceiversResult{
Alert: apimodels.TestReceiversConfigAlertParams{
Annotations: r.Alert.Annotations,
Labels: r.Alert.Labels,
},
Receivers: make([]apimodels.TestReceiverResult, len(r.Receivers)),
NotifiedAt: r.NotifedAt,
}
for ix, next := range r.Receivers {
configs := make([]apimodels.TestReceiverConfigResult, len(next.Configs))
for jx, config := range next.Configs {
configs[jx].Name = config.Name
configs[jx].UID = config.UID
configs[jx].Status = config.Status
if config.Error != nil {
configs[jx].Error = config.Error.Error()
}
}
v.Receivers[ix].Configs = configs
v.Receivers[ix].Name = next.Name
}
return v
}
// statusForTestReceivers returns the appropriate status code for the response
// for the results.
//
// It returns an HTTP 200 OK status code if notifications were sent to all receivers,
// an HTTP 400 Bad Request status code if all receivers contain invalid configuration,
// an HTTP 408 Request Timeout status code if all receivers timed out when sending
// a test notification or an HTTP 207 Multi Status.
func statusForTestReceivers(v []notifier.TestReceiverResult) int {
var (
numBadRequests int
numTimeouts int
numUnknownErrors int
)
for _, receiver := range v {
for _, next := range receiver.Configs {
if next.Error != nil {
var (
invalidReceiverErr notifier.InvalidReceiverError
receiverTimeoutErr alertingNotify.ReceiverTimeoutError
)
if errors.As(next.Error, &invalidReceiverErr) {
numBadRequests += 1
} else if errors.As(next.Error, &receiverTimeoutErr) {
numTimeouts += 1
} else {
numUnknownErrors += 1
}
}
}
}
if numBadRequests == len(v) {
// if all receivers contain invalid configuration
return http.StatusBadRequest
} else if numTimeouts == len(v) {
// if all receivers contain valid configuration but timed out
return http.StatusRequestTimeout
} else if numBadRequests+numTimeouts+numUnknownErrors > 0 {
return http.StatusMultiStatus
} else {
// all receivers were sent a notification without error
return http.StatusOK
}
}
func (srv AlertmanagerSrv) AlertmanagerFor(orgID int64) (Alertmanager, *response.NormalResponse) {
am, err := srv.mam.AlertmanagerFor(orgID)
if err == nil {
return am, nil
}
if errors.Is(err, notifier.ErrNoAlertmanagerForOrg) {
return nil, response.Error(http.StatusNotFound, err.Error(), err)
}
if errors.Is(err, notifier.ErrAlertmanagerNotReady) {
return am, response.Error(http.StatusConflict, err.Error(), err)
}
srv.log.Error("unable to obtain the org's Alertmanager", "error", err)
return nil, response.Error(http.StatusInternalServerError, "unable to obtain org's Alertmanager", err)
}
| pkg/services/ngalert/api/api_alertmanager.go | 1 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.03983188420534134,
0.0021682758815586567,
0.0001635700900806114,
0.00017553639190737158,
0.006926062051206827
]
|
{
"id": 2,
"code_window": [
"\t\"github.com/prometheus/common/model\"\n",
"\t\"gopkg.in/yaml.v3\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/services/secrets\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n",
")\n",
"\n",
"// swagger:route POST /api/alertmanager/grafana/config/api/v1/alerts alertmanager RoutePostGrafanaAlertingConfig\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/api/tooling/definitions/alertmanager.go",
"type": "replace",
"edit_start_line_idx": 19
} | import { uniqueId } from 'lodash';
import React, { ComponentProps, useRef } from 'react';
import { InlineField, Input } from '@grafana/ui';
import { useDispatch } from '../../../../hooks/useStatelessReducer';
import { BucketAggregation } from '../../../../types';
import { SettingsEditorContainer } from '../../SettingsEditorContainer';
import { changeBucketAggregationSetting } from '../state/actions';
import { bucketAggregationConfig } from '../utils';
import { DateHistogramSettingsEditor } from './DateHistogramSettingsEditor';
import { FiltersSettingsEditor } from './FiltersSettingsEditor';
import { TermsSettingsEditor } from './TermsSettingsEditor';
import { useDescription } from './useDescription';
export const inlineFieldProps: Partial<ComponentProps<typeof InlineField>> = {
labelWidth: 16,
};
interface Props {
bucketAgg: BucketAggregation;
}
export const SettingsEditor = ({ bucketAgg }: Props) => {
const { current: baseId } = useRef(uniqueId('es-setting-'));
const dispatch = useDispatch();
const settingsDescription = useDescription(bucketAgg);
return (
<SettingsEditorContainer label={settingsDescription}>
{bucketAgg.type === 'terms' && <TermsSettingsEditor bucketAgg={bucketAgg} />}
{bucketAgg.type === 'date_histogram' && <DateHistogramSettingsEditor bucketAgg={bucketAgg} />}
{bucketAgg.type === 'filters' && <FiltersSettingsEditor bucketAgg={bucketAgg} />}
{bucketAgg.type === 'geohash_grid' && (
<InlineField label="Precision" {...inlineFieldProps}>
<Input
id={`${baseId}-geohash_grid-precision`}
onBlur={(e) =>
dispatch(
changeBucketAggregationSetting({ bucketAgg, settingName: 'precision', newValue: e.target.value })
)
}
defaultValue={
bucketAgg.settings?.precision || bucketAggregationConfig[bucketAgg.type].defaultSettings?.precision
}
/>
</InlineField>
)}
{bucketAgg.type === 'histogram' && (
<>
<InlineField label="Interval" {...inlineFieldProps}>
<Input
id={`${baseId}-histogram-interval`}
onBlur={(e) =>
dispatch(
changeBucketAggregationSetting({ bucketAgg, settingName: 'interval', newValue: e.target.value })
)
}
defaultValue={
bucketAgg.settings?.interval || bucketAggregationConfig[bucketAgg.type].defaultSettings?.interval
}
/>
</InlineField>
<InlineField label="Min Doc Count" {...inlineFieldProps}>
<Input
id={`${baseId}-histogram-min_doc_count`}
onBlur={(e) =>
dispatch(
changeBucketAggregationSetting({ bucketAgg, settingName: 'min_doc_count', newValue: e.target.value })
)
}
defaultValue={
bucketAgg.settings?.min_doc_count ||
bucketAggregationConfig[bucketAgg.type].defaultSettings?.min_doc_count
}
/>
</InlineField>
</>
)}
</SettingsEditorContainer>
);
};
| public/app/plugins/datasource/elasticsearch/components/QueryEditor/BucketAggregationsEditor/SettingsEditor/index.tsx | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.00017786923854146153,
0.0001716888218652457,
0.00016349306679330766,
0.00017210800433531404,
0.000004610799805959687
]
|
{
"id": 2,
"code_window": [
"\t\"github.com/prometheus/common/model\"\n",
"\t\"gopkg.in/yaml.v3\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/services/secrets\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n",
")\n",
"\n",
"// swagger:route POST /api/alertmanager/grafana/config/api/v1/alerts alertmanager RoutePostGrafanaAlertingConfig\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/api/tooling/definitions/alertmanager.go",
"type": "replace",
"edit_start_line_idx": 19
} | ---
aliases:
- ../../http_api/serviceaccount/
canonical: /docs/grafana/latest/developers/http_api/serviceaccount/
description: Grafana service account HTTP API
keywords:
- grafana
- http
- documentation
- api
- serviceaccount
title: Service account HTTP API
---
# Service account API
> If you are running Grafana Enterprise, for some endpoints you'll need to have specific permissions. Refer to [Role-based access control permissions]({{< relref "/docs/grafana/latest/administration/roles-and-permissions/access-control/custom-role-actions-scopes" >}}) for more information.
## Search service accounts with Paging
`GET /api/serviceaccounts/search?perpage=10&page=1&query=myserviceaccount`
**Required permissions**
See note in the [introduction]({{< ref "#service-account-api" >}}) for an explanation.
| Action | Scope |
| -------------------- | ----- |
| serviceaccounts:read | n/a |
**Example Request**:
```http
GET /api/serviceaccounts/search?perpage=10&page=1&query=mygraf HTTP/1.1
Accept: application/json
Content-Type: application/json
Authorization: Basic YWRtaW46YWRtaW4=
```
Default value for the `perpage` parameter is `1000` and for the `page` parameter is `1`. The `totalCount` field in the response can be used for pagination of the user list E.g. if `totalCount` is equal to 100 users and the `perpage` parameter is set to 10 then there are 10 pages of users. The `query` parameter is optional and it will return results where the query value is contained in one of the `name`. Query values with spaces need to be URL encoded e.g. `query=Jane%20Doe`.
**Example Response**:
```http
HTTP/1.1 200
Content-Type: application/json
{
"totalCount": 2,
"serviceAccounts": [
{
"id": 1,
"name": "grafana",
"login": "sa-grafana",
"orgId": 1,
"isDisabled": false,
"role": "Viewer",
"tokens": 0,
"avatarUrl": "/avatar/85ec38023d90823d3e5b43ef35646af9",
"accessControl": {
"serviceaccounts:delete": true,
"serviceaccounts:read": true,
"serviceaccounts:write": true
}
},
{
"id": 2,
"name": "test",
"login": "sa-test",
"orgId": 1,
"isDisabled": false,
"role": "Viewer",
"tokens": 0,
"avatarUrl": "/avatar/8ea890a677d6a223c591a1beea6ea9d2",
"accessControl": {
"serviceaccounts:delete": true,
"serviceaccounts:read": true,
"serviceaccounts:write": true
}
}
],
"page": 1,
"perPage": 10
}
```
## Create service account
`POST /api/serviceaccounts`
**Required permissions**
See note in the [introduction]({{< ref "#service-account-api" >}}) for an explanation.
| Action | Scope |
| ---------------------- | ----- |
| serviceaccounts:create | n/a |
**Example Request**:
```http
POST /api/serviceaccounts HTTP/1.1
Accept: application/json
Content-Type: application/json
Authorization: Basic YWRtaW46YWRtaW4=
{
"name": "grafana",
"role": "Viewer",
"isDisabled" : false
}
```
**Example Response**:
```http
HTTP/1.1 201
Content-Type: application/json
{
"id": 1,
"name": "test",
"login": "sa-test",
"orgId": 1,
"isDisabled": false,
"createdAt": "2022-03-21T14:35:33Z",
"updatedAt": "2022-03-21T14:35:33Z",
"avatarUrl": "/avatar/8ea890a677d6a223c591a1beea6ea9d2",
"role": "Viewer",
"teams": []
}
```
## Get a service account by ID
`GET /api/serviceaccounts/:id`
**Required permissions**
See note in the [introduction]({{< ref "#service-account-api" >}}) for an explanation.
| Action | Scope |
| -------------------- | --------------------- |
| serviceaccounts:read | serviceaccounts:id:\* |
**Example Request**:
```http
GET /api/serviceaccounts/1 HTTP/1.1
Accept: application/json
Content-Type: application/json
Authorization: Basic YWRtaW46YWRtaW4=
```
**Example Response**:
```http
HTTP/1.1 200
Content-Type: application/json
{
"id": 1,
"name": "test",
"login": "sa-test",
"orgId": 1,
"isDisabled": false,
"createdAt": "2022-03-21T14:35:33Z",
"updatedAt": "2022-03-21T14:35:33Z",
"avatarUrl": "/avatar/8ea890a677d6a223c591a1beea6ea9d2",
"role": "Viewer",
"teams": []
}
```
## Update service account
`PATCH /api/serviceaccounts/:id`
**Required permissions**
See note in the [introduction]({{< ref "#service-account-api" >}}) for an explanation.
| Action | Scope |
| --------------------- | --------------------- |
| serviceaccounts:write | serviceaccounts:id:\* |
**Example Request**:
```http
PATCH /api/serviceaccounts/2 HTTP/1.1
Accept: application/json
Content-Type: application/json
Authorization: Basic YWRtaW46YWRtaW4=
{
"name": "test",
"role": "Editor"
}
```
**Example Response**:
```http
HTTP/1.1 200
Content-Type: application/json
{
"id": 2,
"name": "test",
"login": "sa-grafana",
"orgId": 1,
"isDisabled": false,
"createdAt": "2022-03-21T14:35:44Z",
"updatedAt": "2022-03-21T14:35:44Z",
"avatarUrl": "/avatar/8ea890a677d6a223c591a1beea6ea9d2",
"role": "Editor",
"teams": []
}
```
---
## Get service account tokens
`GET /api/serviceaccounts/:id/tokens`
**Required permissions**
See note in the [introduction]({{< ref "#service-account-api" >}}) for an explanation.
| Action | Scope |
| -------------------- | --------------------- |
| serviceaccounts:read | serviceaccounts:id:\* |
**Example Request**:
```http
GET /api/serviceaccounts/2/tokens HTTP/1.1
Accept: application/json
Content-Type: application/json
Authorization: Basic YWRtaW46YWRtaW4=
```
**Example Response**:
```http
HTTP/1.1 200
Content-Type: application/json
[
{
"id": 1,
"name": "grafana",
"role": "Viewer",
"created": "2022-03-23T10:31:02Z",
"expiration": null,
"secondsUntilExpiration": 0,
"hasExpired": false
}
]
```
## Create service account tokens
`POST /api/serviceaccounts/:id/tokens`
**Required permissions**
See note in the [introduction]({{< ref "#service-account-api" >}}) for an explanation.
| Action | Scope |
| --------------------- | --------------------- |
| serviceaccounts:write | serviceaccounts:id:\* |
**Example Request**:
```http
POST /api/serviceaccounts/2/tokens HTTP/1.1
Accept: application/json
Content-Type: application/json
Authorization: Basic YWRtaW46YWRtaW4=
{
"name": "grafana",
"role": "Viewer"
}
```
**Example Response**:
```http
HTTP/1.1 200
Content-Type: application/json
{
"id": 7,
"name": "grafana",
"key": "eyJrIjoiVjFxTHZ6dGdPSjg5Um92MjN1RlhjMkNqYkZUbm9jYkwiLCJuIjoiZ3JhZmFuYSIsImlkIjoxfQ=="
}
```
## Delete service account tokens
`DELETE /api/serviceaccounts/:id/tokens/:tokenId`
**Required permissions**
See note in the [introduction]({{< ref "#service-account-api" >}}) for an explanation.
| Action | Scope |
| --------------------- | --------------------- |
| serviceaccounts:write | serviceaccounts:id:\* |
**Example Request**:
```http
DELETE /api/serviceaccounts/2/tokens/1 HTTP/1.1
Accept: application/json
Content-Type: application/json
Authorization: Basic YWRtaW46YWRtaW4=
```
**Example Response**:
```http
HTTP/1.1 200
Content-Type: application/json
{
"message": "API key deleted"
}
```
## Revert service account token to API key
`DELETE /api/serviceaccounts/:serviceAccountId/revert/:keyId`
This operation will delete the service account and create a legacy API Key for the given `keyId`.
**Required permissions**
See note in the [introduction]({{< ref "#service-account-api" >}}) for an explanation.
| Action | Scope |
| ---------------------- | --------------------- |
| serviceaccounts:delete | serviceaccounts:id:\* |
**Example Request**:
```http
DELETE /api/serviceaccounts/1/revert/glsa_VVQjot0nijQ59lun6pMZRtsdBXxnFQ9M_77c34a79 HTTP/1.1
Accept: application/json
Content-Type: application/json
Authorization: Basic YWRtaW46YWRtaW4=
```
**Example Response**:
```http
HTTP/1.1 200
Content-Type: application/json
{
"message": "Reverted service account to API key"
}
```
| docs/sources/developers/http_api/serviceaccount.md | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.0006231263978406787,
0.00019797042477875948,
0.00016040824993979186,
0.0001711400254862383,
0.0000851443110150285
]
|
{
"id": 2,
"code_window": [
"\t\"github.com/prometheus/common/model\"\n",
"\t\"gopkg.in/yaml.v3\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/services/secrets\"\n",
"\t\"github.com/grafana/grafana/pkg/util\"\n",
")\n",
"\n",
"// swagger:route POST /api/alertmanager/grafana/config/api/v1/alerts alertmanager RoutePostGrafanaAlertingConfig\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/ngalert/api/tooling/definitions/alertmanager.go",
"type": "replace",
"edit_start_line_idx": 19
} | import { css } from '@emotion/css';
import React from 'react';
import { GrafanaTheme2 } from '@grafana/data';
import { useStyles2 } from '../../../themes';
interface Props {
label: string | undefined;
children?: React.ReactNode;
}
export const TimeZoneGroup = (props: Props) => {
const { children, label } = props;
const styles = useStyles2(getStyles);
if (!label) {
return <div>{children}</div>;
}
return (
<div>
<div className={styles.header}>
<span className={styles.label}>{label}</span>
</div>
{children}
</div>
);
};
const getStyles = (theme: GrafanaTheme2) => {
return {
header: css`
padding: 7px 10px;
width: 100%;
border-top: 1px solid ${theme.colors.border.weak};
text-transform: capitalize;
`,
label: css`
font-size: ${theme.typography.size.sm};
color: ${theme.colors.text.secondary};
font-weight: ${theme.typography.fontWeightMedium};
`,
};
};
| packages/grafana-ui/src/components/DateTimePickers/TimeZonePicker/TimeZoneGroup.tsx | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.00017727527301758528,
0.00017361312347929925,
0.00016900272748898715,
0.00017303389904554933,
0.000002929883066826733
]
|
{
"id": 3,
"code_window": [
"\tGrafanaManagedReceivers []*PostableGrafanaReceiver `yaml:\"grafana_managed_receiver_configs,omitempty\" json:\"grafana_managed_receiver_configs,omitempty\"`\n",
"}\n",
"\n",
"type EncryptFn func(ctx context.Context, payload []byte, scope secrets.EncryptionOptions) ([]byte, error)\n",
"\n",
"func processReceiverConfigs(c []*PostableApiReceiver, encrypt EncryptFn) error {\n",
"\tseenUIDs := make(map[string]struct{})\n",
"\t// encrypt secure settings for storing them in DB\n",
"\tfor _, r := range c {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"type EncryptFn func(ctx context.Context, payload []byte) ([]byte, error)\n"
],
"file_path": "pkg/services/ngalert/api/tooling/definitions/alertmanager.go",
"type": "replace",
"edit_start_line_idx": 1179
} | package notifier
import (
"context"
"errors"
"fmt"
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/store"
)
type UnknownReceiverError struct {
UID string
}
func (e UnknownReceiverError) Error() string {
return fmt.Sprintf("unknown receiver: %s", e.UID)
}
type AlertmanagerConfigRejectedError struct {
Inner error
}
func (e AlertmanagerConfigRejectedError) Error() string {
return fmt.Sprintf("failed to save and apply Alertmanager configuration: %s", e.Inner.Error())
}
type configurationStore interface {
GetLatestAlertmanagerConfiguration(ctx context.Context, query *models.GetLatestAlertmanagerConfigurationQuery) error
}
func (moa *MultiOrgAlertmanager) GetAlertmanagerConfiguration(ctx context.Context, org int64) (definitions.GettableUserConfig, error) {
query := models.GetLatestAlertmanagerConfigurationQuery{OrgID: org}
err := moa.configStore.GetLatestAlertmanagerConfiguration(ctx, &query)
if err != nil {
return definitions.GettableUserConfig{}, fmt.Errorf("failed to get latest configuration: %w", err)
}
cfg, err := Load([]byte(query.Result.AlertmanagerConfiguration))
if err != nil {
return definitions.GettableUserConfig{}, fmt.Errorf("failed to unmarshal alertmanager configuration: %w", err)
}
result := definitions.GettableUserConfig{
TemplateFiles: cfg.TemplateFiles,
AlertmanagerConfig: definitions.GettableApiAlertingConfig{
Config: cfg.AlertmanagerConfig.Config,
},
}
for _, recv := range cfg.AlertmanagerConfig.Receivers {
receivers := make([]*definitions.GettableGrafanaReceiver, 0, len(recv.PostableGrafanaReceivers.GrafanaManagedReceivers))
for _, pr := range recv.PostableGrafanaReceivers.GrafanaManagedReceivers {
secureFields := make(map[string]bool, len(pr.SecureSettings))
for k := range pr.SecureSettings {
decryptedValue, err := moa.Crypto.getDecryptedSecret(pr, k)
if err != nil {
return definitions.GettableUserConfig{}, fmt.Errorf("failed to decrypt stored secure setting: %w", err)
}
if decryptedValue == "" {
continue
}
secureFields[k] = true
}
gr := definitions.GettableGrafanaReceiver{
UID: pr.UID,
Name: pr.Name,
Type: pr.Type,
DisableResolveMessage: pr.DisableResolveMessage,
Settings: pr.Settings,
SecureFields: secureFields,
}
receivers = append(receivers, &gr)
}
gettableApiReceiver := definitions.GettableApiReceiver{
GettableGrafanaReceivers: definitions.GettableGrafanaReceivers{
GrafanaManagedReceivers: receivers,
},
}
gettableApiReceiver.Name = recv.Name
result.AlertmanagerConfig.Receivers = append(result.AlertmanagerConfig.Receivers, &gettableApiReceiver)
}
result, err = moa.mergeProvenance(ctx, result, org)
if err != nil {
return definitions.GettableUserConfig{}, err
}
return result, nil
}
func (moa *MultiOrgAlertmanager) ApplyAlertmanagerConfiguration(ctx context.Context, org int64, config definitions.PostableUserConfig) error {
// Get the last known working configuration
query := models.GetLatestAlertmanagerConfigurationQuery{OrgID: org}
if err := moa.configStore.GetLatestAlertmanagerConfiguration(ctx, &query); err != nil {
// If we don't have a configuration there's nothing for us to know and we should just continue saving the new one
if !errors.Is(err, store.ErrNoAlertmanagerConfiguration) {
return fmt.Errorf("failed to get latest configuration %w", err)
}
}
if err := moa.Crypto.LoadSecureSettings(ctx, org, config.AlertmanagerConfig.Receivers); err != nil {
return err
}
if err := config.ProcessConfig(moa.Crypto.Encrypt); err != nil {
return fmt.Errorf("failed to post process Alertmanager configuration: %w", err)
}
am, err := moa.AlertmanagerFor(org)
if err != nil {
// It's okay if the alertmanager isn't ready yet, we're changing its config anyway.
if !errors.Is(err, ErrAlertmanagerNotReady) {
return err
}
}
if err := am.SaveAndApplyConfig(ctx, &config); err != nil {
moa.logger.Error("unable to save and apply alertmanager configuration", "error", err)
return AlertmanagerConfigRejectedError{err}
}
return nil
}
func (moa *MultiOrgAlertmanager) mergeProvenance(ctx context.Context, config definitions.GettableUserConfig, org int64) (definitions.GettableUserConfig, error) {
if config.AlertmanagerConfig.Route != nil {
provenance, err := moa.ProvStore.GetProvenance(ctx, config.AlertmanagerConfig.Route, org)
if err != nil {
return definitions.GettableUserConfig{}, err
}
config.AlertmanagerConfig.Route.Provenance = definitions.Provenance(provenance)
}
cp := definitions.EmbeddedContactPoint{}
cpProvs, err := moa.ProvStore.GetProvenances(ctx, org, cp.ResourceType())
if err != nil {
return definitions.GettableUserConfig{}, err
}
for _, receiver := range config.AlertmanagerConfig.Receivers {
for _, contactPoint := range receiver.GrafanaManagedReceivers {
if provenance, exists := cpProvs[contactPoint.UID]; exists {
contactPoint.Provenance = definitions.Provenance(provenance)
}
}
}
tmpl := definitions.NotificationTemplate{}
tmplProvs, err := moa.ProvStore.GetProvenances(ctx, org, tmpl.ResourceType())
if err != nil {
return definitions.GettableUserConfig{}, nil
}
config.TemplateFileProvenances = make(map[string]definitions.Provenance, len(tmplProvs))
for key, provenance := range tmplProvs {
config.TemplateFileProvenances[key] = definitions.Provenance(provenance)
}
mt := definitions.MuteTimeInterval{}
mtProvs, err := moa.ProvStore.GetProvenances(ctx, org, mt.ResourceType())
if err != nil {
return definitions.GettableUserConfig{}, nil
}
config.AlertmanagerConfig.MuteTimeProvenances = make(map[string]definitions.Provenance, len(mtProvs))
for key, provenance := range mtProvs {
config.AlertmanagerConfig.MuteTimeProvenances[key] = definitions.Provenance(provenance)
}
return config, nil
}
| pkg/services/ngalert/notifier/alertmanager_config.go | 1 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.9919887185096741,
0.17575696110725403,
0.00016647568554617465,
0.00030412781052291393,
0.3766072988510132
]
|
{
"id": 3,
"code_window": [
"\tGrafanaManagedReceivers []*PostableGrafanaReceiver `yaml:\"grafana_managed_receiver_configs,omitempty\" json:\"grafana_managed_receiver_configs,omitempty\"`\n",
"}\n",
"\n",
"type EncryptFn func(ctx context.Context, payload []byte, scope secrets.EncryptionOptions) ([]byte, error)\n",
"\n",
"func processReceiverConfigs(c []*PostableApiReceiver, encrypt EncryptFn) error {\n",
"\tseenUIDs := make(map[string]struct{})\n",
"\t// encrypt secure settings for storing them in DB\n",
"\tfor _, r := range c {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"type EncryptFn func(ctx context.Context, payload []byte) ([]byte, error)\n"
],
"file_path": "pkg/services/ngalert/api/tooling/definitions/alertmanager.go",
"type": "replace",
"edit_start_line_idx": 1179
} | import { css } from '@emotion/css';
import { Global } from '@emotion/react';
import { Map as OpenLayersMap, MapBrowserEvent, View } from 'ol';
import Attribution from 'ol/control/Attribution';
import ScaleLine from 'ol/control/ScaleLine';
import Zoom from 'ol/control/Zoom';
import { Coordinate } from 'ol/coordinate';
import { isEmpty } from 'ol/extent';
import MouseWheelZoom from 'ol/interaction/MouseWheelZoom';
import { fromLonLat } from 'ol/proj';
import React, { Component, ReactNode } from 'react';
import { Subscription } from 'rxjs';
import { DataHoverEvent, PanelData, PanelProps } from '@grafana/data';
import { config } from '@grafana/runtime';
import { PanelContext, PanelContextRoot } from '@grafana/ui';
import { PanelEditExitedEvent } from 'app/types/events';
import { GeomapOverlay, OverlayProps } from './GeomapOverlay';
import { GeomapTooltip } from './GeomapTooltip';
import { DebugOverlay } from './components/DebugOverlay';
import { MeasureOverlay } from './components/MeasureOverlay';
import { MeasureVectorLayer } from './components/MeasureVectorLayer';
import { GeomapHoverPayload } from './event';
import { getGlobalStyles } from './globalStyles';
import { defaultMarkersConfig } from './layers/data/markersLayer';
import { DEFAULT_BASEMAP_CONFIG } from './layers/registry';
import { ControlsOptions, PanelOptions, MapLayerState, MapViewConfig, TooltipMode } from './types';
import { getActions } from './utils/actions';
import { getLayersExtent } from './utils/getLayersExtent';
import { applyLayerFilter, initLayer } from './utils/layers';
import { pointerClickListener, pointerMoveListener, setTooltipListeners } from './utils/tootltip';
import { updateMap, getNewOpenLayersMap, notifyPanelEditor } from './utils/utils';
import { centerPointRegistry, MapCenterID } from './view';
// Allows multiple panels to share the same view instance
let sharedView: View | undefined = undefined;
type Props = PanelProps<PanelOptions>;
interface State extends OverlayProps {
ttip?: GeomapHoverPayload;
ttipOpen: boolean;
legends: ReactNode[];
measureMenuActive?: boolean;
}
export class GeomapPanel extends Component<Props, State> {
declare context: React.ContextType<typeof PanelContextRoot>;
static contextType = PanelContextRoot;
panelContext: PanelContext | undefined = undefined;
private subs = new Subscription();
globalCSS = getGlobalStyles(config.theme2);
mouseWheelZoom?: MouseWheelZoom;
hoverPayload: GeomapHoverPayload = { point: {}, pageX: -1, pageY: -1 };
readonly hoverEvent = new DataHoverEvent(this.hoverPayload);
map?: OpenLayersMap;
mapDiv?: HTMLDivElement;
layers: MapLayerState[] = [];
readonly byName = new Map<string, MapLayerState>();
constructor(props: Props) {
super(props);
this.state = { ttipOpen: false, legends: [] };
this.subs.add(
this.props.eventBus.subscribe(PanelEditExitedEvent, (evt) => {
if (this.mapDiv && this.props.id === evt.payload) {
this.initMapRef(this.mapDiv);
}
})
);
}
componentDidMount() {
this.panelContext = this.context;
}
componentWillUnmount() {
this.subs.unsubscribe();
for (const lyr of this.layers) {
lyr.handler.dispose?.();
}
// Ensure map is disposed
this.map?.dispose();
}
shouldComponentUpdate(nextProps: Props) {
if (!this.map) {
return true; // not yet initialized
}
// Check for resize
if (this.props.height !== nextProps.height || this.props.width !== nextProps.width) {
this.map.updateSize();
}
// External data changed
if (this.props.data !== nextProps.data) {
this.dataChanged(nextProps.data);
}
// Options changed
if (this.props.options !== nextProps.options) {
this.optionsChanged(nextProps.options);
}
return true; // always?
}
componentDidUpdate(prevProps: Props) {
if (this.map && (this.props.height !== prevProps.height || this.props.width !== prevProps.width)) {
this.map.updateSize();
}
// Check for a difference between previous data and component data
if (this.map && this.props.data !== prevProps.data) {
this.dataChanged(this.props.data);
}
}
/** This function will actually update the JSON model */
doOptionsUpdate(selected: number) {
const { options, onOptionsChange } = this.props;
const layers = this.layers;
this.map?.getLayers().forEach((l) => {
if (l instanceof MeasureVectorLayer) {
this.map?.removeLayer(l);
this.map?.addLayer(l);
}
});
onOptionsChange({
...options,
basemap: layers[0].options,
layers: layers.slice(1).map((v) => v.options),
});
notifyPanelEditor(this, layers, selected);
this.setState({ legends: this.getLegends() });
}
actions = getActions(this);
/**
* Called when the panel options change
*
* NOTE: changes to basemap and layers are handled independently
*/
optionsChanged(options: PanelOptions) {
const oldOptions = this.props.options;
if (options.view !== oldOptions.view) {
const [updatedSharedView, view] = this.initMapView(options.view, sharedView);
sharedView = updatedSharedView;
if (this.map && view) {
this.map.setView(view);
}
}
if (options.controls !== oldOptions.controls) {
this.initControls(options.controls ?? { showZoom: true, showAttribution: true });
}
}
/**
* Called when PanelData changes (query results etc)
*/
dataChanged(data: PanelData) {
// Only update if panel data matches component data
if (data === this.props.data) {
for (const state of this.layers) {
applyLayerFilter(state.handler, state.options, this.props.data);
}
}
// Because data changed, check map view and change if needed (data fit)
const v = centerPointRegistry.getIfExists(this.props.options.view.id);
if (v && v.id === MapCenterID.Fit) {
const [, view] = this.initMapView(this.props.options.view);
if (this.map && view) {
this.map.setView(view);
}
}
}
initMapRef = async (div: HTMLDivElement) => {
if (!div) {
// Do not initialize new map or dispose old map
return;
}
this.mapDiv = div;
if (this.map) {
this.map.dispose();
}
const { options } = this.props;
const map = getNewOpenLayersMap(this, options, div);
this.byName.clear();
const layers: MapLayerState[] = [];
try {
layers.push(await initLayer(this, map, options.basemap ?? DEFAULT_BASEMAP_CONFIG, true));
// Default layer values
if (!options.layers) {
options.layers = [defaultMarkersConfig];
}
for (const lyr of options.layers) {
layers.push(await initLayer(this, map, lyr, false));
}
} catch (ex) {
console.error('error loading layers', ex);
}
for (const lyr of layers) {
map.addLayer(lyr.layer);
}
this.layers = layers;
this.map = map; // redundant
this.initViewExtent(map.getView(), options.view);
this.mouseWheelZoom = new MouseWheelZoom();
this.map?.addInteraction(this.mouseWheelZoom);
updateMap(this, options);
setTooltipListeners(this);
notifyPanelEditor(this, layers, layers.length - 1);
this.setState({ legends: this.getLegends() });
};
clearTooltip = () => {
if (this.state.ttip && !this.state.ttipOpen) {
this.tooltipPopupClosed();
}
};
tooltipPopupClosed = () => {
this.setState({ ttipOpen: false, ttip: undefined });
};
pointerClickListener = (evt: MapBrowserEvent<MouseEvent>) => {
pointerClickListener(evt, this);
};
pointerMoveListener = (evt: MapBrowserEvent<MouseEvent>) => {
pointerMoveListener(evt, this);
};
initMapView = (config: MapViewConfig, sharedView?: View | undefined): Array<View | undefined> => {
let view = new View({
center: [0, 0],
zoom: 1,
showFullExtent: true, // allows zooming so the full range is visible
});
// With shared views, all panels use the same view instance
if (config.shared) {
if (!sharedView) {
sharedView = view;
} else {
view = sharedView;
}
}
this.initViewExtent(view, config);
return [sharedView, view];
};
initViewExtent(view: View, config: MapViewConfig) {
const v = centerPointRegistry.getIfExists(config.id);
if (v) {
let coord: Coordinate | undefined = undefined;
if (v.lat == null) {
if (v.id === MapCenterID.Coordinates) {
coord = [config.lon ?? 0, config.lat ?? 0];
} else if (v.id === MapCenterID.Fit) {
const extent = getLayersExtent(this.layers, config.allLayers, config.lastOnly, config.layer);
if (!isEmpty(extent)) {
const padding = config.padding ?? 5;
const res = view.getResolutionForExtent(extent, this.map?.getSize());
const maxZoom = config.zoom ?? config.maxZoom;
view.fit(extent, {
maxZoom: maxZoom,
});
view.setResolution(res * (padding / 100 + 1));
const adjustedZoom = view.getZoom();
if (adjustedZoom && maxZoom && adjustedZoom > maxZoom) {
view.setZoom(maxZoom);
}
}
} else {
// TODO: view requires special handling
}
} else {
coord = [v.lon ?? 0, v.lat ?? 0];
}
if (coord) {
view.setCenter(fromLonLat(coord));
}
}
if (config.maxZoom) {
view.setMaxZoom(config.maxZoom);
}
if (config.minZoom) {
view.setMaxZoom(config.minZoom);
}
if (config.zoom && v?.id !== MapCenterID.Fit) {
view.setZoom(config.zoom);
}
}
initControls(options: ControlsOptions) {
if (!this.map) {
return;
}
this.map.getControls().clear();
if (options.showZoom) {
this.map.addControl(new Zoom());
}
if (options.showScale) {
this.map.addControl(
new ScaleLine({
units: options.scaleUnits,
minWidth: 100,
})
);
}
this.mouseWheelZoom!.setActive(Boolean(options.mouseWheelZoom));
if (options.showAttribution) {
this.map.addControl(new Attribution({ collapsed: true, collapsible: true }));
}
// Update the react overlays
let topRight1: ReactNode[] = [];
if (options.showMeasure) {
topRight1 = [
<MeasureOverlay
key="measure"
map={this.map}
// Lifts menuActive state and resets tooltip state upon close
menuActiveState={(value: boolean) => {
this.setState({ ttipOpen: value, measureMenuActive: value });
}}
/>,
];
}
let topRight2: ReactNode[] = [];
if (options.showDebug) {
topRight2 = [<DebugOverlay key="debug" map={this.map} />];
}
this.setState({ topRight1, topRight2 });
}
getLegends() {
const legends: ReactNode[] = [];
for (const state of this.layers) {
if (state.handler.legend) {
legends.push(<div key={state.options.name}>{state.handler.legend}</div>);
}
}
return legends;
}
render() {
let { ttip, ttipOpen, topRight1, legends, topRight2 } = this.state;
const { options } = this.props;
const showScale = options.controls.showScale;
if (!ttipOpen && options.tooltip?.mode === TooltipMode.None) {
ttip = undefined;
}
return (
<>
<Global styles={this.globalCSS} />
<div className={styles.wrap} onMouseLeave={this.clearTooltip}>
<div className={styles.map} ref={this.initMapRef}></div>
<GeomapOverlay
bottomLeft={legends}
topRight1={topRight1}
topRight2={topRight2}
blStyle={{ bottom: showScale ? '35px' : '8px' }}
/>
</div>
<GeomapTooltip ttip={ttip} isOpen={ttipOpen} onClose={this.tooltipPopupClosed} />
</>
);
}
}
const styles = {
wrap: css`
position: relative;
width: 100%;
height: 100%;
`,
map: css`
position: absolute;
z-index: 0;
width: 100%;
height: 100%;
`,
};
| public/app/plugins/panel/geomap/GeomapPanel.tsx | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.00035819548065774143,
0.00017382066289428622,
0.00016611289174761623,
0.00016903398500289768,
0.000028851387469330803
]
|
{
"id": 3,
"code_window": [
"\tGrafanaManagedReceivers []*PostableGrafanaReceiver `yaml:\"grafana_managed_receiver_configs,omitempty\" json:\"grafana_managed_receiver_configs,omitempty\"`\n",
"}\n",
"\n",
"type EncryptFn func(ctx context.Context, payload []byte, scope secrets.EncryptionOptions) ([]byte, error)\n",
"\n",
"func processReceiverConfigs(c []*PostableApiReceiver, encrypt EncryptFn) error {\n",
"\tseenUIDs := make(map[string]struct{})\n",
"\t// encrypt secure settings for storing them in DB\n",
"\tfor _, r := range c {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"type EncryptFn func(ctx context.Context, payload []byte) ([]byte, error)\n"
],
"file_path": "pkg/services/ngalert/api/tooling/definitions/alertmanager.go",
"type": "replace",
"edit_start_line_idx": 1179
} | package codegen
import (
"bytes"
"go/parser"
"go/token"
"testing"
"github.com/dave/dst/decorator"
"github.com/dave/dst/dstutil"
"github.com/matryer/is"
)
func TestPrefixDropper(t *testing.T) {
tt := map[string]struct {
in, out string
skip bool
}{
"basic": {
in: `package foo
type Foo struct {
Id int64
Ref FooThing
}
type FooThing struct {
Id int64
}`,
out: `package foo
type Foo struct {
Id int64
Ref Thing
}
type Thing struct {
Id int64
}
`,
},
"pointer": {
in: `package foo
type Foo struct {
Id int64
Ref *FooThing
}
type FooThing struct {
Id int64
}`,
out: `package foo
type Foo struct {
Id int64
Ref *Thing
}
type Thing struct {
Id int64
}
`,
},
"sliceref": {
in: `package foo
type Foo struct {
Id int64
Ref []FooThing
PRef []*FooThing
SPRef *[]FooThing
}
type FooThing struct {
Id int64
}`,
out: `package foo
type Foo struct {
Id int64
Ref []Thing
PRef []*Thing
SPRef *[]Thing
}
type Thing struct {
Id int64
}
`,
},
"mapref": {
in: `package foo
type Foo struct {
Id int64
KeyRef map[FooThing]string
ValRef map[string]FooThing
BothRef map[FooThing]FooThing
}
type FooThing struct {
Id int64
}`,
out: `package foo
type Foo struct {
Id int64
KeyRef map[Thing]string
ValRef map[string]Thing
BothRef map[Thing]Thing
}
type Thing struct {
Id int64
}
`,
},
"pmapref": {
in: `package foo
type Foo struct {
Id int64
KeyRef map[*FooThing]string
ValRef map[string]*FooThing
BothRef map[*FooThing]*FooThing
PKeyRef *map[*FooThing]string
}
type FooThing struct {
Id int64
}`,
out: `package foo
type Foo struct {
Id int64
KeyRef map[*Thing]string
ValRef map[string]*Thing
BothRef map[*Thing]*Thing
PKeyRef *map[*Thing]string
}
type Thing struct {
Id int64
}
`,
},
"ignore-fieldname": {
in: `package foo
type Foo struct {
Id int64
FooRef []string
}`,
out: `package foo
type Foo struct {
Id int64
FooRef []string
}
`,
},
"const": {
in: `package foo
const one FooThing = "boop"
const (
two FooThing = "boop"
three FooThing = "boop"
)
type FooThing string
`,
out: `package foo
const one Thing = "boop"
const (
two Thing = "boop"
three Thing = "boop"
)
type Thing string
`,
},
"var": {
in: `package foo
var one FooThing = "boop"
var (
two FooThing = "boop"
three FooThing = "boop"
)
type FooThing string
`,
out: `package foo
var one Thing = "boop"
var (
two Thing = "boop"
three Thing = "boop"
)
type Thing string
`,
},
"varp": {
in: `package foo
var one *FooThing = "boop"
var (
two []FooThing = []FooThing{"boop"}
three map[FooThing]string = map[FooThing]string{ "beep": "boop" }
)
type FooThing string
`,
out: `package foo
var one *Thing = "boop"
var (
two []Thing = []Thing{"boop"}
three map[Thing]string = map[Thing]string{ "beep": "boop" }
)
type Thing string
`,
// Skip this one for now - there's currently no codegen that constructs instances
// of objects, only types, so we shouldn't encounter this case.
skip: true,
},
"comments": {
in: `package foo
// Foo is a thing. It should be Foo still.
type Foo struct {
Id int64
Ref FooThing
}
// FooThing is also a thing. We want [FooThing] to be known properly.
// Even if FooThing
// were not a FooThing, in our minds, forever shall it be FooThing.
type FooThing struct {
Id int64
}`,
out: `package foo
// Foo is a thing. It should be Foo still.
type Foo struct {
Id int64
Ref Thing
}
// Thing is also a thing. We want [Thing] to be known properly.
// Even if Thing
// were not a Thing, in our minds, forever shall it be Thing.
type Thing struct {
Id int64
}
`,
},
}
for name, it := range tt {
item := it
t.Run(name, func(t *testing.T) {
if item.skip {
t.Skip()
}
is := is.New(t)
fset := token.NewFileSet()
inf, err := decorator.ParseFile(fset, "input.go", item.in, parser.ParseComments)
if err != nil {
t.Fatal(err)
}
drop := PrefixDropper("Foo")
dstutil.Apply(inf, drop, nil)
buf := new(bytes.Buffer)
err = decorator.Fprint(buf, inf)
if err != nil {
t.Fatal(err)
}
is.Equal(item.out, buf.String())
})
}
}
| pkg/codegen/astmanip_test.go | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.0008677196456119418,
0.00023132073692977428,
0.0001652985520195216,
0.00016981814405880868,
0.00017492596816737205
]
|
{
"id": 3,
"code_window": [
"\tGrafanaManagedReceivers []*PostableGrafanaReceiver `yaml:\"grafana_managed_receiver_configs,omitempty\" json:\"grafana_managed_receiver_configs,omitempty\"`\n",
"}\n",
"\n",
"type EncryptFn func(ctx context.Context, payload []byte, scope secrets.EncryptionOptions) ([]byte, error)\n",
"\n",
"func processReceiverConfigs(c []*PostableApiReceiver, encrypt EncryptFn) error {\n",
"\tseenUIDs := make(map[string]struct{})\n",
"\t// encrypt secure settings for storing them in DB\n",
"\tfor _, r := range c {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"type EncryptFn func(ctx context.Context, payload []byte) ([]byte, error)\n"
],
"file_path": "pkg/services/ngalert/api/tooling/definitions/alertmanager.go",
"type": "replace",
"edit_start_line_idx": 1179
} | import React, { CSSProperties } from 'react';
import { fieldColorModeRegistry } from '@grafana/data';
import { useTheme2 } from '../../themes';
export interface Props extends React.HTMLAttributes<HTMLDivElement> {
color?: string;
gradient?: string;
}
export const SeriesIcon = React.memo(
React.forwardRef<HTMLDivElement, Props>(({ color, className, gradient, ...restProps }, ref) => {
const theme = useTheme2();
let cssColor: string;
if (gradient) {
const colors = fieldColorModeRegistry.get(gradient).getColors?.(theme);
if (colors?.length) {
cssColor = `linear-gradient(90deg, ${colors.join(', ')})`;
} else {
// Not sure what to default to, this will return gray, this should not happen though.
cssColor = theme.visualization.getColorByName('');
}
} else {
cssColor = color!;
}
const styles: CSSProperties = {
background: cssColor,
width: '14px',
height: '4px',
borderRadius: theme.shape.radius.default,
display: 'inline-block',
marginRight: '8px',
};
return <div data-testid="series-icon" ref={ref} className={className} style={styles} {...restProps} />;
})
);
SeriesIcon.displayName = 'SeriesIcon';
| packages/grafana-ui/src/components/VizLegend/SeriesIcon.tsx | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.0001710912329144776,
0.00017012844909913838,
0.00016929286357481033,
0.000169663893757388,
7.814901437086519e-7
]
|
{
"id": 4,
"code_window": [
"\t\tcase GrafanaReceiverType:\n",
"\t\t\tfor _, gr := range r.PostableGrafanaReceivers.GrafanaManagedReceivers {\n",
"\t\t\t\tfor k, v := range gr.SecureSettings {\n",
"\t\t\t\t\tencryptedData, err := encrypt(context.Background(), []byte(v), secrets.WithoutScope())\n",
"\t\t\t\t\tif err != nil {\n",
"\t\t\t\t\t\treturn fmt.Errorf(\"failed to encrypt secure settings: %w\", err)\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tgr.SecureSettings[k] = base64.StdEncoding.EncodeToString(encryptedData)\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tencryptedData, err := encrypt(context.Background(), []byte(v))\n"
],
"file_path": "pkg/services/ngalert/api/tooling/definitions/alertmanager.go",
"type": "replace",
"edit_start_line_idx": 1189
} | package api
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/go-openapi/strfmt"
alertingNotify "github.com/grafana/alerting/notify"
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/accesscontrol"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/notifier"
"github.com/grafana/grafana/pkg/services/ngalert/store"
"github.com/grafana/grafana/pkg/util"
)
const (
defaultTestReceiversTimeout = 15 * time.Second
maxTestReceiversTimeout = 30 * time.Second
)
type AlertmanagerSrv struct {
log log.Logger
ac accesscontrol.AccessControl
mam *notifier.MultiOrgAlertmanager
crypto notifier.Crypto
}
type UnknownReceiverError struct {
UID string
}
func (e UnknownReceiverError) Error() string {
return fmt.Sprintf("unknown receiver: %s", e.UID)
}
func (srv AlertmanagerSrv) RouteGetAMStatus(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
return response.JSON(http.StatusOK, am.GetStatus())
}
func (srv AlertmanagerSrv) RouteCreateSilence(c *contextmodel.ReqContext, postableSilence apimodels.PostableSilence) response.Response {
err := postableSilence.Validate(strfmt.Default)
if err != nil {
srv.log.Error("silence failed validation", "error", err)
return ErrResp(http.StatusBadRequest, err, "silence failed validation")
}
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
action := accesscontrol.ActionAlertingInstanceUpdate
if postableSilence.ID == "" {
action = accesscontrol.ActionAlertingInstanceCreate
}
if !accesscontrol.HasAccess(srv.ac, c)(accesscontrol.ReqOrgAdminOrEditor, accesscontrol.EvalPermission(action)) {
errAction := "update"
if postableSilence.ID == "" {
errAction = "create"
}
return ErrResp(http.StatusUnauthorized, fmt.Errorf("user is not authorized to %s silences", errAction), "")
}
silenceID, err := am.CreateSilence(&postableSilence)
if err != nil {
if errors.Is(err, alertingNotify.ErrSilenceNotFound) {
return ErrResp(http.StatusNotFound, err, "")
}
if errors.Is(err, alertingNotify.ErrCreateSilenceBadPayload) {
return ErrResp(http.StatusBadRequest, err, "")
}
return ErrResp(http.StatusInternalServerError, err, "failed to create silence")
}
return response.JSON(http.StatusAccepted, apimodels.PostSilencesOKBody{
SilenceID: silenceID,
})
}
func (srv AlertmanagerSrv) RouteDeleteAlertingConfig(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
if err := am.SaveAndApplyDefaultConfig(c.Req.Context()); err != nil {
srv.log.Error("unable to save and apply default alertmanager configuration", "error", err)
return ErrResp(http.StatusInternalServerError, err, "failed to save and apply default Alertmanager configuration")
}
return response.JSON(http.StatusAccepted, util.DynMap{"message": "configuration deleted; the default is applied"})
}
func (srv AlertmanagerSrv) RouteDeleteSilence(c *contextmodel.ReqContext, silenceID string) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
if err := am.DeleteSilence(silenceID); err != nil {
if errors.Is(err, alertingNotify.ErrSilenceNotFound) {
return ErrResp(http.StatusNotFound, err, "")
}
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(http.StatusOK, util.DynMap{"message": "silence deleted"})
}
func (srv AlertmanagerSrv) RouteGetAlertingConfig(c *contextmodel.ReqContext) response.Response {
config, err := srv.mam.GetAlertmanagerConfiguration(c.Req.Context(), c.OrgID)
if err != nil {
if errors.Is(err, store.ErrNoAlertmanagerConfiguration) {
return ErrResp(http.StatusNotFound, err, "")
}
return ErrResp(http.StatusInternalServerError, err, err.Error())
}
return response.JSON(http.StatusOK, config)
}
func (srv AlertmanagerSrv) RouteGetAMAlertGroups(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
groups, err := am.GetAlertGroups(
c.QueryBoolWithDefault("active", true),
c.QueryBoolWithDefault("silenced", true),
c.QueryBoolWithDefault("inhibited", true),
c.QueryStrings("filter"),
c.Query("receiver"),
)
if err != nil {
if errors.Is(err, alertingNotify.ErrGetAlertGroupsBadPayload) {
return ErrResp(http.StatusBadRequest, err, "")
}
// any other error here should be an unexpected failure and thus an internal error
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(http.StatusOK, groups)
}
func (srv AlertmanagerSrv) RouteGetAMAlerts(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
alerts, err := am.GetAlerts(
c.QueryBoolWithDefault("active", true),
c.QueryBoolWithDefault("silenced", true),
c.QueryBoolWithDefault("inhibited", true),
c.QueryStrings("filter"),
c.Query("receiver"),
)
if err != nil {
if errors.Is(err, alertingNotify.ErrGetAlertsBadPayload) {
return ErrResp(http.StatusBadRequest, err, "")
}
if errors.Is(err, alertingNotify.ErrGetAlertsUnavailable) {
return ErrResp(http.StatusServiceUnavailable, err, "")
}
// any other error here should be an unexpected failure and thus an internal error
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(http.StatusOK, alerts)
}
func (srv AlertmanagerSrv) RouteGetSilence(c *contextmodel.ReqContext, silenceID string) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
gettableSilence, err := am.GetSilence(silenceID)
if err != nil {
if errors.Is(err, alertingNotify.ErrSilenceNotFound) {
return ErrResp(http.StatusNotFound, err, "")
}
// any other error here should be an unexpected failure and thus an internal error
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(http.StatusOK, gettableSilence)
}
func (srv AlertmanagerSrv) RouteGetSilences(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
gettableSilences, err := am.ListSilences(c.QueryStrings("filter"))
if err != nil {
if errors.Is(err, alertingNotify.ErrListSilencesBadPayload) {
return ErrResp(http.StatusBadRequest, err, "")
}
// any other error here should be an unexpected failure and thus an internal error
return ErrResp(http.StatusInternalServerError, err, "")
}
return response.JSON(http.StatusOK, gettableSilences)
}
func (srv AlertmanagerSrv) RoutePostAlertingConfig(c *contextmodel.ReqContext, body apimodels.PostableUserConfig) response.Response {
currentConfig, err := srv.mam.GetAlertmanagerConfiguration(c.Req.Context(), c.OrgID)
// If a config is present and valid we proceed with the guard, otherwise we
// just bypass the guard which is okay as we are anyway in an invalid state.
if err == nil {
if err := srv.provenanceGuard(currentConfig, body); err != nil {
return ErrResp(http.StatusBadRequest, err, "")
}
}
err = srv.mam.ApplyAlertmanagerConfiguration(c.Req.Context(), c.OrgID, body)
if err == nil {
return response.JSON(http.StatusAccepted, util.DynMap{"message": "configuration created"})
}
var unknownReceiverError notifier.UnknownReceiverError
if errors.As(err, &unknownReceiverError) {
return ErrResp(http.StatusBadRequest, unknownReceiverError, "")
}
var configRejectedError notifier.AlertmanagerConfigRejectedError
if errors.As(err, &configRejectedError) {
return ErrResp(http.StatusBadRequest, configRejectedError, "")
}
if errors.Is(err, notifier.ErrNoAlertmanagerForOrg) {
return response.Error(http.StatusNotFound, err.Error(), err)
}
if errors.Is(err, notifier.ErrAlertmanagerNotReady) {
return response.Error(http.StatusConflict, err.Error(), err)
}
return ErrResp(http.StatusInternalServerError, err, "")
}
func (srv AlertmanagerSrv) RouteGetReceivers(c *contextmodel.ReqContext) response.Response {
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
rcvs := am.GetReceivers(c.Req.Context())
return response.JSON(http.StatusOK, rcvs)
}
func (srv AlertmanagerSrv) RoutePostTestReceivers(c *contextmodel.ReqContext, body apimodels.TestReceiversConfigBodyParams) response.Response {
if err := srv.crypto.LoadSecureSettings(c.Req.Context(), c.OrgID, body.Receivers); err != nil {
var unknownReceiverError UnknownReceiverError
if errors.As(err, &unknownReceiverError) {
return ErrResp(http.StatusBadRequest, err, "")
}
return ErrResp(http.StatusInternalServerError, err, "")
}
if err := body.ProcessConfig(srv.crypto.Encrypt); err != nil {
return ErrResp(http.StatusInternalServerError, err, "failed to post process Alertmanager configuration")
}
ctx, cancelFunc, err := contextWithTimeoutFromRequest(
c.Req.Context(),
c.Req,
defaultTestReceiversTimeout,
maxTestReceiversTimeout)
if err != nil {
return ErrResp(http.StatusBadRequest, err, "")
}
defer cancelFunc()
am, errResp := srv.AlertmanagerFor(c.OrgID)
if errResp != nil {
return errResp
}
result, err := am.TestReceivers(ctx, body)
if err != nil {
if errors.Is(err, alertingNotify.ErrNoReceivers) {
return response.Error(http.StatusBadRequest, "", err)
}
return response.Error(http.StatusInternalServerError, "", err)
}
return response.JSON(statusForTestReceivers(result.Receivers), newTestReceiversResult(result))
}
// contextWithTimeoutFromRequest returns a context with a deadline set from the
// Request-Timeout header in the HTTP request. If the header is absent then the
// context will use the default timeout. The timeout in the Request-Timeout
// header cannot exceed the maximum timeout.
func contextWithTimeoutFromRequest(ctx context.Context, r *http.Request, defaultTimeout, maxTimeout time.Duration) (context.Context, context.CancelFunc, error) {
timeout := defaultTimeout
if s := strings.TrimSpace(r.Header.Get("Request-Timeout")); s != "" {
// the timeout is measured in seconds
v, err := strconv.ParseInt(s, 10, 16)
if err != nil {
return nil, nil, err
}
if d := time.Duration(v) * time.Second; d < maxTimeout {
timeout = d
} else {
return nil, nil, fmt.Errorf("exceeded maximum timeout of %d seconds", maxTimeout)
}
}
ctx, cancelFunc := context.WithTimeout(ctx, timeout)
return ctx, cancelFunc, nil
}
func newTestReceiversResult(r *notifier.TestReceiversResult) apimodels.TestReceiversResult {
v := apimodels.TestReceiversResult{
Alert: apimodels.TestReceiversConfigAlertParams{
Annotations: r.Alert.Annotations,
Labels: r.Alert.Labels,
},
Receivers: make([]apimodels.TestReceiverResult, len(r.Receivers)),
NotifiedAt: r.NotifedAt,
}
for ix, next := range r.Receivers {
configs := make([]apimodels.TestReceiverConfigResult, len(next.Configs))
for jx, config := range next.Configs {
configs[jx].Name = config.Name
configs[jx].UID = config.UID
configs[jx].Status = config.Status
if config.Error != nil {
configs[jx].Error = config.Error.Error()
}
}
v.Receivers[ix].Configs = configs
v.Receivers[ix].Name = next.Name
}
return v
}
// statusForTestReceivers returns the appropriate status code for the response
// for the results.
//
// It returns an HTTP 200 OK status code if notifications were sent to all receivers,
// an HTTP 400 Bad Request status code if all receivers contain invalid configuration,
// an HTTP 408 Request Timeout status code if all receivers timed out when sending
// a test notification or an HTTP 207 Multi Status.
func statusForTestReceivers(v []notifier.TestReceiverResult) int {
var (
numBadRequests int
numTimeouts int
numUnknownErrors int
)
for _, receiver := range v {
for _, next := range receiver.Configs {
if next.Error != nil {
var (
invalidReceiverErr notifier.InvalidReceiverError
receiverTimeoutErr alertingNotify.ReceiverTimeoutError
)
if errors.As(next.Error, &invalidReceiverErr) {
numBadRequests += 1
} else if errors.As(next.Error, &receiverTimeoutErr) {
numTimeouts += 1
} else {
numUnknownErrors += 1
}
}
}
}
if numBadRequests == len(v) {
// if all receivers contain invalid configuration
return http.StatusBadRequest
} else if numTimeouts == len(v) {
// if all receivers contain valid configuration but timed out
return http.StatusRequestTimeout
} else if numBadRequests+numTimeouts+numUnknownErrors > 0 {
return http.StatusMultiStatus
} else {
// all receivers were sent a notification without error
return http.StatusOK
}
}
func (srv AlertmanagerSrv) AlertmanagerFor(orgID int64) (Alertmanager, *response.NormalResponse) {
am, err := srv.mam.AlertmanagerFor(orgID)
if err == nil {
return am, nil
}
if errors.Is(err, notifier.ErrNoAlertmanagerForOrg) {
return nil, response.Error(http.StatusNotFound, err.Error(), err)
}
if errors.Is(err, notifier.ErrAlertmanagerNotReady) {
return am, response.Error(http.StatusConflict, err.Error(), err)
}
srv.log.Error("unable to obtain the org's Alertmanager", "error", err)
return nil, response.Error(http.StatusInternalServerError, "unable to obtain org's Alertmanager", err)
}
| pkg/services/ngalert/api/api_alertmanager.go | 1 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.03188083693385124,
0.0015895215328782797,
0.00015893764793872833,
0.0001713823585305363,
0.005298563279211521
]
|
{
"id": 4,
"code_window": [
"\t\tcase GrafanaReceiverType:\n",
"\t\t\tfor _, gr := range r.PostableGrafanaReceivers.GrafanaManagedReceivers {\n",
"\t\t\t\tfor k, v := range gr.SecureSettings {\n",
"\t\t\t\t\tencryptedData, err := encrypt(context.Background(), []byte(v), secrets.WithoutScope())\n",
"\t\t\t\t\tif err != nil {\n",
"\t\t\t\t\t\treturn fmt.Errorf(\"failed to encrypt secure settings: %w\", err)\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tgr.SecureSettings[k] = base64.StdEncoding.EncodeToString(encryptedData)\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tencryptedData, err := encrypt(context.Background(), []byte(v))\n"
],
"file_path": "pkg/services/ngalert/api/tooling/definitions/alertmanager.go",
"type": "replace",
"edit_start_line_idx": 1189
} | import { css } from '@emotion/css';
import React, { ReactElement } from 'react';
import { Draggable } from 'react-beautiful-dnd';
import { GrafanaTheme2 } from '@grafana/data';
import { selectors } from '@grafana/e2e-selectors';
import { reportInteraction } from '@grafana/runtime';
import { Button, Icon, IconButton, useStyles2, useTheme2 } from '@grafana/ui';
import { hasOptions, isAdHoc, isQuery } from '../guard';
import { VariableUsagesButton } from '../inspect/VariableUsagesButton';
import { getVariableUsages, UsagesToNetwork, VariableUsageTree } from '../inspect/utils';
import { KeyedVariableIdentifier } from '../state/types';
import { VariableModel } from '../types';
import { toKeyedVariableIdentifier } from '../utils';
export interface VariableEditorListRowProps {
index: number;
variable: VariableModel;
usageTree: VariableUsageTree[];
usagesNetwork: UsagesToNetwork[];
onEdit: (identifier: KeyedVariableIdentifier) => void;
onDuplicate: (identifier: KeyedVariableIdentifier) => void;
onDelete: (identifier: KeyedVariableIdentifier) => void;
}
export function VariableEditorListRow({
index,
variable,
usageTree,
usagesNetwork,
onEdit: propsOnEdit,
onDuplicate: propsOnDuplicate,
onDelete: propsOnDelete,
}: VariableEditorListRowProps): ReactElement {
const theme = useTheme2();
const styles = useStyles2(getStyles);
const definition = getDefinition(variable);
const usages = getVariableUsages(variable.id, usageTree);
const passed = usages > 0 || isAdHoc(variable);
const identifier = toKeyedVariableIdentifier(variable);
return (
<Draggable draggableId={JSON.stringify(identifier)} index={index}>
{(provided, snapshot) => (
<tr
ref={provided.innerRef}
{...provided.draggableProps}
style={{
userSelect: snapshot.isDragging ? 'none' : 'auto',
background: snapshot.isDragging ? theme.colors.background.secondary : undefined,
...provided.draggableProps.style,
}}
>
<td role="gridcell" className={styles.column}>
<Button
size="xs"
fill="text"
onClick={(event) => {
event.preventDefault();
propsOnEdit(identifier);
}}
className={styles.nameLink}
aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowNameFields(variable.name)}
>
{variable.name}
</Button>
</td>
<td
role="gridcell"
className={styles.definitionColumn}
onClick={(event) => {
event.preventDefault();
propsOnEdit(identifier);
}}
aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDefinitionFields(variable.name)}
>
{definition}
</td>
<td role="gridcell" className={styles.column}>
<VariableCheckIndicator passed={passed} />
</td>
<td role="gridcell" className={styles.column}>
<VariableUsagesButton id={variable.id} isAdhoc={isAdHoc(variable)} usages={usagesNetwork} />
</td>
<td role="gridcell" className={styles.column}>
<IconButton
onClick={(event) => {
event.preventDefault();
reportInteraction('Duplicate variable');
propsOnDuplicate(identifier);
}}
name="copy"
title="Duplicate variable"
aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowDuplicateButtons(variable.name)}
/>
</td>
<td role="gridcell" className={styles.column}>
<IconButton
onClick={(event) => {
event.preventDefault();
reportInteraction('Delete variable');
propsOnDelete(identifier);
}}
name="trash-alt"
title="Remove variable"
aria-label={selectors.pages.Dashboard.Settings.Variables.List.tableRowRemoveButtons(variable.name)}
/>
</td>
<td role="gridcell" className={styles.column}>
<div {...provided.dragHandleProps} className={styles.dragHandle}>
<Icon name="draggabledots" size="lg" />
</div>
</td>
</tr>
)}
</Draggable>
);
}
function getDefinition(model: VariableModel): string {
let definition = '';
if (isQuery(model)) {
if (model.definition) {
definition = model.definition;
} else if (typeof model.query === 'string') {
definition = model.query;
}
} else if (hasOptions(model)) {
definition = model.query;
}
return definition;
}
interface VariableCheckIndicatorProps {
passed: boolean;
}
function VariableCheckIndicator({ passed }: VariableCheckIndicatorProps): ReactElement {
const styles = useStyles2(getStyles);
if (passed) {
return (
<Icon
name="check"
className={styles.iconPassed}
title="This variable is referenced by other variables or dashboard."
/>
);
}
return (
<Icon
name="exclamation-triangle"
className={styles.iconFailed}
title="This variable is not referenced by any variable or dashboard."
/>
);
}
function getStyles(theme: GrafanaTheme2) {
return {
dragHandle: css`
cursor: grab;
`,
column: css`
width: 1%;
`,
nameLink: css`
cursor: pointer;
color: ${theme.colors.primary.text};
`,
definitionColumn: css`
width: 100%;
max-width: 200px;
cursor: pointer;
overflow: hidden;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
white-space: nowrap;
`,
iconPassed: css`
color: ${theme.v1.palette.greenBase};
`,
iconFailed: css`
color: ${theme.v1.palette.orange};
`,
};
}
| public/app/features/variables/editor/VariableEditorListRow.tsx | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.00017862912500277162,
0.00017341732745990157,
0.0001654126972425729,
0.00017405449762009084,
0.0000037915585835435195
]
|
{
"id": 4,
"code_window": [
"\t\tcase GrafanaReceiverType:\n",
"\t\t\tfor _, gr := range r.PostableGrafanaReceivers.GrafanaManagedReceivers {\n",
"\t\t\t\tfor k, v := range gr.SecureSettings {\n",
"\t\t\t\t\tencryptedData, err := encrypt(context.Background(), []byte(v), secrets.WithoutScope())\n",
"\t\t\t\t\tif err != nil {\n",
"\t\t\t\t\t\treturn fmt.Errorf(\"failed to encrypt secure settings: %w\", err)\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tgr.SecureSettings[k] = base64.StdEncoding.EncodeToString(encryptedData)\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tencryptedData, err := encrypt(context.Background(), []byte(v))\n"
],
"file_path": "pkg/services/ngalert/api/tooling/definitions/alertmanager.go",
"type": "replace",
"edit_start_line_idx": 1189
} | ###
# set external Alertmanager
POST http://admin:admin@localhost:3000/api/v1/ngalert/admin_config
content-type: application/json
{
"alertmanagers": ["http://localhost:9093"]
}
###
GET http://admin:admin@localhost:3000/api/v1/ngalert/admin_config
###
# after a few minutes it should be discovered
GET http://admin:admin@localhost:3000/api/v1/ngalert/alertmanagers
###
# remove it
POST http://admin:admin@localhost:3000/api/v1/ngalert/admin_config
content-type: application/json
{
"alertmanagers": []
}
###
# check again
GET http://admin:admin@localhost:3000/api/v1/ngalert/alertmanagers | pkg/services/ngalert/api/test-data/admin_config.http | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.00017377562471665442,
0.00017149921040982008,
0.0001702250592643395,
0.00017049697635229677,
0.0000016134845282067545
]
|
{
"id": 4,
"code_window": [
"\t\tcase GrafanaReceiverType:\n",
"\t\t\tfor _, gr := range r.PostableGrafanaReceivers.GrafanaManagedReceivers {\n",
"\t\t\t\tfor k, v := range gr.SecureSettings {\n",
"\t\t\t\t\tencryptedData, err := encrypt(context.Background(), []byte(v), secrets.WithoutScope())\n",
"\t\t\t\t\tif err != nil {\n",
"\t\t\t\t\t\treturn fmt.Errorf(\"failed to encrypt secure settings: %w\", err)\n",
"\t\t\t\t\t}\n",
"\t\t\t\t\tgr.SecureSettings[k] = base64.StdEncoding.EncodeToString(encryptedData)\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tencryptedData, err := encrypt(context.Background(), []byte(v))\n"
],
"file_path": "pkg/services/ngalert/api/tooling/definitions/alertmanager.go",
"type": "replace",
"edit_start_line_idx": 1189
} | .grafana-options-table {
width: 100%;
th {
text-align: left;
padding: 5px 10px;
border-bottom: 4px solid $panel-bg;
}
tr td {
background-color: $list-item-bg;
padding: 5px 10px;
white-space: nowrap;
border-bottom: 4px solid $panel-bg;
&.nobg {
background-color: transparent;
}
}
.max-width-btns {
padding-right: 0px;
.btn {
box-sizing: border-box;
width: 100%;
}
}
}
.max-width {
overflow: hidden;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
white-space: nowrap;
}
.grafana-list-item {
display: block;
padding: 1px 10px;
line-height: 34px;
background-color: $list-item-bg;
margin-bottom: 4px;
cursor: pointer;
}
| public/sass/components/_tables_lists.scss | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.00017324306827504188,
0.00017046833818312734,
0.0001647071330808103,
0.00017226363706868142,
0.0000032688528790458804
]
|
{
"id": 5,
"code_window": [
"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/models\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/store\"\n",
")\n",
"\n",
"type UnknownReceiverError struct {\n",
"\tUID string\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/services/secrets\"\n"
],
"file_path": "pkg/services/ngalert/notifier/alertmanager_config.go",
"type": "add",
"edit_start_line_idx": 10
} | package notifier
import (
"context"
"errors"
"fmt"
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/store"
)
type UnknownReceiverError struct {
UID string
}
func (e UnknownReceiverError) Error() string {
return fmt.Sprintf("unknown receiver: %s", e.UID)
}
type AlertmanagerConfigRejectedError struct {
Inner error
}
func (e AlertmanagerConfigRejectedError) Error() string {
return fmt.Sprintf("failed to save and apply Alertmanager configuration: %s", e.Inner.Error())
}
type configurationStore interface {
GetLatestAlertmanagerConfiguration(ctx context.Context, query *models.GetLatestAlertmanagerConfigurationQuery) error
}
func (moa *MultiOrgAlertmanager) GetAlertmanagerConfiguration(ctx context.Context, org int64) (definitions.GettableUserConfig, error) {
query := models.GetLatestAlertmanagerConfigurationQuery{OrgID: org}
err := moa.configStore.GetLatestAlertmanagerConfiguration(ctx, &query)
if err != nil {
return definitions.GettableUserConfig{}, fmt.Errorf("failed to get latest configuration: %w", err)
}
cfg, err := Load([]byte(query.Result.AlertmanagerConfiguration))
if err != nil {
return definitions.GettableUserConfig{}, fmt.Errorf("failed to unmarshal alertmanager configuration: %w", err)
}
result := definitions.GettableUserConfig{
TemplateFiles: cfg.TemplateFiles,
AlertmanagerConfig: definitions.GettableApiAlertingConfig{
Config: cfg.AlertmanagerConfig.Config,
},
}
for _, recv := range cfg.AlertmanagerConfig.Receivers {
receivers := make([]*definitions.GettableGrafanaReceiver, 0, len(recv.PostableGrafanaReceivers.GrafanaManagedReceivers))
for _, pr := range recv.PostableGrafanaReceivers.GrafanaManagedReceivers {
secureFields := make(map[string]bool, len(pr.SecureSettings))
for k := range pr.SecureSettings {
decryptedValue, err := moa.Crypto.getDecryptedSecret(pr, k)
if err != nil {
return definitions.GettableUserConfig{}, fmt.Errorf("failed to decrypt stored secure setting: %w", err)
}
if decryptedValue == "" {
continue
}
secureFields[k] = true
}
gr := definitions.GettableGrafanaReceiver{
UID: pr.UID,
Name: pr.Name,
Type: pr.Type,
DisableResolveMessage: pr.DisableResolveMessage,
Settings: pr.Settings,
SecureFields: secureFields,
}
receivers = append(receivers, &gr)
}
gettableApiReceiver := definitions.GettableApiReceiver{
GettableGrafanaReceivers: definitions.GettableGrafanaReceivers{
GrafanaManagedReceivers: receivers,
},
}
gettableApiReceiver.Name = recv.Name
result.AlertmanagerConfig.Receivers = append(result.AlertmanagerConfig.Receivers, &gettableApiReceiver)
}
result, err = moa.mergeProvenance(ctx, result, org)
if err != nil {
return definitions.GettableUserConfig{}, err
}
return result, nil
}
func (moa *MultiOrgAlertmanager) ApplyAlertmanagerConfiguration(ctx context.Context, org int64, config definitions.PostableUserConfig) error {
// Get the last known working configuration
query := models.GetLatestAlertmanagerConfigurationQuery{OrgID: org}
if err := moa.configStore.GetLatestAlertmanagerConfiguration(ctx, &query); err != nil {
// If we don't have a configuration there's nothing for us to know and we should just continue saving the new one
if !errors.Is(err, store.ErrNoAlertmanagerConfiguration) {
return fmt.Errorf("failed to get latest configuration %w", err)
}
}
if err := moa.Crypto.LoadSecureSettings(ctx, org, config.AlertmanagerConfig.Receivers); err != nil {
return err
}
if err := config.ProcessConfig(moa.Crypto.Encrypt); err != nil {
return fmt.Errorf("failed to post process Alertmanager configuration: %w", err)
}
am, err := moa.AlertmanagerFor(org)
if err != nil {
// It's okay if the alertmanager isn't ready yet, we're changing its config anyway.
if !errors.Is(err, ErrAlertmanagerNotReady) {
return err
}
}
if err := am.SaveAndApplyConfig(ctx, &config); err != nil {
moa.logger.Error("unable to save and apply alertmanager configuration", "error", err)
return AlertmanagerConfigRejectedError{err}
}
return nil
}
func (moa *MultiOrgAlertmanager) mergeProvenance(ctx context.Context, config definitions.GettableUserConfig, org int64) (definitions.GettableUserConfig, error) {
if config.AlertmanagerConfig.Route != nil {
provenance, err := moa.ProvStore.GetProvenance(ctx, config.AlertmanagerConfig.Route, org)
if err != nil {
return definitions.GettableUserConfig{}, err
}
config.AlertmanagerConfig.Route.Provenance = definitions.Provenance(provenance)
}
cp := definitions.EmbeddedContactPoint{}
cpProvs, err := moa.ProvStore.GetProvenances(ctx, org, cp.ResourceType())
if err != nil {
return definitions.GettableUserConfig{}, err
}
for _, receiver := range config.AlertmanagerConfig.Receivers {
for _, contactPoint := range receiver.GrafanaManagedReceivers {
if provenance, exists := cpProvs[contactPoint.UID]; exists {
contactPoint.Provenance = definitions.Provenance(provenance)
}
}
}
tmpl := definitions.NotificationTemplate{}
tmplProvs, err := moa.ProvStore.GetProvenances(ctx, org, tmpl.ResourceType())
if err != nil {
return definitions.GettableUserConfig{}, nil
}
config.TemplateFileProvenances = make(map[string]definitions.Provenance, len(tmplProvs))
for key, provenance := range tmplProvs {
config.TemplateFileProvenances[key] = definitions.Provenance(provenance)
}
mt := definitions.MuteTimeInterval{}
mtProvs, err := moa.ProvStore.GetProvenances(ctx, org, mt.ResourceType())
if err != nil {
return definitions.GettableUserConfig{}, nil
}
config.AlertmanagerConfig.MuteTimeProvenances = make(map[string]definitions.Provenance, len(mtProvs))
for key, provenance := range mtProvs {
config.AlertmanagerConfig.MuteTimeProvenances[key] = definitions.Provenance(provenance)
}
return config, nil
}
| pkg/services/ngalert/notifier/alertmanager_config.go | 1 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.9952333569526672,
0.06212850287556648,
0.00016519644123036414,
0.000174323286046274,
0.23352579772472382
]
|
{
"id": 5,
"code_window": [
"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/models\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/store\"\n",
")\n",
"\n",
"type UnknownReceiverError struct {\n",
"\tUID string\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/services/secrets\"\n"
],
"file_path": "pkg/services/ngalert/notifier/alertmanager_config.go",
"type": "add",
"edit_start_line_idx": 10
} | {
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": "-- Grafana --",
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"target": {
"limit": 100,
"matchAny": false,
"tags": [],
"type": "dashboard"
},
"type": "dashboard"
}
]
},
"editable": true,
"gnetId": null,
"graphTooltip": 0,
"id": 321,
"links": [],
"liveNow": false,
"panels": [
{
"datasource": null,
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
}
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 0
},
"id": 6,
"options": {
"reduceOptions": {
"calcs": ["lastNotNull"],
"fields": "",
"values": false
},
"showThresholdLabels": false,
"showThresholdMarkers": true,
"text": {}
},
"pluginVersion": "8.3.0-pre",
"title": "Gauge Example",
"type": "gauge"
},
{
"datasource": null,
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
}
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 8
},
"id": 4,
"options": {
"colorMode": "value",
"graphMode": "area",
"justifyMode": "auto",
"orientation": "auto",
"reduceOptions": {
"calcs": ["lastNotNull"],
"fields": "",
"values": false
},
"text": {},
"textMode": "auto"
},
"pluginVersion": "8.3.0-pre",
"title": "Stat",
"type": "stat"
},
{
"datasource": null,
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 0,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 5,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "auto",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
}
},
"overrides": []
},
"gridPos": {
"h": 9,
"w": 12,
"x": 0,
"y": 16
},
"id": 2,
"options": {
"legend": {
"calcs": [],
"displayMode": "list",
"placement": "bottom"
},
"tooltip": {
"mode": "single"
}
},
"title": "Time series example",
"type": "timeseries"
}
],
"refresh": false,
"schemaVersion": 31,
"style": "dark",
"tags": [],
"templating": {
"list": []
},
"time": {
"from": "2021-09-01T04:00:00.000Z",
"to": "2021-09-15T04:00:00.000Z"
},
"timepicker": {},
"timezone": "",
"title": "E2E Test - Dashboard Search",
"uid": "kquZN5H7k",
"version": 4
}
| e2e/dashboards/DashboardSearchTest.json | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.00017551011114846915,
0.00017272416152991354,
0.00016765049076639116,
0.00017275965365115553,
0.0000015891818065938423
]
|
{
"id": 5,
"code_window": [
"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/models\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/store\"\n",
")\n",
"\n",
"type UnknownReceiverError struct {\n",
"\tUID string\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/services/secrets\"\n"
],
"file_path": "pkg/services/ngalert/notifier/alertmanager_config.go",
"type": "add",
"edit_start_line_idx": 10
} | import { DataFrame, DataQuery, DataQueryError, DataTopic } from '@grafana/data';
export const SHARED_DASHBOARD_QUERY = '-- Dashboard --';
export interface DashboardQuery extends DataQuery {
panelId?: number;
withTransforms?: boolean;
topic?: DataTopic;
}
export type ResultInfo = {
img: string; // The Datasource
refId: string;
query: string; // As text
data: DataFrame[];
error?: DataQueryError;
};
| public/app/plugins/datasource/dashboard/types.ts | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.0002074067306239158,
0.0001892943400889635,
0.00017118196410592645,
0.0001892943400889635,
0.00001811238325899467
]
|
{
"id": 5,
"code_window": [
"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/models\"\n",
"\t\"github.com/grafana/grafana/pkg/services/ngalert/store\"\n",
")\n",
"\n",
"type UnknownReceiverError struct {\n",
"\tUID string\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"github.com/grafana/grafana/pkg/services/secrets\"\n"
],
"file_path": "pkg/services/ngalert/notifier/alertmanager_config.go",
"type": "add",
"edit_start_line_idx": 10
} | <svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M8.5,10a2,2,0,1,0,2,2A2,2,0,0,0,8.5,10Zm0,7a2,2,0,1,0,2,2A2,2,0,0,0,8.5,17Zm7-10a2,2,0,1,0-2-2A2,2,0,0,0,15.5,7Zm-7-4a2,2,0,1,0,2,2A2,2,0,0,0,8.5,3Zm7,14a2,2,0,1,0,2,2A2,2,0,0,0,15.5,17Zm0-7a2,2,0,1,0,2,2A2,2,0,0,0,15.5,10Z"/></svg> | public/img/icons/unicons/draggabledots.svg | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.0001753478718455881,
0.0001753478718455881,
0.0001753478718455881,
0.0001753478718455881,
0
]
|
{
"id": 6,
"code_window": [
"\t\treturn err\n",
"\t}\n",
"\n",
"\tif err := config.ProcessConfig(moa.Crypto.Encrypt); err != nil {\n",
"\t\treturn fmt.Errorf(\"failed to post process Alertmanager configuration: %w\", err)\n",
"\t}\n",
"\n",
"\tam, err := moa.AlertmanagerFor(org)\n",
"\tif err != nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif err := config.ProcessConfig(func(ctx context.Context, payload []byte) ([]byte, error) {\n",
"\t\treturn moa.Crypto.Encrypt(ctx, payload, secrets.WithoutScope())\n",
"\t}); err != nil {\n"
],
"file_path": "pkg/services/ngalert/notifier/alertmanager_config.go",
"type": "replace",
"edit_start_line_idx": 105
} | package notifier
import (
"context"
"errors"
"fmt"
"github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/store"
)
type UnknownReceiverError struct {
UID string
}
func (e UnknownReceiverError) Error() string {
return fmt.Sprintf("unknown receiver: %s", e.UID)
}
type AlertmanagerConfigRejectedError struct {
Inner error
}
func (e AlertmanagerConfigRejectedError) Error() string {
return fmt.Sprintf("failed to save and apply Alertmanager configuration: %s", e.Inner.Error())
}
type configurationStore interface {
GetLatestAlertmanagerConfiguration(ctx context.Context, query *models.GetLatestAlertmanagerConfigurationQuery) error
}
func (moa *MultiOrgAlertmanager) GetAlertmanagerConfiguration(ctx context.Context, org int64) (definitions.GettableUserConfig, error) {
query := models.GetLatestAlertmanagerConfigurationQuery{OrgID: org}
err := moa.configStore.GetLatestAlertmanagerConfiguration(ctx, &query)
if err != nil {
return definitions.GettableUserConfig{}, fmt.Errorf("failed to get latest configuration: %w", err)
}
cfg, err := Load([]byte(query.Result.AlertmanagerConfiguration))
if err != nil {
return definitions.GettableUserConfig{}, fmt.Errorf("failed to unmarshal alertmanager configuration: %w", err)
}
result := definitions.GettableUserConfig{
TemplateFiles: cfg.TemplateFiles,
AlertmanagerConfig: definitions.GettableApiAlertingConfig{
Config: cfg.AlertmanagerConfig.Config,
},
}
for _, recv := range cfg.AlertmanagerConfig.Receivers {
receivers := make([]*definitions.GettableGrafanaReceiver, 0, len(recv.PostableGrafanaReceivers.GrafanaManagedReceivers))
for _, pr := range recv.PostableGrafanaReceivers.GrafanaManagedReceivers {
secureFields := make(map[string]bool, len(pr.SecureSettings))
for k := range pr.SecureSettings {
decryptedValue, err := moa.Crypto.getDecryptedSecret(pr, k)
if err != nil {
return definitions.GettableUserConfig{}, fmt.Errorf("failed to decrypt stored secure setting: %w", err)
}
if decryptedValue == "" {
continue
}
secureFields[k] = true
}
gr := definitions.GettableGrafanaReceiver{
UID: pr.UID,
Name: pr.Name,
Type: pr.Type,
DisableResolveMessage: pr.DisableResolveMessage,
Settings: pr.Settings,
SecureFields: secureFields,
}
receivers = append(receivers, &gr)
}
gettableApiReceiver := definitions.GettableApiReceiver{
GettableGrafanaReceivers: definitions.GettableGrafanaReceivers{
GrafanaManagedReceivers: receivers,
},
}
gettableApiReceiver.Name = recv.Name
result.AlertmanagerConfig.Receivers = append(result.AlertmanagerConfig.Receivers, &gettableApiReceiver)
}
result, err = moa.mergeProvenance(ctx, result, org)
if err != nil {
return definitions.GettableUserConfig{}, err
}
return result, nil
}
func (moa *MultiOrgAlertmanager) ApplyAlertmanagerConfiguration(ctx context.Context, org int64, config definitions.PostableUserConfig) error {
// Get the last known working configuration
query := models.GetLatestAlertmanagerConfigurationQuery{OrgID: org}
if err := moa.configStore.GetLatestAlertmanagerConfiguration(ctx, &query); err != nil {
// If we don't have a configuration there's nothing for us to know and we should just continue saving the new one
if !errors.Is(err, store.ErrNoAlertmanagerConfiguration) {
return fmt.Errorf("failed to get latest configuration %w", err)
}
}
if err := moa.Crypto.LoadSecureSettings(ctx, org, config.AlertmanagerConfig.Receivers); err != nil {
return err
}
if err := config.ProcessConfig(moa.Crypto.Encrypt); err != nil {
return fmt.Errorf("failed to post process Alertmanager configuration: %w", err)
}
am, err := moa.AlertmanagerFor(org)
if err != nil {
// It's okay if the alertmanager isn't ready yet, we're changing its config anyway.
if !errors.Is(err, ErrAlertmanagerNotReady) {
return err
}
}
if err := am.SaveAndApplyConfig(ctx, &config); err != nil {
moa.logger.Error("unable to save and apply alertmanager configuration", "error", err)
return AlertmanagerConfigRejectedError{err}
}
return nil
}
func (moa *MultiOrgAlertmanager) mergeProvenance(ctx context.Context, config definitions.GettableUserConfig, org int64) (definitions.GettableUserConfig, error) {
if config.AlertmanagerConfig.Route != nil {
provenance, err := moa.ProvStore.GetProvenance(ctx, config.AlertmanagerConfig.Route, org)
if err != nil {
return definitions.GettableUserConfig{}, err
}
config.AlertmanagerConfig.Route.Provenance = definitions.Provenance(provenance)
}
cp := definitions.EmbeddedContactPoint{}
cpProvs, err := moa.ProvStore.GetProvenances(ctx, org, cp.ResourceType())
if err != nil {
return definitions.GettableUserConfig{}, err
}
for _, receiver := range config.AlertmanagerConfig.Receivers {
for _, contactPoint := range receiver.GrafanaManagedReceivers {
if provenance, exists := cpProvs[contactPoint.UID]; exists {
contactPoint.Provenance = definitions.Provenance(provenance)
}
}
}
tmpl := definitions.NotificationTemplate{}
tmplProvs, err := moa.ProvStore.GetProvenances(ctx, org, tmpl.ResourceType())
if err != nil {
return definitions.GettableUserConfig{}, nil
}
config.TemplateFileProvenances = make(map[string]definitions.Provenance, len(tmplProvs))
for key, provenance := range tmplProvs {
config.TemplateFileProvenances[key] = definitions.Provenance(provenance)
}
mt := definitions.MuteTimeInterval{}
mtProvs, err := moa.ProvStore.GetProvenances(ctx, org, mt.ResourceType())
if err != nil {
return definitions.GettableUserConfig{}, nil
}
config.AlertmanagerConfig.MuteTimeProvenances = make(map[string]definitions.Provenance, len(mtProvs))
for key, provenance := range mtProvs {
config.AlertmanagerConfig.MuteTimeProvenances[key] = definitions.Provenance(provenance)
}
return config, nil
}
| pkg/services/ngalert/notifier/alertmanager_config.go | 1 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.9988409876823425,
0.17628012597560883,
0.00017186198965646327,
0.002973234048113227,
0.37377840280532837
]
|
{
"id": 6,
"code_window": [
"\t\treturn err\n",
"\t}\n",
"\n",
"\tif err := config.ProcessConfig(moa.Crypto.Encrypt); err != nil {\n",
"\t\treturn fmt.Errorf(\"failed to post process Alertmanager configuration: %w\", err)\n",
"\t}\n",
"\n",
"\tam, err := moa.AlertmanagerFor(org)\n",
"\tif err != nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif err := config.ProcessConfig(func(ctx context.Context, payload []byte) ([]byte, error) {\n",
"\t\treturn moa.Crypto.Encrypt(ctx, payload, secrets.WithoutScope())\n",
"\t}); err != nil {\n"
],
"file_path": "pkg/services/ngalert/notifier/alertmanager_config.go",
"type": "replace",
"edit_start_line_idx": 105
} | import { render, screen } from '@testing-library/react';
import React from 'react';
import { LogLevel, LogRowModel, MutableDataFrame } from '@grafana/data';
import { LiveLogsWithTheme } from './LiveLogs';
const setup = (rows: LogRowModel[]) =>
render(
<LiveLogsWithTheme
logRows={rows}
timeZone={'utc'}
stopLive={() => {}}
onPause={() => {}}
onResume={() => {}}
isPaused={true}
/>
);
const makeLog = (overrides: Partial<LogRowModel>): LogRowModel => {
const uid = overrides.uid || '1';
const entry = `log message ${uid}`;
return {
uid,
entryFieldIndex: 0,
rowIndex: 0,
dataFrame: new MutableDataFrame(),
logLevel: LogLevel.debug,
entry,
hasAnsi: false,
hasUnescapedContent: false,
labels: {},
raw: entry,
timeFromNow: '',
timeEpochMs: 1,
timeEpochNs: '1000000',
timeLocal: '',
timeUtc: '',
...overrides,
};
};
describe('LiveLogs', () => {
it('renders logs', () => {
setup([makeLog({ uid: '1' }), makeLog({ uid: '2' }), makeLog({ uid: '3' })]);
expect(screen.getByRole('cell', { name: 'log message 1' })).toBeInTheDocument();
expect(screen.getByRole('cell', { name: 'log message 2' })).toBeInTheDocument();
expect(screen.getByRole('cell', { name: 'log message 3' })).toBeInTheDocument();
});
it('renders new logs only when not paused', () => {
const { rerender } = setup([makeLog({ uid: '1' }), makeLog({ uid: '2' }), makeLog({ uid: '3' })]);
rerender(
<LiveLogsWithTheme
logRows={[makeLog({ uid: '4' }), makeLog({ uid: '5' }), makeLog({ uid: '6' })]}
timeZone={'utc'}
stopLive={() => {}}
onPause={() => {}}
onResume={() => {}}
isPaused={true}
/>
);
expect(screen.getByRole('cell', { name: 'log message 1' })).toBeInTheDocument();
expect(screen.getByRole('cell', { name: 'log message 2' })).toBeInTheDocument();
expect(screen.getByRole('cell', { name: 'log message 3' })).toBeInTheDocument();
expect(screen.queryByRole('cell', { name: 'log message 4' })).not.toBeInTheDocument();
expect(screen.queryByRole('cell', { name: 'log message 5' })).not.toBeInTheDocument();
expect(screen.queryByRole('cell', { name: 'log message 6' })).not.toBeInTheDocument();
rerender(
<LiveLogsWithTheme
logRows={[makeLog({ uid: '4' }), makeLog({ uid: '5' }), makeLog({ uid: '6' })]}
timeZone={'utc'}
stopLive={() => {}}
onPause={() => {}}
onResume={() => {}}
isPaused={false}
/>
);
expect(screen.getByRole('cell', { name: 'log message 4' })).toBeInTheDocument();
expect(screen.getByRole('cell', { name: 'log message 5' })).toBeInTheDocument();
expect(screen.getByRole('cell', { name: 'log message 6' })).toBeInTheDocument();
});
it('renders ansi logs', () => {
setup([
makeLog({ uid: '1' }),
makeLog({ hasAnsi: true, raw: 'log message \u001B[31m2\u001B[0m', uid: '2' }),
makeLog({ hasAnsi: true, raw: 'log message \u001B[33m3\u001B[0m', uid: '3' }),
]);
expect(screen.getByRole('cell', { name: 'log message 1' })).toBeInTheDocument();
expect(screen.getByRole('cell', { name: 'log message 2' })).toBeInTheDocument();
expect(screen.getByRole('cell', { name: 'log message 3' })).toBeInTheDocument();
const logList = screen.getAllByTestId('ansiLogLine');
expect(logList).toHaveLength(2);
expect(logList[0]).toHaveAttribute('style', 'color: rgb(204, 0, 0);');
expect(logList[1]).toHaveAttribute('style', 'color: rgb(204, 102, 0);');
});
});
| public/app/features/explore/LiveLogs.test.tsx | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.00017988745821639895,
0.0001758905127644539,
0.00017116581148002297,
0.00017611242947168648,
0.000002144433210560237
]
|
{
"id": 6,
"code_window": [
"\t\treturn err\n",
"\t}\n",
"\n",
"\tif err := config.ProcessConfig(moa.Crypto.Encrypt); err != nil {\n",
"\t\treturn fmt.Errorf(\"failed to post process Alertmanager configuration: %w\", err)\n",
"\t}\n",
"\n",
"\tam, err := moa.AlertmanagerFor(org)\n",
"\tif err != nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif err := config.ProcessConfig(func(ctx context.Context, payload []byte) ([]byte, error) {\n",
"\t\treturn moa.Crypto.Encrypt(ctx, payload, secrets.WithoutScope())\n",
"\t}); err != nil {\n"
],
"file_path": "pkg/services/ngalert/notifier/alertmanager_config.go",
"type": "replace",
"edit_start_line_idx": 105
} | import { GrafanaThemeType } from '@grafana/data';
/**
* @deprecated
*/
export type VariantDescriptor = { [key in GrafanaThemeType]: string | number };
/**
* @deprecated use theme.isLight ? or theme.isDark instead
*/
export const selectThemeVariant = (variants: VariantDescriptor, currentTheme?: GrafanaThemeType) => {
return variants[currentTheme || GrafanaThemeType.Dark];
};
| packages/grafana-ui/src/themes/selectThemeVariant.ts | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.00017701076285447925,
0.00017617781122680753,
0.00017534485959913582,
0.00017617781122680753,
8.329516276717186e-7
]
|
{
"id": 6,
"code_window": [
"\t\treturn err\n",
"\t}\n",
"\n",
"\tif err := config.ProcessConfig(moa.Crypto.Encrypt); err != nil {\n",
"\t\treturn fmt.Errorf(\"failed to post process Alertmanager configuration: %w\", err)\n",
"\t}\n",
"\n",
"\tam, err := moa.AlertmanagerFor(org)\n",
"\tif err != nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif err := config.ProcessConfig(func(ctx context.Context, payload []byte) ([]byte, error) {\n",
"\t\treturn moa.Crypto.Encrypt(ctx, payload, secrets.WithoutScope())\n",
"\t}); err != nil {\n"
],
"file_path": "pkg/services/ngalert/notifier/alertmanager_config.go",
"type": "replace",
"edit_start_line_idx": 105
} | package api
import (
"context"
"encoding/json"
"fmt"
"net/http"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/api/routing"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/db/dbtest"
"github.com/grafana/grafana/pkg/infra/usagestats"
acmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
"github.com/grafana/grafana/pkg/services/login"
"github.com/grafana/grafana/pkg/services/login/authinfoservice"
authinfostore "github.com/grafana/grafana/pkg/services/login/authinfoservice/database"
"github.com/grafana/grafana/pkg/services/login/logintest"
"github.com/grafana/grafana/pkg/services/org/orgimpl"
"github.com/grafana/grafana/pkg/services/quota/quotatest"
"github.com/grafana/grafana/pkg/services/searchusers"
"github.com/grafana/grafana/pkg/services/searchusers/filters"
"github.com/grafana/grafana/pkg/services/secrets/database"
secretsManager "github.com/grafana/grafana/pkg/services/secrets/manager"
"github.com/grafana/grafana/pkg/services/supportbundles/supportbundlestest"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/services/user/userimpl"
"github.com/grafana/grafana/pkg/services/user/usertest"
"github.com/grafana/grafana/pkg/setting"
)
func TestUserAPIEndpoint_userLoggedIn(t *testing.T) {
settings := setting.NewCfg()
sqlStore := db.InitTestDB(t)
hs := &HTTPServer{
Cfg: settings,
SQLStore: sqlStore,
AccessControl: acmock.New(),
}
mockResult := user.SearchUserQueryResult{
Users: []*user.UserSearchHitDTO{
{Name: "user1"},
{Name: "user2"},
},
TotalCount: 2,
}
mock := dbtest.NewFakeDB()
userMock := usertest.NewUserServiceFake()
loggedInUserScenario(t, "When calling GET on", "api/users/1", "api/users/:id", func(sc *scenarioContext) {
fakeNow := time.Date(2019, 2, 11, 17, 30, 40, 0, time.UTC)
secretsService := secretsManager.SetupTestService(t, database.ProvideSecretsStore(sqlStore))
authInfoStore := authinfostore.ProvideAuthInfoStore(sqlStore, secretsService, userMock)
srv := authinfoservice.ProvideAuthInfoService(
&authinfoservice.OSSUserProtectionImpl{},
authInfoStore,
&usagestats.UsageStatsMock{},
)
hs.authInfoService = srv
orgSvc, err := orgimpl.ProvideService(sqlStore, sqlStore.Cfg, quotatest.New(false, nil))
require.NoError(t, err)
userSvc, err := userimpl.ProvideService(sqlStore, orgSvc, sc.cfg, nil, nil, quotatest.New(false, nil), supportbundlestest.NewFakeBundleService())
require.NoError(t, err)
hs.userService = userSvc
createUserCmd := user.CreateUserCommand{
Email: fmt.Sprint("user", "@test.com"),
Name: "user",
Login: "loginuser",
IsAdmin: true,
}
usr, err := userSvc.Create(context.Background(), &createUserCmd)
require.NoError(t, err)
sc.handlerFunc = hs.GetUserByID
token := &oauth2.Token{
AccessToken: "testaccess",
RefreshToken: "testrefresh",
Expiry: time.Now(),
TokenType: "Bearer",
}
idToken := "testidtoken"
token = token.WithExtra(map[string]interface{}{"id_token": idToken})
userlogin := "loginuser"
query := &login.GetUserByAuthInfoQuery{AuthModule: "test", AuthId: "test", UserLookupParams: login.UserLookupParams{Login: &userlogin}}
cmd := &login.UpdateAuthInfoCommand{
UserId: usr.ID,
AuthId: query.AuthId,
AuthModule: query.AuthModule,
OAuthToken: token,
}
err = srv.UpdateAuthInfo(context.Background(), cmd)
require.NoError(t, err)
avatarUrl := dtos.GetGravatarUrl("@test.com")
sc.fakeReqWithParams("GET", sc.url, map[string]string{"id": fmt.Sprintf("%v", usr.ID)}).exec()
expected := user.UserProfileDTO{
ID: 1,
Email: "[email protected]",
Name: "user",
Login: "loginuser",
OrgID: 1,
IsGrafanaAdmin: true,
AuthLabels: []string{},
CreatedAt: fakeNow,
UpdatedAt: fakeNow,
AvatarURL: avatarUrl,
}
var resp user.UserProfileDTO
require.Equal(t, http.StatusOK, sc.resp.Code)
err = json.Unmarshal(sc.resp.Body.Bytes(), &resp)
require.NoError(t, err)
resp.CreatedAt = fakeNow
resp.UpdatedAt = fakeNow
resp.AvatarURL = avatarUrl
require.EqualValues(t, expected, resp)
}, mock)
loggedInUserScenario(t, "When calling GET on", "/api/users/lookup", "/api/users/lookup", func(sc *scenarioContext) {
createUserCmd := user.CreateUserCommand{
Email: fmt.Sprint("admin", "@test.com"),
Name: "admin",
Login: "admin",
IsAdmin: true,
}
orgSvc, err := orgimpl.ProvideService(sqlStore, sqlStore.Cfg, quotatest.New(false, nil))
require.NoError(t, err)
userSvc, err := userimpl.ProvideService(sqlStore, orgSvc, sc.cfg, nil, nil, quotatest.New(false, nil), supportbundlestest.NewFakeBundleService())
require.NoError(t, err)
_, err = userSvc.Create(context.Background(), &createUserCmd)
require.Nil(t, err)
sc.handlerFunc = hs.GetUserByLoginOrEmail
userMock := usertest.NewUserServiceFake()
userMock.ExpectedUser = &user.User{ID: 2}
sc.userService = userMock
hs.userService = userMock
sc.fakeReqWithParams("GET", sc.url, map[string]string{"loginOrEmail": "[email protected]"}).exec()
var resp user.UserProfileDTO
require.Equal(t, http.StatusOK, sc.resp.Code)
err = json.Unmarshal(sc.resp.Body.Bytes(), &resp)
require.NoError(t, err)
}, mock)
loggedInUserScenario(t, "When calling GET on", "/api/users", "/api/users", func(sc *scenarioContext) {
userMock.ExpectedSearchUsers = mockResult
searchUsersService := searchusers.ProvideUsersService(filters.ProvideOSSSearchUserFilter(), userMock)
sc.handlerFunc = searchUsersService.SearchUsers
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes())
require.NoError(t, err)
assert.Equal(t, 2, len(respJSON.MustArray()))
}, mock)
loggedInUserScenario(t, "When calling GET with page and limit querystring parameters on", "/api/users", "/api/users", func(sc *scenarioContext) {
userMock.ExpectedSearchUsers = mockResult
searchUsersService := searchusers.ProvideUsersService(filters.ProvideOSSSearchUserFilter(), userMock)
sc.handlerFunc = searchUsersService.SearchUsers
sc.fakeReqWithParams("GET", sc.url, map[string]string{"perpage": "10", "page": "2"}).exec()
respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes())
require.NoError(t, err)
assert.Equal(t, 2, len(respJSON.MustArray()))
}, mock)
loggedInUserScenario(t, "When calling GET on", "/api/users/search", "/api/users/search", func(sc *scenarioContext) {
userMock.ExpectedSearchUsers = mockResult
searchUsersService := searchusers.ProvideUsersService(filters.ProvideOSSSearchUserFilter(), userMock)
sc.handlerFunc = searchUsersService.SearchUsersWithPaging
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes())
require.NoError(t, err)
assert.Equal(t, 1, respJSON.Get("page").MustInt())
assert.Equal(t, 1000, respJSON.Get("perPage").MustInt())
assert.Equal(t, 2, respJSON.Get("totalCount").MustInt())
assert.Equal(t, 2, len(respJSON.Get("users").MustArray()))
}, mock)
loggedInUserScenario(t, "When calling GET with page and perpage querystring parameters on", "/api/users/search", "/api/users/search", func(sc *scenarioContext) {
userMock.ExpectedSearchUsers = mockResult
searchUsersService := searchusers.ProvideUsersService(filters.ProvideOSSSearchUserFilter(), userMock)
sc.handlerFunc = searchUsersService.SearchUsersWithPaging
sc.fakeReqWithParams("GET", sc.url, map[string]string{"perpage": "10", "page": "2"}).exec()
respJSON, err := simplejson.NewJson(sc.resp.Body.Bytes())
require.NoError(t, err)
assert.Equal(t, 2, respJSON.Get("page").MustInt())
assert.Equal(t, 10, respJSON.Get("perPage").MustInt())
}, mock)
}
func TestHTTPServer_UpdateUser(t *testing.T) {
settings := setting.NewCfg()
sqlStore := db.InitTestDB(t)
hs := &HTTPServer{
Cfg: settings,
SQLStore: sqlStore,
AccessControl: acmock.New(),
}
updateUserCommand := user.UpdateUserCommand{
Email: fmt.Sprint("admin", "@test.com"),
Name: "admin",
Login: "admin",
UserID: 1,
}
updateUserScenario(t, updateUserContext{
desc: "Should return 403 when the current User is an external user",
url: "/api/users/1",
routePattern: "/api/users/:id",
cmd: updateUserCommand,
fn: func(sc *scenarioContext) {
sc.authInfoService.ExpectedUserAuth = &login.UserAuth{}
sc.fakeReqWithParams("PUT", sc.url, map[string]string{"id": "1"}).exec()
assert.Equal(t, 403, sc.resp.Code)
},
}, hs)
}
type updateUserContext struct {
desc string
url string
routePattern string
cmd user.UpdateUserCommand
fn scenarioFunc
}
func updateUserScenario(t *testing.T, ctx updateUserContext, hs *HTTPServer) {
t.Run(fmt.Sprintf("%s %s", ctx.desc, ctx.url), func(t *testing.T) {
sc := setupScenarioContext(t, ctx.url)
sc.authInfoService = &logintest.AuthInfoServiceFake{}
hs.authInfoService = sc.authInfoService
sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(ctx.cmd)
c.Req.Header.Add("Content-Type", "application/json")
sc.context = c
sc.context.OrgID = testOrgID
sc.context.UserID = testUserID
return hs.UpdateUser(c)
})
sc.m.Put(ctx.routePattern, sc.defaultHandler)
ctx.fn(sc)
})
}
func TestHTTPServer_UpdateSignedInUser(t *testing.T) {
settings := setting.NewCfg()
sqlStore := db.InitTestDB(t)
hs := &HTTPServer{
Cfg: settings,
SQLStore: sqlStore,
AccessControl: acmock.New(),
}
updateUserCommand := user.UpdateUserCommand{
Email: fmt.Sprint("admin", "@test.com"),
Name: "admin",
Login: "admin",
UserID: 1,
}
updateSignedInUserScenario(t, updateUserContext{
desc: "Should return 403 when the current User is an external user",
url: "/api/users/",
routePattern: "/api/users/",
cmd: updateUserCommand,
fn: func(sc *scenarioContext) {
sc.authInfoService.ExpectedUserAuth = &login.UserAuth{}
sc.fakeReqWithParams("PUT", sc.url, map[string]string{"id": "1"}).exec()
assert.Equal(t, 403, sc.resp.Code)
},
}, hs)
}
func updateSignedInUserScenario(t *testing.T, ctx updateUserContext, hs *HTTPServer) {
t.Run(fmt.Sprintf("%s %s", ctx.desc, ctx.url), func(t *testing.T) {
sc := setupScenarioContext(t, ctx.url)
sc.authInfoService = &logintest.AuthInfoServiceFake{}
hs.authInfoService = sc.authInfoService
sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response {
c.Req.Body = mockRequestBody(ctx.cmd)
c.Req.Header.Add("Content-Type", "application/json")
sc.context = c
sc.context.OrgID = testOrgID
sc.context.UserID = testUserID
return hs.UpdateSignedInUser(c)
})
sc.m.Put(ctx.routePattern, sc.defaultHandler)
ctx.fn(sc)
})
}
| pkg/api/user_test.go | 0 | https://github.com/grafana/grafana/commit/ec4152c7e58533ec55d06bb60981642966d9e3bd | [
0.0006713012116961181,
0.00019733856606762856,
0.00015850966155994684,
0.00017052153998520225,
0.00011481465480756015
]
|
{
"id": 0,
"code_window": [
"\t\t// Dashboard\n",
"\t\tapiRoute.Group(\"/dashboards\", func(dashboardRoute RouteRegister) {\n",
"\t\t\tdashboardRoute.Get(\"/uid/:uid\", wrap(GetDashboard))\n",
"\n",
"\t\t\tdashboardRoute.Get(\"/db/:slug\", wrap(GetDashboard))\n",
"\t\t\tdashboardRoute.Get(\"/db/:slug/uid\", wrap(GetDashboardUidBySlug))\n",
"\t\t\tdashboardRoute.Delete(\"/db/:slug\", reqEditorRole, wrap(DeleteDashboard))\n",
"\n",
"\t\t\tdashboardRoute.Post(\"/calculate-diff\", bind(dtos.CalculateDiffOptions{}), wrap(CalculateDashboardDiff))\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/api.go",
"type": "replace",
"edit_start_line_idx": 247
} | package api
import (
"encoding/json"
"path/filepath"
"testing"
macaron "gopkg.in/macaron.v1"
"github.com/go-macaron/session"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
type fakeDashboardRepo struct {
inserted []*dashboards.SaveDashboardItem
getDashboard []*m.Dashboard
}
func (repo *fakeDashboardRepo) SaveDashboard(json *dashboards.SaveDashboardItem) (*m.Dashboard, error) {
repo.inserted = append(repo.inserted, json)
return json.Dashboard, nil
}
var fakeRepo *fakeDashboardRepo
func TestDashboardApiEndpoint(t *testing.T) {
Convey("Given a dashboard with a parent folder which does not have an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = false
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
viewerRole := m.ROLE_VIEWER
editorRole := m.ROLE_EDITOR
aclMockResp := []*m.DashboardAclInfoDTO{
{Role: &viewerRole, Permission: m.PERMISSION_VIEW},
{Role: &editorRole, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
"id": fakeDash.Id,
}),
}
Convey("When user is an Org Viewer", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
Convey("When saving a dashboard folder in another folder", func() {
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
query.Result.IsFolder = true
return nil
})
invalidCmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
IsFolder: true,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("Should return an error", func() {
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, invalidCmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 400)
})
})
})
})
})
Convey("Given a dashboard with a parent folder which has an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = true
setting.ViewersCanEdit = false
aclMockResp := []*m.DashboardAclInfoDTO{
{
DashboardId: 1,
Permission: m.PERMISSION_EDIT,
UserId: 200,
},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"id": fakeDash.Id,
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("When user is an Org Viewer and has no permissions for this dashboard", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor and has no permissions for this dashboard", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Viewer but has an edit permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Viewer and viewers can edit", func() {
role := m.ROLE_VIEWER
setting.ViewersCanEdit = true
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
})
Convey("When user is an Org Viewer but has an admin permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_ADMIN},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Editor but has a view permission", func() {
role := m.ROLE_EDITOR
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
})
}
func GetDashboardShouldReturn200(sc *scenarioContext) dtos.DashboardFullWithMeta {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
So(sc.resp.Code, ShouldEqual, 200)
dash := dtos.DashboardFullWithMeta{}
err := json.NewDecoder(sc.resp.Body).Decode(&dash)
So(err, ShouldBeNil)
return dash
}
func GetDashboardUidBySlugShouldReturn200(sc *scenarioContext) string {
CallGetDashboardUidBySlug(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
return result.Get("uid").MustString()
}
func CallGetDashboardUidBySlug(sc *scenarioContext) {
sc.handlerFunc = GetDashboardUidBySlug
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersion(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error {
query.Result = &m.DashboardVersion{}
return nil
})
sc.handlerFunc = GetDashboardVersion
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersions(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionsQuery) error {
query.Result = []*m.DashboardVersionDTO{}
return nil
})
sc.handlerFunc = GetDashboardVersions
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallDeleteDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error {
return nil
})
sc.handlerFunc = DeleteDashboard
sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec()
}
func CallPostDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *alerting.ValidateDashboardAlertsCommand) error {
return nil
})
bus.AddHandler("test", func(cmd *m.SaveDashboardCommand) error {
cmd.Result = &m.Dashboard{Id: 2, Slug: "Dash", Version: 2}
return nil
})
bus.AddHandler("test", func(cmd *alerting.UpdateDashboardAlertsCommand) error {
return nil
})
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec()
}
func postDashboardScenario(desc string, url string, routePattern string, role m.RoleType, cmd m.SaveDashboardCommand, fn scenarioFunc) {
Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers()
sc := &scenarioContext{
url: url,
}
viewsPath, _ := filepath.Abs("../../public/views")
sc.m = macaron.New()
sc.m.Use(macaron.Renderer(macaron.RenderOptions{
Directory: viewsPath,
Delims: macaron.Delims{Left: "[[", Right: "]]"},
}))
sc.m.Use(middleware.GetContextHandler())
sc.m.Use(middleware.Sessioner(&session.Options{}))
sc.defaultHandler = wrap(func(c *middleware.Context) Response {
sc.context = c
sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID
sc.context.OrgRole = role
return PostDashboard(c, cmd)
})
fakeRepo = &fakeDashboardRepo{}
dashboards.SetRepository(fakeRepo)
sc.m.Post(routePattern, sc.defaultHandler)
fn(sc)
})
}
func (sc *scenarioContext) ToJson() *simplejson.Json {
var result *simplejson.Json
err := json.NewDecoder(sc.resp.Body).Decode(&result)
So(err, ShouldBeNil)
return result
}
| pkg/api/dashboard_test.go | 1 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.029555238783359528,
0.003234707284718752,
0.00016500282799825072,
0.001002588076516986,
0.005361313000321388
]
|
{
"id": 0,
"code_window": [
"\t\t// Dashboard\n",
"\t\tapiRoute.Group(\"/dashboards\", func(dashboardRoute RouteRegister) {\n",
"\t\t\tdashboardRoute.Get(\"/uid/:uid\", wrap(GetDashboard))\n",
"\n",
"\t\t\tdashboardRoute.Get(\"/db/:slug\", wrap(GetDashboard))\n",
"\t\t\tdashboardRoute.Get(\"/db/:slug/uid\", wrap(GetDashboardUidBySlug))\n",
"\t\t\tdashboardRoute.Delete(\"/db/:slug\", reqEditorRole, wrap(DeleteDashboard))\n",
"\n",
"\t\t\tdashboardRoute.Post(\"/calculate-diff\", bind(dtos.CalculateDiffOptions{}), wrap(CalculateDashboardDiff))\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/api.go",
"type": "replace",
"edit_start_line_idx": 247
} | import PerfectScrollbar from 'perfect-scrollbar';
import coreModule from 'app/core/core_module';
import appEvents from 'app/core/app_events';
export function geminiScrollbar() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
let scrollbar = new PerfectScrollbar(elem[0]);
appEvents.on(
'smooth-scroll-top',
() => {
elem.animate(
{
scrollTop: 0,
},
500
);
},
scope
);
scope.$on('$routeChangeSuccess', () => {
elem[0].scrollTop = 0;
});
scope.$on('$routeUpdate', () => {
elem[0].scrollTop = 0;
});
scope.$on('$destroy', () => {
scrollbar.destroy();
});
},
};
}
coreModule.directive('grafanaScrollbar', geminiScrollbar);
| public/app/core/components/scroll/scroll.ts | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.000177400914253667,
0.00017492080223746598,
0.00017246957577299327,
0.00017490636673755944,
0.0000017647131471676403
]
|
{
"id": 0,
"code_window": [
"\t\t// Dashboard\n",
"\t\tapiRoute.Group(\"/dashboards\", func(dashboardRoute RouteRegister) {\n",
"\t\t\tdashboardRoute.Get(\"/uid/:uid\", wrap(GetDashboard))\n",
"\n",
"\t\t\tdashboardRoute.Get(\"/db/:slug\", wrap(GetDashboard))\n",
"\t\t\tdashboardRoute.Get(\"/db/:slug/uid\", wrap(GetDashboardUidBySlug))\n",
"\t\t\tdashboardRoute.Delete(\"/db/:slug\", reqEditorRole, wrap(DeleteDashboard))\n",
"\n",
"\t\t\tdashboardRoute.Post(\"/calculate-diff\", bind(dtos.CalculateDiffOptions{}), wrap(CalculateDashboardDiff))\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/api.go",
"type": "replace",
"edit_start_line_idx": 247
} | import { describe, beforeEach, it, expect, angularMocks, sinon } from 'test/lib/common';
import 'app/core/directives/value_select_dropdown';
describe('SelectDropdownCtrl', function() {
var scope;
var ctrl;
var tagValuesMap: any = {};
var rootScope;
var q;
beforeEach(angularMocks.module('grafana.core'));
beforeEach(
angularMocks.inject(function($controller, $rootScope, $q, $httpBackend) {
rootScope = $rootScope;
q = $q;
scope = $rootScope.$new();
ctrl = $controller('ValueSelectDropdownCtrl', { $scope: scope });
ctrl.onUpdated = sinon.spy();
$httpBackend.when('GET', /\.html$/).respond('');
})
);
describe('Given simple variable', function() {
beforeEach(function() {
ctrl.variable = {
current: { text: 'hej', value: 'hej' },
getValuesForTag: function(key) {
return q.when(tagValuesMap[key]);
},
};
ctrl.init();
});
it('Should init labelText and linkText', function() {
expect(ctrl.linkText).to.be('hej');
});
});
describe('Given variable with tags and dropdown is opened', function() {
beforeEach(function() {
ctrl.variable = {
current: { text: 'server-1', value: 'server-1' },
options: [
{ text: 'server-1', value: 'server-1', selected: true },
{ text: 'server-2', value: 'server-2' },
{ text: 'server-3', value: 'server-3' },
],
tags: ['key1', 'key2', 'key3'],
getValuesForTag: function(key) {
return q.when(tagValuesMap[key]);
},
multi: true,
};
tagValuesMap.key1 = ['server-1', 'server-3'];
tagValuesMap.key2 = ['server-2', 'server-3'];
tagValuesMap.key3 = ['server-1', 'server-2', 'server-3'];
ctrl.init();
ctrl.show();
});
it('should init tags model', function() {
expect(ctrl.tags.length).to.be(3);
expect(ctrl.tags[0].text).to.be('key1');
});
it('should init options model', function() {
expect(ctrl.options.length).to.be(3);
});
it('should init selected values array', function() {
expect(ctrl.selectedValues.length).to.be(1);
});
it('should set linkText', function() {
expect(ctrl.linkText).to.be('server-1');
});
describe('after adititional value is selected', function() {
beforeEach(function() {
ctrl.selectValue(ctrl.options[2], {});
ctrl.commitChanges();
});
it('should update link text', function() {
expect(ctrl.linkText).to.be('server-1 + server-3');
});
});
describe('When tag is selected', function() {
beforeEach(function() {
ctrl.selectTag(ctrl.tags[0]);
rootScope.$digest();
ctrl.commitChanges();
});
it('should select tag', function() {
expect(ctrl.selectedTags.length).to.be(1);
});
it('should select values', function() {
expect(ctrl.options[0].selected).to.be(true);
expect(ctrl.options[2].selected).to.be(true);
});
it('link text should not include tag values', function() {
expect(ctrl.linkText).to.be('');
});
describe('and then dropdown is opened and closed without changes', function() {
beforeEach(function() {
ctrl.show();
ctrl.commitChanges();
rootScope.$digest();
});
it('should still have selected tag', function() {
expect(ctrl.selectedTags.length).to.be(1);
});
});
describe('and then unselected', function() {
beforeEach(function() {
ctrl.selectTag(ctrl.tags[0]);
rootScope.$digest();
});
it('should deselect tag', function() {
expect(ctrl.selectedTags.length).to.be(0);
});
});
describe('and then value is unselected', function() {
beforeEach(function() {
ctrl.selectValue(ctrl.options[0], {});
});
it('should deselect tag', function() {
expect(ctrl.selectedTags.length).to.be(0);
});
});
});
});
describe('Given variable with selected tags', function() {
beforeEach(function() {
ctrl.variable = {
current: {
text: 'server-1',
value: 'server-1',
tags: [{ text: 'key1', selected: true }],
},
options: [
{ text: 'server-1', value: 'server-1' },
{ text: 'server-2', value: 'server-2' },
{ text: 'server-3', value: 'server-3' },
],
tags: ['key1', 'key2', 'key3'],
getValuesForTag: function(key) {
return q.when(tagValuesMap[key]);
},
multi: true,
};
ctrl.init();
ctrl.show();
});
it('should set tag as selected', function() {
expect(ctrl.tags[0].selected).to.be(true);
});
});
});
| public/app/core/specs/value_select_dropdown_specs.ts | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.0001779304730007425,
0.00017631957598496228,
0.00017261879111174494,
0.00017656129784882069,
0.0000012526484169939067
]
|
{
"id": 0,
"code_window": [
"\t\t// Dashboard\n",
"\t\tapiRoute.Group(\"/dashboards\", func(dashboardRoute RouteRegister) {\n",
"\t\t\tdashboardRoute.Get(\"/uid/:uid\", wrap(GetDashboard))\n",
"\n",
"\t\t\tdashboardRoute.Get(\"/db/:slug\", wrap(GetDashboard))\n",
"\t\t\tdashboardRoute.Get(\"/db/:slug/uid\", wrap(GetDashboardUidBySlug))\n",
"\t\t\tdashboardRoute.Delete(\"/db/:slug\", reqEditorRole, wrap(DeleteDashboard))\n",
"\n",
"\t\t\tdashboardRoute.Post(\"/calculate-diff\", bind(dtos.CalculateDiffOptions{}), wrap(CalculateDashboardDiff))\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/api.go",
"type": "replace",
"edit_start_line_idx": 247
} | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bidi
import "unicode/utf8"
// Properties provides access to BiDi properties of runes.
type Properties struct {
entry uint8
last uint8
}
var trie = newBidiTrie(0)
// TODO: using this for bidirule reduces the running time by about 5%. Consider
// if this is worth exposing or if we can find a way to speed up the Class
// method.
//
// // CompactClass is like Class, but maps all of the BiDi control classes
// // (LRO, RLO, LRE, RLE, PDF, LRI, RLI, FSI, PDI) to the class Control.
// func (p Properties) CompactClass() Class {
// return Class(p.entry & 0x0F)
// }
// Class returns the Bidi class for p.
func (p Properties) Class() Class {
c := Class(p.entry & 0x0F)
if c == Control {
c = controlByteToClass[p.last&0xF]
}
return c
}
// IsBracket reports whether the rune is a bracket.
func (p Properties) IsBracket() bool { return p.entry&0xF0 != 0 }
// IsOpeningBracket reports whether the rune is an opening bracket.
// IsBracket must return true.
func (p Properties) IsOpeningBracket() bool { return p.entry&openMask != 0 }
// TODO: find a better API and expose.
func (p Properties) reverseBracket(r rune) rune {
return xorMasks[p.entry>>xorMaskShift] ^ r
}
var controlByteToClass = [16]Class{
0xD: LRO, // U+202D LeftToRightOverride,
0xE: RLO, // U+202E RightToLeftOverride,
0xA: LRE, // U+202A LeftToRightEmbedding,
0xB: RLE, // U+202B RightToLeftEmbedding,
0xC: PDF, // U+202C PopDirectionalFormat,
0x6: LRI, // U+2066 LeftToRightIsolate,
0x7: RLI, // U+2067 RightToLeftIsolate,
0x8: FSI, // U+2068 FirstStrongIsolate,
0x9: PDI, // U+2069 PopDirectionalIsolate,
}
// LookupRune returns properties for r.
func LookupRune(r rune) (p Properties, size int) {
var buf [4]byte
n := utf8.EncodeRune(buf[:], r)
return Lookup(buf[:n])
}
// TODO: these lookup methods are based on the generated trie code. The returned
// sizes have slightly different semantics from the generated code, in that it
// always returns size==1 for an illegal UTF-8 byte (instead of the length
// of the maximum invalid subsequence). Most Transformers, like unicode/norm,
// leave invalid UTF-8 untouched, in which case it has performance benefits to
// do so (without changing the semantics). Bidi requires the semantics used here
// for the bidirule implementation to be compatible with the Go semantics.
// They ultimately should perhaps be adopted by all trie implementations, for
// convenience sake.
// This unrolled code also boosts performance of the secure/bidirule package by
// about 30%.
// So, to remove this code:
// - add option to trie generator to define return type.
// - always return 1 byte size for ill-formed UTF-8 runes.
// Lookup returns properties for the first rune in s and the width in bytes of
// its encoding. The size will be 0 if s does not hold enough bytes to complete
// the encoding.
func Lookup(s []byte) (p Properties, sz int) {
c0 := s[0]
switch {
case c0 < 0x80: // is ASCII
return Properties{entry: bidiValues[c0]}, 1
case c0 < 0xC2:
return Properties{}, 1
case c0 < 0xE0: // 2-byte UTF-8
if len(s) < 2 {
return Properties{}, 0
}
i := bidiIndex[c0]
c1 := s[1]
if c1 < 0x80 || 0xC0 <= c1 {
return Properties{}, 1
}
return Properties{entry: trie.lookupValue(uint32(i), c1)}, 2
case c0 < 0xF0: // 3-byte UTF-8
if len(s) < 3 {
return Properties{}, 0
}
i := bidiIndex[c0]
c1 := s[1]
if c1 < 0x80 || 0xC0 <= c1 {
return Properties{}, 1
}
o := uint32(i)<<6 + uint32(c1)
i = bidiIndex[o]
c2 := s[2]
if c2 < 0x80 || 0xC0 <= c2 {
return Properties{}, 1
}
return Properties{entry: trie.lookupValue(uint32(i), c2), last: c2}, 3
case c0 < 0xF8: // 4-byte UTF-8
if len(s) < 4 {
return Properties{}, 0
}
i := bidiIndex[c0]
c1 := s[1]
if c1 < 0x80 || 0xC0 <= c1 {
return Properties{}, 1
}
o := uint32(i)<<6 + uint32(c1)
i = bidiIndex[o]
c2 := s[2]
if c2 < 0x80 || 0xC0 <= c2 {
return Properties{}, 1
}
o = uint32(i)<<6 + uint32(c2)
i = bidiIndex[o]
c3 := s[3]
if c3 < 0x80 || 0xC0 <= c3 {
return Properties{}, 1
}
return Properties{entry: trie.lookupValue(uint32(i), c3)}, 4
}
// Illegal rune
return Properties{}, 1
}
// LookupString returns properties for the first rune in s and the width in
// bytes of its encoding. The size will be 0 if s does not hold enough bytes to
// complete the encoding.
func LookupString(s string) (p Properties, sz int) {
c0 := s[0]
switch {
case c0 < 0x80: // is ASCII
return Properties{entry: bidiValues[c0]}, 1
case c0 < 0xC2:
return Properties{}, 1
case c0 < 0xE0: // 2-byte UTF-8
if len(s) < 2 {
return Properties{}, 0
}
i := bidiIndex[c0]
c1 := s[1]
if c1 < 0x80 || 0xC0 <= c1 {
return Properties{}, 1
}
return Properties{entry: trie.lookupValue(uint32(i), c1)}, 2
case c0 < 0xF0: // 3-byte UTF-8
if len(s) < 3 {
return Properties{}, 0
}
i := bidiIndex[c0]
c1 := s[1]
if c1 < 0x80 || 0xC0 <= c1 {
return Properties{}, 1
}
o := uint32(i)<<6 + uint32(c1)
i = bidiIndex[o]
c2 := s[2]
if c2 < 0x80 || 0xC0 <= c2 {
return Properties{}, 1
}
return Properties{entry: trie.lookupValue(uint32(i), c2), last: c2}, 3
case c0 < 0xF8: // 4-byte UTF-8
if len(s) < 4 {
return Properties{}, 0
}
i := bidiIndex[c0]
c1 := s[1]
if c1 < 0x80 || 0xC0 <= c1 {
return Properties{}, 1
}
o := uint32(i)<<6 + uint32(c1)
i = bidiIndex[o]
c2 := s[2]
if c2 < 0x80 || 0xC0 <= c2 {
return Properties{}, 1
}
o = uint32(i)<<6 + uint32(c2)
i = bidiIndex[o]
c3 := s[3]
if c3 < 0x80 || 0xC0 <= c3 {
return Properties{}, 1
}
return Properties{entry: trie.lookupValue(uint32(i), c3)}, 4
}
// Illegal rune
return Properties{}, 1
}
| vendor/golang.org/x/text/unicode/bidi/prop.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017825652321334928,
0.00017406321421731263,
0.00016692408826202154,
0.00017433875473216176,
0.000002825109504556167
]
|
{
"id": 1,
"code_window": [
"\treturn Json(200, dto)\n",
"}\n",
"\n",
"func GetDashboardUidBySlug(c *middleware.Context) Response {\n",
"\tdash, rsp := getDashboardHelper(c.OrgId, c.Params(\":slug\"), 0, \"\")\n",
"\tif rsp != nil {\n",
"\t\treturn rsp\n",
"\t}\n",
"\n",
"\tguardian := guardian.NewDashboardGuardian(dash.Id, c.OrgId, c.SignedInUser)\n",
"\tif canView, err := guardian.CanView(); err != nil || !canView {\n",
"\t\tfmt.Printf(\"%v\", err)\n",
"\t\treturn dashboardGuardianResponse(err)\n",
"\t}\n",
"\n",
"\treturn Json(200, util.DynMap{\"uid\": dash.Uid})\n",
"}\n",
"\n",
"func getUserLogin(userId int64) string {\n",
"\tquery := m.GetUserByIdQuery{Id: userId}\n",
"\terr := bus.Dispatch(&query)\n",
"\tif err != nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard.go",
"type": "replace",
"edit_start_line_idx": 121
} | package api
import (
"encoding/json"
"path/filepath"
"testing"
macaron "gopkg.in/macaron.v1"
"github.com/go-macaron/session"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
type fakeDashboardRepo struct {
inserted []*dashboards.SaveDashboardItem
getDashboard []*m.Dashboard
}
func (repo *fakeDashboardRepo) SaveDashboard(json *dashboards.SaveDashboardItem) (*m.Dashboard, error) {
repo.inserted = append(repo.inserted, json)
return json.Dashboard, nil
}
var fakeRepo *fakeDashboardRepo
func TestDashboardApiEndpoint(t *testing.T) {
Convey("Given a dashboard with a parent folder which does not have an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = false
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
viewerRole := m.ROLE_VIEWER
editorRole := m.ROLE_EDITOR
aclMockResp := []*m.DashboardAclInfoDTO{
{Role: &viewerRole, Permission: m.PERMISSION_VIEW},
{Role: &editorRole, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
"id": fakeDash.Id,
}),
}
Convey("When user is an Org Viewer", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
Convey("When saving a dashboard folder in another folder", func() {
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
query.Result.IsFolder = true
return nil
})
invalidCmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
IsFolder: true,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("Should return an error", func() {
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, invalidCmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 400)
})
})
})
})
})
Convey("Given a dashboard with a parent folder which has an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = true
setting.ViewersCanEdit = false
aclMockResp := []*m.DashboardAclInfoDTO{
{
DashboardId: 1,
Permission: m.PERMISSION_EDIT,
UserId: 200,
},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"id": fakeDash.Id,
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("When user is an Org Viewer and has no permissions for this dashboard", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor and has no permissions for this dashboard", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Viewer but has an edit permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Viewer and viewers can edit", func() {
role := m.ROLE_VIEWER
setting.ViewersCanEdit = true
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
})
Convey("When user is an Org Viewer but has an admin permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_ADMIN},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Editor but has a view permission", func() {
role := m.ROLE_EDITOR
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
})
}
func GetDashboardShouldReturn200(sc *scenarioContext) dtos.DashboardFullWithMeta {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
So(sc.resp.Code, ShouldEqual, 200)
dash := dtos.DashboardFullWithMeta{}
err := json.NewDecoder(sc.resp.Body).Decode(&dash)
So(err, ShouldBeNil)
return dash
}
func GetDashboardUidBySlugShouldReturn200(sc *scenarioContext) string {
CallGetDashboardUidBySlug(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
return result.Get("uid").MustString()
}
func CallGetDashboardUidBySlug(sc *scenarioContext) {
sc.handlerFunc = GetDashboardUidBySlug
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersion(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error {
query.Result = &m.DashboardVersion{}
return nil
})
sc.handlerFunc = GetDashboardVersion
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersions(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionsQuery) error {
query.Result = []*m.DashboardVersionDTO{}
return nil
})
sc.handlerFunc = GetDashboardVersions
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallDeleteDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error {
return nil
})
sc.handlerFunc = DeleteDashboard
sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec()
}
func CallPostDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *alerting.ValidateDashboardAlertsCommand) error {
return nil
})
bus.AddHandler("test", func(cmd *m.SaveDashboardCommand) error {
cmd.Result = &m.Dashboard{Id: 2, Slug: "Dash", Version: 2}
return nil
})
bus.AddHandler("test", func(cmd *alerting.UpdateDashboardAlertsCommand) error {
return nil
})
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec()
}
func postDashboardScenario(desc string, url string, routePattern string, role m.RoleType, cmd m.SaveDashboardCommand, fn scenarioFunc) {
Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers()
sc := &scenarioContext{
url: url,
}
viewsPath, _ := filepath.Abs("../../public/views")
sc.m = macaron.New()
sc.m.Use(macaron.Renderer(macaron.RenderOptions{
Directory: viewsPath,
Delims: macaron.Delims{Left: "[[", Right: "]]"},
}))
sc.m.Use(middleware.GetContextHandler())
sc.m.Use(middleware.Sessioner(&session.Options{}))
sc.defaultHandler = wrap(func(c *middleware.Context) Response {
sc.context = c
sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID
sc.context.OrgRole = role
return PostDashboard(c, cmd)
})
fakeRepo = &fakeDashboardRepo{}
dashboards.SetRepository(fakeRepo)
sc.m.Post(routePattern, sc.defaultHandler)
fn(sc)
})
}
func (sc *scenarioContext) ToJson() *simplejson.Json {
var result *simplejson.Json
err := json.NewDecoder(sc.resp.Body).Decode(&result)
So(err, ShouldBeNil)
return result
}
| pkg/api/dashboard_test.go | 1 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.9991167187690735,
0.14984643459320068,
0.00016149190196301788,
0.001672675833106041,
0.3511621654033661
]
|
{
"id": 1,
"code_window": [
"\treturn Json(200, dto)\n",
"}\n",
"\n",
"func GetDashboardUidBySlug(c *middleware.Context) Response {\n",
"\tdash, rsp := getDashboardHelper(c.OrgId, c.Params(\":slug\"), 0, \"\")\n",
"\tif rsp != nil {\n",
"\t\treturn rsp\n",
"\t}\n",
"\n",
"\tguardian := guardian.NewDashboardGuardian(dash.Id, c.OrgId, c.SignedInUser)\n",
"\tif canView, err := guardian.CanView(); err != nil || !canView {\n",
"\t\tfmt.Printf(\"%v\", err)\n",
"\t\treturn dashboardGuardianResponse(err)\n",
"\t}\n",
"\n",
"\treturn Json(200, util.DynMap{\"uid\": dash.Uid})\n",
"}\n",
"\n",
"func getUserLogin(userId int64) string {\n",
"\tquery := m.GetUserByIdQuery{Id: userId}\n",
"\terr := bus.Dispatch(&query)\n",
"\tif err != nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard.go",
"type": "replace",
"edit_start_line_idx": 121
} | <?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 20.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="117.8px" height="64px" viewBox="0 0 117.8 64" style="enable-background:new 0 0 117.8 64;" xml:space="preserve">
<style type="text/css">
.st0{fill:#555555;}
.st1{fill:url(#SVGID_1_);}
</style>
<g>
<path class="st0" d="M15.2,22.7H1.9c-1.1,0-1.9,0.9-1.9,1.9v37.5C0,63.2,0.9,64,1.9,64h13.3c1.1,0,1.9-0.9,1.9-1.9V24.6
C17.1,23.5,16.3,22.7,15.2,22.7z"/>
<path class="st0" d="M36.3,10.2H23c-1.1,0-1.9,0.9-1.9,1.9v50c0,1.1,0.9,1.9,1.9,1.9h13.3c1.1,0,1.9-0.9,1.9-1.9v-50
C38.2,11.1,37.3,10.2,36.3,10.2z"/>
<path class="st0" d="M57.3,32H44c-1.1,0-1.9,0.9-1.9,1.9v28.1c0,1.1,0.9,1.9,1.9,1.9h13.3c1.1,0,1.9-0.9,1.9-1.9V34
C59.2,32.9,58.4,32,57.3,32z"/>
<path class="st0" d="M70.1,38V26.1c0-3.4,2.7-6.1,6.1-6.1h4.1V2c0-1.1-0.9-1.9-1.9-1.9H65.1C64,0,63.1,0.9,63.1,2v60.1
c0,1.1,0.9,1.9,1.9,1.9h13.3c1.1,0,1.9-0.9,1.9-1.9V44.1h-4.1C72.9,44.1,70.1,41.3,70.1,38z"/>
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="96.4427" y1="83.7013" x2="96.4427" y2="-9.4831">
<stop offset="0" style="stop-color:#FFF23A"/>
<stop offset="4.010540e-02" style="stop-color:#FEE62D"/>
<stop offset="0.1171" style="stop-color:#FED41A"/>
<stop offset="0.1964" style="stop-color:#FDC90F"/>
<stop offset="0.2809" style="stop-color:#FDC60B"/>
<stop offset="0.6685" style="stop-color:#F28F3F"/>
<stop offset="0.8876" style="stop-color:#ED693C"/>
<stop offset="1" style="stop-color:#E83E39"/>
</linearGradient>
<path class="st1" d="M116.7,24.9h-7.2h-0.5h-5.4V11.8c0-0.6-0.5-1.1-1.1-1.1H90.5c-0.6,0-1.1,0.5-1.1,1.1v13.1h-9.1h-4.1
c-0.6,0-1.1,0.5-1.1,1.1V38c0,0.6,0.5,1.1,1.1,1.1h4.1h9.1v4.6v1.9v6.7c0,0.6,0.5,1.1,1.1,1.1h11.9c0.6,0,1.1-0.5,1.1-1.1V39.1
h13.1c0.6,0,1.1-0.5,1.1-1.1V26.1C117.8,25.5,117.3,24.9,116.7,24.9z"/>
</g>
</svg>
| public/img/icons_light_theme/icon_add_panel.svg | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017238620785064995,
0.00017109105829149485,
0.00017018968355841935,
0.00017089414177462459,
8.044528954087582e-7
]
|
{
"id": 1,
"code_window": [
"\treturn Json(200, dto)\n",
"}\n",
"\n",
"func GetDashboardUidBySlug(c *middleware.Context) Response {\n",
"\tdash, rsp := getDashboardHelper(c.OrgId, c.Params(\":slug\"), 0, \"\")\n",
"\tif rsp != nil {\n",
"\t\treturn rsp\n",
"\t}\n",
"\n",
"\tguardian := guardian.NewDashboardGuardian(dash.Id, c.OrgId, c.SignedInUser)\n",
"\tif canView, err := guardian.CanView(); err != nil || !canView {\n",
"\t\tfmt.Printf(\"%v\", err)\n",
"\t\treturn dashboardGuardianResponse(err)\n",
"\t}\n",
"\n",
"\treturn Json(200, util.DynMap{\"uid\": dash.Uid})\n",
"}\n",
"\n",
"func getUserLogin(userId int64) string {\n",
"\tquery := m.GetUserByIdQuery{Id: userId}\n",
"\terr := bus.Dispatch(&query)\n",
"\tif err != nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard.go",
"type": "replace",
"edit_start_line_idx": 121
} | {
"__inputs": [
{
"name": "DS_NAME",
"type": "datasource",
"pluginId": "prometheus",
"pluginName": "Prometheus"
}
],
"annotations": {
"list": []
},
"editable": true,
"gnetId": null,
"graphTooltip": 1,
"hideControls": false,
"id": null,
"links": [
{
"icon": "info",
"tags": [],
"targetBlank": true,
"title": "Grafana Docs",
"tooltip": "",
"type": "link",
"url": "http://docs.grafana.org/"
},
{
"icon": "info",
"tags": [],
"targetBlank": true,
"title": "Prometheus Docs",
"type": "link",
"url": "http://prometheus.io/docs/introduction/overview/"
}
],
"refresh": "1m",
"revision": "1.0",
"rows": [
{
"collapse": false,
"height": "200",
"panels": [
{
"aliasColors": {
"prometheus": "#C15C17",
"{instance=\"localhost:9090\",job=\"prometheus\"}": "#CCA300"
},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_NAME}",
"editable": true,
"error": false,
"fill": 0,
"grid": {},
"id": 3,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "connected",
"percentage": false,
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 3,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "sum(irate(prometheus_tsdb_head_samples_appended_total{job=\"prometheus\"}[5m]))",
"format": "time_series",
"hide": false,
"interval": "",
"intervalFactor": 2,
"legendFormat": "samples",
"metric": "",
"refId": "A",
"step": 20
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Samples Appended",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "cumulative"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"logBase": 1,
"max": null,
"min": "0",
"show": true
},
{
"format": "short",
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_NAME}",
"editable": true,
"error": false,
"fill": 0,
"grid": {},
"id": 14,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "connected",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 3,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "topk(5, max(scrape_duration_seconds) by (job))",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "{{job}}",
"metric": "",
"refId": "A",
"step": 20
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Scrape Duration",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "cumulative"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "s",
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_NAME}",
"description": "",
"fill": 0,
"id": 16,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 3,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "sum(process_resident_memory_bytes{job=\"prometheus\"})",
"format": "time_series",
"hide": false,
"interval": "",
"intervalFactor": 2,
"legendFormat": "p8s process resident memory",
"refId": "D",
"step": 20
},
{
"expr": "process_virtual_memory_bytes{job=\"prometheus\"}",
"format": "time_series",
"hide": false,
"intervalFactor": 2,
"legendFormat": "virtual memory",
"refId": "C",
"step": 20
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Memory Profile",
"tooltip": {
"shared": true,
"sort": 2,
"value_type": "individual"
},
"transparent": false,
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "bytes",
"label": "",
"logBase": 1,
"max": null,
"min": "0",
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
},
{
"cacheTimeout": null,
"colorBackground": false,
"colorValue": true,
"colors": [
"rgba(50, 172, 45, 0.97)",
"rgba(237, 129, 40, 0.89)",
"rgba(245, 54, 54, 0.9)"
],
"datasource": "${DS_NAME}",
"format": "none",
"gauge": {
"maxValue": 100,
"minValue": 0,
"show": false,
"thresholdLabels": false,
"thresholdMarkers": true
},
"id": 37,
"interval": null,
"links": [],
"mappingType": 1,
"mappingTypes": [
{
"name": "value to text",
"value": 1
},
{
"name": "range to text",
"value": 2
}
],
"maxDataPoints": 100,
"nullPointMode": "connected",
"nullText": null,
"postfix": "",
"postfixFontSize": "50%",
"prefix": "",
"prefixFontSize": "50%",
"rangeMaps": [
{
"from": "null",
"text": "N/A",
"to": "null"
}
],
"span": 3,
"sparkline": {
"fillColor": "rgba(31, 118, 189, 0.18)",
"full": false,
"lineColor": "rgb(31, 120, 193)",
"show": false
},
"tableColumn": "",
"targets": [
{
"expr": "tsdb_wal_corruptions_total{job=\"prometheus\"}",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "",
"refId": "A",
"step": 60
}
],
"thresholds": "0.1,1",
"title": "WAL Corruptions",
"type": "singlestat",
"valueFontSize": "200%",
"valueMaps": [
{
"op": "=",
"text": "None",
"value": "0"
}
],
"valueName": "max"
}
],
"repeat": null,
"repeatIteration": null,
"repeatRowId": null,
"showTitle": false,
"title": "New row",
"titleSize": "h6"
},
{
"collapse": false,
"height": "200",
"panels": [
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_NAME}",
"fill": 0,
"id": 29,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 3,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "sum(prometheus_tsdb_head_active_appenders{job=\"prometheus\"})",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "active_appenders",
"metric": "",
"refId": "A",
"step": 20
},
{
"expr": "sum(process_open_fds{job=\"prometheus\"})",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "open_fds",
"refId": "B",
"step": 20
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Active Appenders",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": false
}
]
},
{
"aliasColors": {
"prometheus": "#F9BA8F",
"{instance=\"localhost:9090\",interval=\"5s\",job=\"prometheus\"}": "#F9BA8F"
},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_NAME}",
"editable": true,
"error": false,
"fill": 0,
"grid": {},
"id": 2,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "connected",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 3,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "prometheus_tsdb_blocks_loaded{job=\"prometheus\"}",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "blocks",
"refId": "A",
"step": 20
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Blocks Loaded",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "cumulative"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_NAME}",
"decimals": null,
"description": "",
"fill": 0,
"id": 33,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "connected",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 3,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "prometheus_tsdb_head_chunks{job=\"prometheus\"}",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "chunks",
"refId": "A",
"step": 20
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Head Chunks",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "bytes",
"label": "",
"logBase": 1,
"max": null,
"min": null,
"show": false
}
]
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_NAME}",
"fill": 1,
"id": 36,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [
{
"alias": "duration-p99",
"yaxis": 2
}
],
"spaceLength": 10,
"span": 3,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "prometheus_tsdb_head_gc_duration_seconds{job=\"prometheus\",quantile=\"0.99\"}",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "duration-p99",
"refId": "A",
"step": 20
},
{
"expr": "irate(prometheus_tsdb_head_gc_duration_seconds_count{job=\"prometheus\"}[5m])",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "collections",
"refId": "B",
"step": 20
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Head Block GC Activity",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": "0",
"show": true
},
{
"format": "s",
"label": null,
"logBase": 1,
"max": null,
"min": "0",
"show": true
}
]
}
],
"repeat": null,
"repeatIteration": null,
"repeatRowId": null,
"showTitle": false,
"title": "New row",
"titleSize": "h6"
},
{
"collapse": false,
"height": "200",
"panels": [
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_NAME}",
"decimals": null,
"description": "",
"fill": 0,
"id": 20,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "connected",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [
{
"alias": "duration-p99",
"yaxis": 2
}
],
"spaceLength": 10,
"span": 4,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "histogram_quantile(0.99, sum(rate(prometheus_tsdb_compaction_duration_bucket{job=\"prometheus\"}[5m])) by (le))",
"format": "time_series",
"hide": false,
"interval": "",
"intervalFactor": 2,
"legendFormat": "duration-{{p99}}",
"refId": "A",
"step": 20
},
{
"expr": "irate(prometheus_tsdb_compactions_total{job=\"prometheus\"}[5m])",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "compactions",
"refId": "B",
"step": 20
},
{
"expr": "irate(prometheus_tsdb_compactions_failed_total{job=\"prometheus\"}[5m])",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "failed",
"refId": "C",
"step": 20
},
{
"expr": "irate(prometheus_tsdb_compactions_triggered_total{job=\"prometheus\"}[5m])",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "triggered",
"refId": "D",
"step": 20
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Compaction Activity",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": "0",
"show": true
},
{
"format": "s",
"label": "",
"logBase": 1,
"max": null,
"min": "0",
"show": true
}
]
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_NAME}",
"fill": 1,
"id": 32,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 4,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "rate(prometheus_tsdb_reloads_total{job=\"prometheus\"}[5m])",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "reloads",
"refId": "A",
"step": 20
},
{
"expr": "rate(prometheus_tsdb_reloads_failures_total{job=\"prometheus\"}[5m])",
"format": "time_series",
"hide": false,
"intervalFactor": 2,
"legendFormat": "failures",
"refId": "B",
"step": 20
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Reload Count",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_NAME}",
"fill": 0,
"id": 38,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 4,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "prometheus_engine_query_duration_seconds{job=\"prometheus\", quantile=\"0.99\"}",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "{{slice}}_p99",
"refId": "A",
"step": 20
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Query Durations",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
}
],
"repeat": null,
"repeatIteration": null,
"repeatRowId": null,
"showTitle": false,
"title": "New row",
"titleSize": "h6"
},
{
"collapse": false,
"height": 250,
"panels": [
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_NAME}",
"decimals": null,
"editable": true,
"error": false,
"fill": 0,
"grid": {},
"id": 35,
"legend": {
"alignAsTable": false,
"avg": false,
"current": false,
"hideEmpty": true,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "connected",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 6,
"stack": false,
"steppedLine": false,
"targets": [
{
"expr": "max(prometheus_evaluator_duration_seconds{job=\"prometheus\", quantile!=\"0.01\", quantile!=\"0.05\"}) by (quantile)",
"format": "time_series",
"interval": "",
"intervalFactor": 2,
"legendFormat": "{{quantile}}",
"refId": "A",
"step": 10
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Rule Eval Duration",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "cumulative"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "s",
"label": "",
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "${DS_NAME}",
"fill": 1,
"id": 39,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"span": 6,
"stack": true,
"steppedLine": false,
"targets": [
{
"expr": "rate(prometheus_evaluator_iterations_missed_total{job=\"prometheus\"}[5m])",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "missed",
"refId": "B",
"step": 10
},
{
"expr": "rate(prometheus_evaluator_iterations_skipped_total{job=\"prometheus\"}[5m])",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "skipped",
"refId": "C",
"step": 10
},
{
"expr": "rate(prometheus_evaluator_iterations_total{job=\"prometheus\"}[5m])",
"format": "time_series",
"intervalFactor": 2,
"legendFormat": "iterations",
"refId": "A",
"step": 10
}
],
"thresholds": [],
"timeFrom": null,
"timeShift": null,
"title": "Rule Eval Activity",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
]
}
],
"repeat": null,
"repeatIteration": null,
"repeatRowId": null,
"showTitle": false,
"title": "Dashboard Row",
"titleSize": "h6"
}
],
"schemaVersion": 14,
"style": "dark",
"tags": [
"prometheus"
],
"templating": {
"list": []
},
"time": {
"from": "now-1h",
"to": "now"
},
"timepicker": {
"now": true,
"refresh_intervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
"time_options": [
"5m",
"15m",
"1h",
"6h",
"12h",
"24h",
"2d",
"7d",
"30d"
]
},
"timezone": "browser",
"title": "Prometheus 2.0 Stats",
"version": 19
}
| public/app/plugins/datasource/prometheus/dashboards/prometheus_2_stats.json | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.000176708068465814,
0.00017282205226365477,
0.00016579165821895003,
0.00017306854715570807,
0.0000017328820831608027
]
|
{
"id": 1,
"code_window": [
"\treturn Json(200, dto)\n",
"}\n",
"\n",
"func GetDashboardUidBySlug(c *middleware.Context) Response {\n",
"\tdash, rsp := getDashboardHelper(c.OrgId, c.Params(\":slug\"), 0, \"\")\n",
"\tif rsp != nil {\n",
"\t\treturn rsp\n",
"\t}\n",
"\n",
"\tguardian := guardian.NewDashboardGuardian(dash.Id, c.OrgId, c.SignedInUser)\n",
"\tif canView, err := guardian.CanView(); err != nil || !canView {\n",
"\t\tfmt.Printf(\"%v\", err)\n",
"\t\treturn dashboardGuardianResponse(err)\n",
"\t}\n",
"\n",
"\treturn Json(200, util.DynMap{\"uid\": dash.Uid})\n",
"}\n",
"\n",
"func getUserLogin(userId int64) string {\n",
"\tquery := m.GetUserByIdQuery{Id: userId}\n",
"\terr := bus.Dispatch(&query)\n",
"\tif err != nil {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard.go",
"type": "replace",
"edit_start_line_idx": 121
} | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
// Package unix contains an interface to the low-level operating system
// primitives. OS details vary depending on the underlying system, and
// by default, godoc will display OS-specific documentation for the current
// system. If you want godoc to display OS documentation for another
// system, set $GOOS and $GOARCH to the desired system. For example, if
// you want to view documentation for freebsd/arm on linux/amd64, set $GOOS
// to freebsd and $GOARCH to arm.
// The primary use of this package is inside other packages that provide a more
// portable interface to the system, such as "os", "time" and "net". Use
// those packages rather than this one if you can.
// For details of the functions and data types in this package consult
// the manuals for the appropriate operating system.
// These calls return err == nil to indicate success; otherwise
// err represents an operating system error describing the failure and
// holds a value of type syscall.Errno.
package unix // import "golang.org/x/sys/unix"
// ByteSliceFromString returns a NUL-terminated slice of bytes
// containing the text of s. If s contains a NUL byte at any
// location, it returns (nil, EINVAL).
func ByteSliceFromString(s string) ([]byte, error) {
for i := 0; i < len(s); i++ {
if s[i] == 0 {
return nil, EINVAL
}
}
a := make([]byte, len(s)+1)
copy(a, s)
return a, nil
}
// BytePtrFromString returns a pointer to a NUL-terminated array of
// bytes containing the text of s. If s contains a NUL byte at any
// location, it returns (nil, EINVAL).
func BytePtrFromString(s string) (*byte, error) {
a, err := ByteSliceFromString(s)
if err != nil {
return nil, err
}
return &a[0], nil
}
// Single-word zero for use when we need a valid pointer to 0 bytes.
// See mkunix.pl.
var _zero uintptr
| vendor/golang.org/x/sys/unix/syscall.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017498426313977689,
0.00016944471281021833,
0.00016485970991197973,
0.0001698429259704426,
0.0000037558868370979326
]
|
{
"id": 2,
"code_window": [
"\t\t\tgetDashboardQueries = append(getDashboardQueries, query)\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tbus.AddHandler(\"test\", func(query *m.GetDashboardUidBySlugQuery) error {\n",
"\t\t\tquery.Result = fakeDash.Uid\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tviewerRole := m.ROLE_VIEWER\n",
"\t\teditorRole := m.ROLE_EDITOR\n",
"\n",
"\t\taclMockResp := []*m.DashboardAclInfoDTO{\n",
"\t\t\t{Role: &viewerRole, Permission: m.PERMISSION_VIEW},\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 49
} | package api
import (
"encoding/json"
"path/filepath"
"testing"
macaron "gopkg.in/macaron.v1"
"github.com/go-macaron/session"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
type fakeDashboardRepo struct {
inserted []*dashboards.SaveDashboardItem
getDashboard []*m.Dashboard
}
func (repo *fakeDashboardRepo) SaveDashboard(json *dashboards.SaveDashboardItem) (*m.Dashboard, error) {
repo.inserted = append(repo.inserted, json)
return json.Dashboard, nil
}
var fakeRepo *fakeDashboardRepo
func TestDashboardApiEndpoint(t *testing.T) {
Convey("Given a dashboard with a parent folder which does not have an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = false
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
viewerRole := m.ROLE_VIEWER
editorRole := m.ROLE_EDITOR
aclMockResp := []*m.DashboardAclInfoDTO{
{Role: &viewerRole, Permission: m.PERMISSION_VIEW},
{Role: &editorRole, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
"id": fakeDash.Id,
}),
}
Convey("When user is an Org Viewer", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
Convey("When saving a dashboard folder in another folder", func() {
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
query.Result.IsFolder = true
return nil
})
invalidCmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
IsFolder: true,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("Should return an error", func() {
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, invalidCmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 400)
})
})
})
})
})
Convey("Given a dashboard with a parent folder which has an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = true
setting.ViewersCanEdit = false
aclMockResp := []*m.DashboardAclInfoDTO{
{
DashboardId: 1,
Permission: m.PERMISSION_EDIT,
UserId: 200,
},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"id": fakeDash.Id,
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("When user is an Org Viewer and has no permissions for this dashboard", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor and has no permissions for this dashboard", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Viewer but has an edit permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Viewer and viewers can edit", func() {
role := m.ROLE_VIEWER
setting.ViewersCanEdit = true
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
})
Convey("When user is an Org Viewer but has an admin permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_ADMIN},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Editor but has a view permission", func() {
role := m.ROLE_EDITOR
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
})
}
func GetDashboardShouldReturn200(sc *scenarioContext) dtos.DashboardFullWithMeta {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
So(sc.resp.Code, ShouldEqual, 200)
dash := dtos.DashboardFullWithMeta{}
err := json.NewDecoder(sc.resp.Body).Decode(&dash)
So(err, ShouldBeNil)
return dash
}
func GetDashboardUidBySlugShouldReturn200(sc *scenarioContext) string {
CallGetDashboardUidBySlug(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
return result.Get("uid").MustString()
}
func CallGetDashboardUidBySlug(sc *scenarioContext) {
sc.handlerFunc = GetDashboardUidBySlug
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersion(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error {
query.Result = &m.DashboardVersion{}
return nil
})
sc.handlerFunc = GetDashboardVersion
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersions(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionsQuery) error {
query.Result = []*m.DashboardVersionDTO{}
return nil
})
sc.handlerFunc = GetDashboardVersions
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallDeleteDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error {
return nil
})
sc.handlerFunc = DeleteDashboard
sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec()
}
func CallPostDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *alerting.ValidateDashboardAlertsCommand) error {
return nil
})
bus.AddHandler("test", func(cmd *m.SaveDashboardCommand) error {
cmd.Result = &m.Dashboard{Id: 2, Slug: "Dash", Version: 2}
return nil
})
bus.AddHandler("test", func(cmd *alerting.UpdateDashboardAlertsCommand) error {
return nil
})
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec()
}
func postDashboardScenario(desc string, url string, routePattern string, role m.RoleType, cmd m.SaveDashboardCommand, fn scenarioFunc) {
Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers()
sc := &scenarioContext{
url: url,
}
viewsPath, _ := filepath.Abs("../../public/views")
sc.m = macaron.New()
sc.m.Use(macaron.Renderer(macaron.RenderOptions{
Directory: viewsPath,
Delims: macaron.Delims{Left: "[[", Right: "]]"},
}))
sc.m.Use(middleware.GetContextHandler())
sc.m.Use(middleware.Sessioner(&session.Options{}))
sc.defaultHandler = wrap(func(c *middleware.Context) Response {
sc.context = c
sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID
sc.context.OrgRole = role
return PostDashboard(c, cmd)
})
fakeRepo = &fakeDashboardRepo{}
dashboards.SetRepository(fakeRepo)
sc.m.Post(routePattern, sc.defaultHandler)
fn(sc)
})
}
func (sc *scenarioContext) ToJson() *simplejson.Json {
var result *simplejson.Json
err := json.NewDecoder(sc.resp.Body).Decode(&result)
So(err, ShouldBeNil)
return result
}
| pkg/api/dashboard_test.go | 1 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.9987452030181885,
0.07083049416542053,
0.000164146171300672,
0.006678489036858082,
0.21786251664161682
]
|
{
"id": 2,
"code_window": [
"\t\t\tgetDashboardQueries = append(getDashboardQueries, query)\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tbus.AddHandler(\"test\", func(query *m.GetDashboardUidBySlugQuery) error {\n",
"\t\t\tquery.Result = fakeDash.Uid\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tviewerRole := m.ROLE_VIEWER\n",
"\t\teditorRole := m.ROLE_EDITOR\n",
"\n",
"\t\taclMockResp := []*m.DashboardAclInfoDTO{\n",
"\t\t\t{Role: &viewerRole, Permission: m.PERMISSION_VIEW},\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 49
} | import { describe, beforeEach, it, expect, angularMocks, sinon } from 'test/lib/common';
import 'app/core/directives/value_select_dropdown';
describe('SelectDropdownCtrl', function() {
var scope;
var ctrl;
var tagValuesMap: any = {};
var rootScope;
var q;
beforeEach(angularMocks.module('grafana.core'));
beforeEach(
angularMocks.inject(function($controller, $rootScope, $q, $httpBackend) {
rootScope = $rootScope;
q = $q;
scope = $rootScope.$new();
ctrl = $controller('ValueSelectDropdownCtrl', { $scope: scope });
ctrl.onUpdated = sinon.spy();
$httpBackend.when('GET', /\.html$/).respond('');
})
);
describe('Given simple variable', function() {
beforeEach(function() {
ctrl.variable = {
current: { text: 'hej', value: 'hej' },
getValuesForTag: function(key) {
return q.when(tagValuesMap[key]);
},
};
ctrl.init();
});
it('Should init labelText and linkText', function() {
expect(ctrl.linkText).to.be('hej');
});
});
describe('Given variable with tags and dropdown is opened', function() {
beforeEach(function() {
ctrl.variable = {
current: { text: 'server-1', value: 'server-1' },
options: [
{ text: 'server-1', value: 'server-1', selected: true },
{ text: 'server-2', value: 'server-2' },
{ text: 'server-3', value: 'server-3' },
],
tags: ['key1', 'key2', 'key3'],
getValuesForTag: function(key) {
return q.when(tagValuesMap[key]);
},
multi: true,
};
tagValuesMap.key1 = ['server-1', 'server-3'];
tagValuesMap.key2 = ['server-2', 'server-3'];
tagValuesMap.key3 = ['server-1', 'server-2', 'server-3'];
ctrl.init();
ctrl.show();
});
it('should init tags model', function() {
expect(ctrl.tags.length).to.be(3);
expect(ctrl.tags[0].text).to.be('key1');
});
it('should init options model', function() {
expect(ctrl.options.length).to.be(3);
});
it('should init selected values array', function() {
expect(ctrl.selectedValues.length).to.be(1);
});
it('should set linkText', function() {
expect(ctrl.linkText).to.be('server-1');
});
describe('after adititional value is selected', function() {
beforeEach(function() {
ctrl.selectValue(ctrl.options[2], {});
ctrl.commitChanges();
});
it('should update link text', function() {
expect(ctrl.linkText).to.be('server-1 + server-3');
});
});
describe('When tag is selected', function() {
beforeEach(function() {
ctrl.selectTag(ctrl.tags[0]);
rootScope.$digest();
ctrl.commitChanges();
});
it('should select tag', function() {
expect(ctrl.selectedTags.length).to.be(1);
});
it('should select values', function() {
expect(ctrl.options[0].selected).to.be(true);
expect(ctrl.options[2].selected).to.be(true);
});
it('link text should not include tag values', function() {
expect(ctrl.linkText).to.be('');
});
describe('and then dropdown is opened and closed without changes', function() {
beforeEach(function() {
ctrl.show();
ctrl.commitChanges();
rootScope.$digest();
});
it('should still have selected tag', function() {
expect(ctrl.selectedTags.length).to.be(1);
});
});
describe('and then unselected', function() {
beforeEach(function() {
ctrl.selectTag(ctrl.tags[0]);
rootScope.$digest();
});
it('should deselect tag', function() {
expect(ctrl.selectedTags.length).to.be(0);
});
});
describe('and then value is unselected', function() {
beforeEach(function() {
ctrl.selectValue(ctrl.options[0], {});
});
it('should deselect tag', function() {
expect(ctrl.selectedTags.length).to.be(0);
});
});
});
});
describe('Given variable with selected tags', function() {
beforeEach(function() {
ctrl.variable = {
current: {
text: 'server-1',
value: 'server-1',
tags: [{ text: 'key1', selected: true }],
},
options: [
{ text: 'server-1', value: 'server-1' },
{ text: 'server-2', value: 'server-2' },
{ text: 'server-3', value: 'server-3' },
],
tags: ['key1', 'key2', 'key3'],
getValuesForTag: function(key) {
return q.when(tagValuesMap[key]);
},
multi: true,
};
ctrl.init();
ctrl.show();
});
it('should set tag as selected', function() {
expect(ctrl.tags[0].selected).to.be(true);
});
});
});
| public/app/core/specs/value_select_dropdown_specs.ts | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017696469149086624,
0.00017441960517317057,
0.0001725226902635768,
0.00017445124103687704,
0.0000012961132824784727
]
|
{
"id": 2,
"code_window": [
"\t\t\tgetDashboardQueries = append(getDashboardQueries, query)\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tbus.AddHandler(\"test\", func(query *m.GetDashboardUidBySlugQuery) error {\n",
"\t\t\tquery.Result = fakeDash.Uid\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tviewerRole := m.ROLE_VIEWER\n",
"\t\teditorRole := m.ROLE_EDITOR\n",
"\n",
"\t\taclMockResp := []*m.DashboardAclInfoDTO{\n",
"\t\t\t{Role: &viewerRole, Permission: m.PERMISSION_VIEW},\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 49
} | .query-keyword {
font-weight: $font-weight-semi-bold;
color: $query-blue;
}
.gf-form-disabled {
.query-keyword {
color: darken($query-blue, 20%);
}
}
.query-segment-operator {
color: $orange;
}
.gf-form-query {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
align-content: flex-start;
align-items: flex-start;
.gf-form,
.gf-form-filler {
margin-bottom: 2px;
}
.gf-form-switch,
.gf-form-switch label,
.gf-form-input,
.gf-form-select-wrapper,
.gf-form-filler,
.gf-form-label {
margin-right: 2px;
}
.gf-form + .gf-form {
margin-right: 0;
}
}
.gf-form-query-content {
flex-grow: 2;
&--collapsed {
overflow: hidden;
.gf-form-label {
overflow: hidden;
text-overflow: ellipsis;
width: 100%;
white-space: nowrap;
}
}
}
.gf-form-query-letter-cell {
.gf-form-query-letter-cell-carret {
display: inline-block;
width: 0.7rem;
position: relative;
left: -2px;
}
.gf-form-query-letter-cell-letter {
font-weight: bold;
color: $query-blue;
}
.gf-form-query-letter-cell-ds {
color: $text-color-weak;
}
}
.gf-query-ds-label {
text-align: center;
width: 44px;
}
.grafana-metric-options {
margin-top: 25px;
}
.tight-form-func {
background: $tight-form-func-bg;
&.show-function-controls {
padding-top: 5px;
min-width: 100px;
text-align: center;
}
}
input[type='text'].tight-form-func-param {
font-size: 0.875rem;
background: transparent;
border: none;
margin: 0;
padding: 0;
}
.tight-form-func-controls {
display: none;
text-align: center;
.fa-arrow-left {
float: left;
position: relative;
top: 2px;
}
.fa-arrow-right {
float: right;
position: relative;
top: 2px;
}
.fa-remove {
margin-left: 10px;
}
}
.grafana-metric-options {
margin-top: 25px;
}
.tight-form-func {
background: $tight-form-func-bg;
&.show-function-controls {
padding-top: 5px;
min-width: 100px;
text-align: center;
}
}
.query-troubleshooter {
font-size: $font-size-sm;
margin: $gf-form-margin;
border: 1px solid $btn-secondary-bg;
min-height: 100px;
border-radius: 3px;
}
.query-troubleshooter__header {
float: right;
font-size: $font-size-sm;
text-align: right;
padding: $input-padding-y $input-padding-x;
a {
margin-left: $spacer;
}
}
.query-troubleshooter__body {
padding: $spacer 0;
}
.rst-text::before {
content: ' ';
}
.rst-unknown.rst-directive {
font-family: monospace;
margin-bottom: 1rem;
}
.rst-interpreted_text {
font-family: monospace;
display: inline;
}
.rst-bullet-list {
padding-left: 1.5rem;
margin-bottom: 1rem;
}
.rst-paragraph:last-child {
margin-bottom: 0;
}
.drop-element.drop-popover.drop-function-def .drop-content {
max-width: 30rem;
}
.rst-literal-block .rst-text {
display: block;
}
| public/sass/components/_query_editor.scss | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017576469690538943,
0.00017292675329372287,
0.00016983141540549695,
0.00017343281069770455,
0.0000016733611118979752
]
|
{
"id": 2,
"code_window": [
"\t\t\tgetDashboardQueries = append(getDashboardQueries, query)\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tbus.AddHandler(\"test\", func(query *m.GetDashboardUidBySlugQuery) error {\n",
"\t\t\tquery.Result = fakeDash.Uid\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tviewerRole := m.ROLE_VIEWER\n",
"\t\teditorRole := m.ROLE_EDITOR\n",
"\n",
"\t\taclMockResp := []*m.DashboardAclInfoDTO{\n",
"\t\t\t{Role: &viewerRole, Permission: m.PERMISSION_VIEW},\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 49
} | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build arm,linux
package unix
import (
"syscall"
"unsafe"
)
func setTimespec(sec, nsec int64) Timespec {
return Timespec{Sec: int32(sec), Nsec: int32(nsec)}
}
func setTimeval(sec, usec int64) Timeval {
return Timeval{Sec: int32(sec), Usec: int32(usec)}
}
func Pipe(p []int) (err error) {
if len(p) != 2 {
return EINVAL
}
var pp [2]_C_int
err = pipe2(&pp, 0)
p[0] = int(pp[0])
p[1] = int(pp[1])
return
}
//sysnb pipe2(p *[2]_C_int, flags int) (err error)
func Pipe2(p []int, flags int) (err error) {
if len(p) != 2 {
return EINVAL
}
var pp [2]_C_int
err = pipe2(&pp, flags)
p[0] = int(pp[0])
p[1] = int(pp[1])
return
}
// Underlying system call writes to newoffset via pointer.
// Implemented in assembly to avoid allocation.
func seek(fd int, offset int64, whence int) (newoffset int64, err syscall.Errno)
func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
newoffset, errno := seek(fd, offset, whence)
if errno != 0 {
return 0, errno
}
return newoffset, nil
}
//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error)
//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error)
//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sysnb getgroups(n int, list *_Gid_t) (nn int, err error) = SYS_GETGROUPS32
//sysnb setgroups(n int, list *_Gid_t) (err error) = SYS_SETGROUPS32
//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error)
//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error)
//sysnb socket(domain int, typ int, proto int) (fd int, err error)
//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error)
//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error)
//sysnb socketpair(domain int, typ int, flags int, fd *[2]int32) (err error)
//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error)
//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error)
// 64-bit file system and 32-bit uid calls
// (16-bit uid calls are not always supported in newer kernels)
//sys Dup2(oldfd int, newfd int) (err error)
//sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32
//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64
//sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64
//sysnb Getegid() (egid int) = SYS_GETEGID32
//sysnb Geteuid() (euid int) = SYS_GETEUID32
//sysnb Getgid() (gid int) = SYS_GETGID32
//sysnb Getuid() (uid int) = SYS_GETUID32
//sysnb InotifyInit() (fd int, err error)
//sys Lchown(path string, uid int, gid int) (err error) = SYS_LCHOWN32
//sys Listen(s int, n int) (err error)
//sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64
//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT
//sys Setfsgid(gid int) (err error) = SYS_SETFSGID32
//sys Setfsuid(uid int) (err error) = SYS_SETFSUID32
//sysnb Setregid(rgid int, egid int) (err error) = SYS_SETREGID32
//sysnb Setresgid(rgid int, egid int, sgid int) (err error) = SYS_SETRESGID32
//sysnb Setresuid(ruid int, euid int, suid int) (err error) = SYS_SETRESUID32
//sysnb Setreuid(ruid int, euid int) (err error) = SYS_SETREUID32
//sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64
// Vsyscalls on amd64.
//sysnb Gettimeofday(tv *Timeval) (err error)
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
//sys Pause() (err error)
func Time(t *Time_t) (Time_t, error) {
var tv Timeval
err := Gettimeofday(&tv)
if err != nil {
return 0, err
}
if t != nil {
*t = Time_t(tv.Sec)
}
return Time_t(tv.Sec), nil
}
func Utime(path string, buf *Utimbuf) error {
tv := []Timeval{
{Sec: buf.Actime},
{Sec: buf.Modtime},
}
return Utimes(path, tv)
}
//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64
//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64
//sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64
//sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64
func Fadvise(fd int, offset int64, length int64, advice int) (err error) {
_, _, e1 := Syscall6(SYS_ARM_FADVISE64_64, uintptr(fd), uintptr(advice), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
//sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error)
func Fstatfs(fd int, buf *Statfs_t) (err error) {
_, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf)))
if e != 0 {
err = e
}
return
}
func Statfs(path string, buf *Statfs_t) (err error) {
pathp, err := BytePtrFromString(path)
if err != nil {
return err
}
_, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(pathp)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf)))
if e != 0 {
err = e
}
return
}
func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) {
page := uintptr(offset / 4096)
if offset != int64(page)*4096 {
return 0, EINVAL
}
return mmap2(addr, length, prot, flags, fd, page)
}
type rlimit32 struct {
Cur uint32
Max uint32
}
//sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_UGETRLIMIT
const rlimInf32 = ^uint32(0)
const rlimInf64 = ^uint64(0)
func Getrlimit(resource int, rlim *Rlimit) (err error) {
err = prlimit(0, resource, nil, rlim)
if err != ENOSYS {
return err
}
rl := rlimit32{}
err = getrlimit(resource, &rl)
if err != nil {
return
}
if rl.Cur == rlimInf32 {
rlim.Cur = rlimInf64
} else {
rlim.Cur = uint64(rl.Cur)
}
if rl.Max == rlimInf32 {
rlim.Max = rlimInf64
} else {
rlim.Max = uint64(rl.Max)
}
return
}
//sysnb setrlimit(resource int, rlim *rlimit32) (err error) = SYS_SETRLIMIT
func Setrlimit(resource int, rlim *Rlimit) (err error) {
err = prlimit(0, resource, rlim, nil)
if err != ENOSYS {
return err
}
rl := rlimit32{}
if rlim.Cur == rlimInf64 {
rl.Cur = rlimInf32
} else if rlim.Cur < uint64(rlimInf32) {
rl.Cur = uint32(rlim.Cur)
} else {
return EINVAL
}
if rlim.Max == rlimInf64 {
rl.Max = rlimInf32
} else if rlim.Max < uint64(rlimInf32) {
rl.Max = uint32(rlim.Max)
} else {
return EINVAL
}
return setrlimit(resource, &rl)
}
func (r *PtraceRegs) PC() uint64 { return uint64(r.Uregs[15]) }
func (r *PtraceRegs) SetPC(pc uint64) { r.Uregs[15] = uint32(pc) }
func (iov *Iovec) SetLen(length int) {
iov.Len = uint32(length)
}
func (msghdr *Msghdr) SetControllen(length int) {
msghdr.Controllen = uint32(length)
}
func (cmsg *Cmsghdr) SetLen(length int) {
cmsg.Len = uint32(length)
}
//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
func Poll(fds []PollFd, timeout int) (n int, err error) {
if len(fds) == 0 {
return poll(nil, 0, timeout)
}
return poll(&fds[0], len(fds), timeout)
}
| vendor/golang.org/x/sys/unix/syscall_linux_arm.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017712489352561533,
0.00017036401550285518,
0.00016019991016946733,
0.00017170910723507404,
0.000004537831955531146
]
|
{
"id": 3,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanSave, ShouldBeFalse)\n",
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeFalse)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n",
"\t\t\t\tConvey(\"Should lookup dashboard by slug\", func() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 111
} | package api
import (
"encoding/json"
"path/filepath"
"testing"
macaron "gopkg.in/macaron.v1"
"github.com/go-macaron/session"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
type fakeDashboardRepo struct {
inserted []*dashboards.SaveDashboardItem
getDashboard []*m.Dashboard
}
func (repo *fakeDashboardRepo) SaveDashboard(json *dashboards.SaveDashboardItem) (*m.Dashboard, error) {
repo.inserted = append(repo.inserted, json)
return json.Dashboard, nil
}
var fakeRepo *fakeDashboardRepo
func TestDashboardApiEndpoint(t *testing.T) {
Convey("Given a dashboard with a parent folder which does not have an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = false
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
viewerRole := m.ROLE_VIEWER
editorRole := m.ROLE_EDITOR
aclMockResp := []*m.DashboardAclInfoDTO{
{Role: &viewerRole, Permission: m.PERMISSION_VIEW},
{Role: &editorRole, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
"id": fakeDash.Id,
}),
}
Convey("When user is an Org Viewer", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
Convey("When saving a dashboard folder in another folder", func() {
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
query.Result.IsFolder = true
return nil
})
invalidCmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
IsFolder: true,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("Should return an error", func() {
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, invalidCmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 400)
})
})
})
})
})
Convey("Given a dashboard with a parent folder which has an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = true
setting.ViewersCanEdit = false
aclMockResp := []*m.DashboardAclInfoDTO{
{
DashboardId: 1,
Permission: m.PERMISSION_EDIT,
UserId: 200,
},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"id": fakeDash.Id,
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("When user is an Org Viewer and has no permissions for this dashboard", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor and has no permissions for this dashboard", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Viewer but has an edit permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Viewer and viewers can edit", func() {
role := m.ROLE_VIEWER
setting.ViewersCanEdit = true
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
})
Convey("When user is an Org Viewer but has an admin permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_ADMIN},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Editor but has a view permission", func() {
role := m.ROLE_EDITOR
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
})
}
func GetDashboardShouldReturn200(sc *scenarioContext) dtos.DashboardFullWithMeta {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
So(sc.resp.Code, ShouldEqual, 200)
dash := dtos.DashboardFullWithMeta{}
err := json.NewDecoder(sc.resp.Body).Decode(&dash)
So(err, ShouldBeNil)
return dash
}
func GetDashboardUidBySlugShouldReturn200(sc *scenarioContext) string {
CallGetDashboardUidBySlug(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
return result.Get("uid").MustString()
}
func CallGetDashboardUidBySlug(sc *scenarioContext) {
sc.handlerFunc = GetDashboardUidBySlug
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersion(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error {
query.Result = &m.DashboardVersion{}
return nil
})
sc.handlerFunc = GetDashboardVersion
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersions(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionsQuery) error {
query.Result = []*m.DashboardVersionDTO{}
return nil
})
sc.handlerFunc = GetDashboardVersions
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallDeleteDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error {
return nil
})
sc.handlerFunc = DeleteDashboard
sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec()
}
func CallPostDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *alerting.ValidateDashboardAlertsCommand) error {
return nil
})
bus.AddHandler("test", func(cmd *m.SaveDashboardCommand) error {
cmd.Result = &m.Dashboard{Id: 2, Slug: "Dash", Version: 2}
return nil
})
bus.AddHandler("test", func(cmd *alerting.UpdateDashboardAlertsCommand) error {
return nil
})
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec()
}
func postDashboardScenario(desc string, url string, routePattern string, role m.RoleType, cmd m.SaveDashboardCommand, fn scenarioFunc) {
Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers()
sc := &scenarioContext{
url: url,
}
viewsPath, _ := filepath.Abs("../../public/views")
sc.m = macaron.New()
sc.m.Use(macaron.Renderer(macaron.RenderOptions{
Directory: viewsPath,
Delims: macaron.Delims{Left: "[[", Right: "]]"},
}))
sc.m.Use(middleware.GetContextHandler())
sc.m.Use(middleware.Sessioner(&session.Options{}))
sc.defaultHandler = wrap(func(c *middleware.Context) Response {
sc.context = c
sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID
sc.context.OrgRole = role
return PostDashboard(c, cmd)
})
fakeRepo = &fakeDashboardRepo{}
dashboards.SetRepository(fakeRepo)
sc.m.Post(routePattern, sc.defaultHandler)
fn(sc)
})
}
func (sc *scenarioContext) ToJson() *simplejson.Json {
var result *simplejson.Json
err := json.NewDecoder(sc.resp.Body).Decode(&result)
So(err, ShouldBeNil)
return result
}
| pkg/api/dashboard_test.go | 1 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.997999370098114,
0.12430800497531891,
0.0001677653199294582,
0.006170196458697319,
0.2914065420627594
]
|
{
"id": 3,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanSave, ShouldBeFalse)\n",
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeFalse)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n",
"\t\t\t\tConvey(\"Should lookup dashboard by slug\", func() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 111
} | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
package unix
import "time"
// TimespecToNsec converts a Timespec value into a number of
// nanoseconds since the Unix epoch.
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
// NsecToTimespec takes a number of nanoseconds since the Unix epoch
// and returns the corresponding Timespec value.
func NsecToTimespec(nsec int64) Timespec {
sec := nsec / 1e9
nsec = nsec % 1e9
if nsec < 0 {
nsec += 1e9
sec--
}
return setTimespec(sec, nsec)
}
// TimeToTimespec converts t into a Timespec.
// On some 32-bit systems the range of valid Timespec values are smaller
// than that of time.Time values. So if t is out of the valid range of
// Timespec, it returns a zero Timespec and ERANGE.
func TimeToTimespec(t time.Time) (Timespec, error) {
sec := t.Unix()
nsec := int64(t.Nanosecond())
ts := setTimespec(sec, nsec)
// Currently all targets have either int32 or int64 for Timespec.Sec.
// If there were a new target with floating point type for it, we have
// to consider the rounding error.
if int64(ts.Sec) != sec {
return Timespec{}, ERANGE
}
return ts, nil
}
// TimevalToNsec converts a Timeval value into a number of nanoseconds
// since the Unix epoch.
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
// NsecToTimeval takes a number of nanoseconds since the Unix epoch
// and returns the corresponding Timeval value.
func NsecToTimeval(nsec int64) Timeval {
nsec += 999 // round up to microsecond
usec := nsec % 1e9 / 1e3
sec := nsec / 1e9
if usec < 0 {
usec += 1e6
sec--
}
return setTimeval(sec, usec)
}
// Unix returns ts as the number of seconds and nanoseconds elapsed since the
// Unix epoch.
func (ts *Timespec) Unix() (sec int64, nsec int64) {
return int64(ts.Sec), int64(ts.Nsec)
}
// Unix returns tv as the number of seconds and nanoseconds elapsed since the
// Unix epoch.
func (tv *Timeval) Unix() (sec int64, nsec int64) {
return int64(tv.Sec), int64(tv.Usec) * 1000
}
// Nano returns ts as the number of nanoseconds elapsed since the Unix epoch.
func (ts *Timespec) Nano() int64 {
return int64(ts.Sec)*1e9 + int64(ts.Nsec)
}
// Nano returns tv as the number of nanoseconds elapsed since the Unix epoch.
func (tv *Timeval) Nano() int64 {
return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000
}
| vendor/golang.org/x/sys/unix/timestruct.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017268101510126144,
0.00016710411000531167,
0.00016216667427215725,
0.00016664578288327903,
0.000002831830215654918
]
|
{
"id": 3,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanSave, ShouldBeFalse)\n",
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeFalse)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n",
"\t\t\t\tConvey(\"Should lookup dashboard by slug\", func() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 111
} | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Socket control messages
package unix
import "unsafe"
// UnixCredentials encodes credentials into a socket control message
// for sending to another process. This can be used for
// authentication.
func UnixCredentials(ucred *Ucred) []byte {
b := make([]byte, CmsgSpace(SizeofUcred))
h := (*Cmsghdr)(unsafe.Pointer(&b[0]))
h.Level = SOL_SOCKET
h.Type = SCM_CREDENTIALS
h.SetLen(CmsgLen(SizeofUcred))
*((*Ucred)(cmsgData(h))) = *ucred
return b
}
// ParseUnixCredentials decodes a socket control message that contains
// credentials in a Ucred structure. To receive such a message, the
// SO_PASSCRED option must be enabled on the socket.
func ParseUnixCredentials(m *SocketControlMessage) (*Ucred, error) {
if m.Header.Level != SOL_SOCKET {
return nil, EINVAL
}
if m.Header.Type != SCM_CREDENTIALS {
return nil, EINVAL
}
ucred := *(*Ucred)(unsafe.Pointer(&m.Data[0]))
return &ucred, nil
}
| vendor/golang.org/x/sys/unix/sockcmsg_linux.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017060544632840902,
0.00016644757124595344,
0.00016022207273636013,
0.0001674813829595223,
0.000004154778252996039
]
|
{
"id": 3,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanSave, ShouldBeFalse)\n",
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeFalse)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n",
"\t\t\t\tConvey(\"Should lookup dashboard by slug\", func() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 111
} | FROM nginx:alpine
COPY nginx.conf /etc/nginx/nginx.conf | docker/blocks/nginx_proxy/Dockerfile | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.0001644405274419114,
0.0001644405274419114,
0.0001644405274419114,
0.0001644405274419114,
0
]
|
{
"id": 4,
"code_window": [
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 200)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 175
} | package api
import (
"encoding/json"
"path/filepath"
"testing"
macaron "gopkg.in/macaron.v1"
"github.com/go-macaron/session"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
type fakeDashboardRepo struct {
inserted []*dashboards.SaveDashboardItem
getDashboard []*m.Dashboard
}
func (repo *fakeDashboardRepo) SaveDashboard(json *dashboards.SaveDashboardItem) (*m.Dashboard, error) {
repo.inserted = append(repo.inserted, json)
return json.Dashboard, nil
}
var fakeRepo *fakeDashboardRepo
func TestDashboardApiEndpoint(t *testing.T) {
Convey("Given a dashboard with a parent folder which does not have an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = false
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
viewerRole := m.ROLE_VIEWER
editorRole := m.ROLE_EDITOR
aclMockResp := []*m.DashboardAclInfoDTO{
{Role: &viewerRole, Permission: m.PERMISSION_VIEW},
{Role: &editorRole, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
"id": fakeDash.Id,
}),
}
Convey("When user is an Org Viewer", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
Convey("When saving a dashboard folder in another folder", func() {
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
query.Result.IsFolder = true
return nil
})
invalidCmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
IsFolder: true,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("Should return an error", func() {
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, invalidCmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 400)
})
})
})
})
})
Convey("Given a dashboard with a parent folder which has an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = true
setting.ViewersCanEdit = false
aclMockResp := []*m.DashboardAclInfoDTO{
{
DashboardId: 1,
Permission: m.PERMISSION_EDIT,
UserId: 200,
},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"id": fakeDash.Id,
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("When user is an Org Viewer and has no permissions for this dashboard", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor and has no permissions for this dashboard", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Viewer but has an edit permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Viewer and viewers can edit", func() {
role := m.ROLE_VIEWER
setting.ViewersCanEdit = true
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
})
Convey("When user is an Org Viewer but has an admin permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_ADMIN},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Editor but has a view permission", func() {
role := m.ROLE_EDITOR
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
})
}
func GetDashboardShouldReturn200(sc *scenarioContext) dtos.DashboardFullWithMeta {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
So(sc.resp.Code, ShouldEqual, 200)
dash := dtos.DashboardFullWithMeta{}
err := json.NewDecoder(sc.resp.Body).Decode(&dash)
So(err, ShouldBeNil)
return dash
}
func GetDashboardUidBySlugShouldReturn200(sc *scenarioContext) string {
CallGetDashboardUidBySlug(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
return result.Get("uid").MustString()
}
func CallGetDashboardUidBySlug(sc *scenarioContext) {
sc.handlerFunc = GetDashboardUidBySlug
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersion(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error {
query.Result = &m.DashboardVersion{}
return nil
})
sc.handlerFunc = GetDashboardVersion
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersions(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionsQuery) error {
query.Result = []*m.DashboardVersionDTO{}
return nil
})
sc.handlerFunc = GetDashboardVersions
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallDeleteDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error {
return nil
})
sc.handlerFunc = DeleteDashboard
sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec()
}
func CallPostDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *alerting.ValidateDashboardAlertsCommand) error {
return nil
})
bus.AddHandler("test", func(cmd *m.SaveDashboardCommand) error {
cmd.Result = &m.Dashboard{Id: 2, Slug: "Dash", Version: 2}
return nil
})
bus.AddHandler("test", func(cmd *alerting.UpdateDashboardAlertsCommand) error {
return nil
})
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec()
}
func postDashboardScenario(desc string, url string, routePattern string, role m.RoleType, cmd m.SaveDashboardCommand, fn scenarioFunc) {
Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers()
sc := &scenarioContext{
url: url,
}
viewsPath, _ := filepath.Abs("../../public/views")
sc.m = macaron.New()
sc.m.Use(macaron.Renderer(macaron.RenderOptions{
Directory: viewsPath,
Delims: macaron.Delims{Left: "[[", Right: "]]"},
}))
sc.m.Use(middleware.GetContextHandler())
sc.m.Use(middleware.Sessioner(&session.Options{}))
sc.defaultHandler = wrap(func(c *middleware.Context) Response {
sc.context = c
sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID
sc.context.OrgRole = role
return PostDashboard(c, cmd)
})
fakeRepo = &fakeDashboardRepo{}
dashboards.SetRepository(fakeRepo)
sc.m.Post(routePattern, sc.defaultHandler)
fn(sc)
})
}
func (sc *scenarioContext) ToJson() *simplejson.Json {
var result *simplejson.Json
err := json.NewDecoder(sc.resp.Body).Decode(&result)
So(err, ShouldBeNil)
return result
}
| pkg/api/dashboard_test.go | 1 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.9984226226806641,
0.20564353466033936,
0.00016604605480097234,
0.008598041720688343,
0.3596327304840088
]
|
{
"id": 4,
"code_window": [
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 200)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 175
} | [cache]
LOCAL_DATA_DIR = /opt/graphite/storage/whisper/
# Specify the user to drop privileges to
# If this is blank carbon runs as the user that invokes it
# This user must have write access to the local data directory
USER =
# Limit the size of the cache to avoid swapping or becoming CPU bound.
# Sorts and serving cache queries gets more expensive as the cache grows.
# Use the value "inf" (infinity) for an unlimited cache size.
MAX_CACHE_SIZE = inf
# Limits the number of whisper update_many() calls per second, which effectively
# means the number of write requests sent to the disk. This is intended to
# prevent over-utilizing the disk and thus starving the rest of the system.
# When the rate of required updates exceeds this, then carbon's caching will
# take effect and increase the overall throughput accordingly.
MAX_UPDATES_PER_SECOND = 1000
# Softly limits the number of whisper files that get created each minute.
# Setting this value low (like at 50) is a good way to ensure your graphite
# system will not be adversely impacted when a bunch of new metrics are
# sent to it. The trade off is that it will take much longer for those metrics'
# database files to all get created and thus longer until the data becomes usable.
# Setting this value high (like "inf" for infinity) will cause graphite to create
# the files quickly but at the risk of slowing I/O down considerably for a while.
MAX_CREATES_PER_MINUTE = inf
LINE_RECEIVER_INTERFACE = 0.0.0.0
LINE_RECEIVER_PORT = 2003
PICKLE_RECEIVER_INTERFACE = 0.0.0.0
PICKLE_RECEIVER_PORT = 2004
CACHE_QUERY_INTERFACE = 0.0.0.0
CACHE_QUERY_PORT = 7002
LOG_UPDATES = False
# Enable AMQP if you want to receve metrics using an amqp broker
# ENABLE_AMQP = False
# Verbose means a line will be logged for every metric received
# useful for testing
# AMQP_VERBOSE = False
# AMQP_HOST = localhost
# AMQP_PORT = 5672
# AMQP_VHOST = /
# AMQP_USER = guest
# AMQP_PASSWORD = guest
# AMQP_EXCHANGE = graphite
# Patterns for all of the metrics this machine will store. Read more at
# http://en.wikipedia.org/wiki/Advanced_Message_Queuing_Protocol#Bindings
#
# Example: store all sales, linux servers, and utilization metrics
# BIND_PATTERNS = sales.#, servers.linux.#, #.utilization
#
# Example: store everything
# BIND_PATTERNS = #
# NOTE: you cannot run both a cache and a relay on the same server
# with the default configuration, you have to specify a distinict
# interfaces and ports for the listeners.
[relay]
LINE_RECEIVER_INTERFACE = 0.0.0.0
LINE_RECEIVER_PORT = 2003
PICKLE_RECEIVER_INTERFACE = 0.0.0.0
PICKLE_RECEIVER_PORT = 2004
CACHE_SERVERS = server1, server2, server3
MAX_QUEUE_SIZE = 10000
| docker/blocks/graphite/files/carbon.conf | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.0004463866353034973,
0.00020543148275464773,
0.00016316151595674455,
0.00017140238196589053,
0.00009137389133684337
]
|
{
"id": 4,
"code_window": [
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 200)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 175
} | .table-panel-wrapper {
.panel-content {
padding: 0;
}
.panel-title-container {
padding-bottom: 4px;
}
}
.table-panel-scroll {
overflow: auto;
}
.table-panel-container {
padding-top: 2.2em;
position: relative;
}
.table-panel-footer {
text-align: center;
font-size: 90%;
line-height: 2px;
ul {
position: relative;
display: inline-block;
margin-left: 0;
margin-bottom: 0;
}
ul > li {
display: inline; // Remove list-style and block-level defaults
}
ul > li > a {
float: left; // Collapse white-space
padding: 4px 12px;
text-decoration: none;
border-left-width: 0;
&:hover {
background-color: $tight-form-func-bg;
}
&.active {
font-weight: bold;
color: $blue;
}
}
}
.table-panel-table {
width: 100%;
border-collapse: collapse;
th {
padding: 0;
&:first-child {
.table-panel-table-header-inner {
padding-left: 15px;
}
}
}
td {
padding: 0.45em 0 0.45em 1.1em;
border-bottom: 2px solid $body-bg;
border-right: 2px solid $body-bg;
&:first-child {
padding-left: 15px;
}
&:last-child {
border-right: none;
}
&.table-panel-cell-pre {
white-space: pre;
}
&.table-panel-cell-link {
// Expand internal div to cell size (make all cell clickable)
padding: 0;
a {
padding: 0.45em 0 0.45em 1.1em;
height: 100%;
display: inline-block;
}
}
&.cell-highlighted:hover {
background-color: $tight-form-func-bg;
}
&:hover {
.table-panel-filter-link {
visibility: visible;
}
}
}
}
.table-panel-filter-link {
visibility: hidden;
color: $text-color-weak;
float: right;
display: block;
padding: 0 5px;
}
.table-panel-header-bg {
background: $list-item-bg;
border-top: 2px solid $body-bg;
border-bottom: 2px solid $body-bg;
height: 2em;
position: absolute;
top: 0;
right: 0;
left: 0;
}
.table-panel-table-header-inner {
padding: 0.45em 0 0.45em 1.1em;
text-align: left;
color: $blue;
position: absolute;
top: 0;
}
.table-panel-width-hack {
visibility: hidden;
height: 0px;
line-height: 0px;
}
| public/sass/components/_panel_table.scss | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.0001754987461026758,
0.00017244364426005632,
0.00016771636728662997,
0.0001725627516862005,
0.0000020467293779802276
]
|
{
"id": 4,
"code_window": [
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 200)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 175
} | // +build appengine plan9
package request
import (
"strings"
)
func isErrConnectionReset(err error) bool {
return strings.Contains(err.Error(), "connection reset")
}
| vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00016625678108539432,
0.0001654995430726558,
0.0001647423196118325,
0.0001654995430726558,
7.572307367809117e-7
]
|
{
"id": 5,
"code_window": [
"\t\t\tgetDashboardQueries = append(getDashboardQueries, query)\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tbus.AddHandler(\"test\", func(query *m.GetDashboardUidBySlugQuery) error {\n",
"\t\t\tquery.Result = fakeDash.Uid\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tbus.AddHandler(\"test\", func(query *m.GetTeamsByUserQuery) error {\n",
"\t\t\tquery.Result = []*m.Team{}\n",
"\t\t\treturn nil\n",
"\t\t})\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 264
} | package api
import (
"encoding/json"
"path/filepath"
"testing"
macaron "gopkg.in/macaron.v1"
"github.com/go-macaron/session"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
type fakeDashboardRepo struct {
inserted []*dashboards.SaveDashboardItem
getDashboard []*m.Dashboard
}
func (repo *fakeDashboardRepo) SaveDashboard(json *dashboards.SaveDashboardItem) (*m.Dashboard, error) {
repo.inserted = append(repo.inserted, json)
return json.Dashboard, nil
}
var fakeRepo *fakeDashboardRepo
func TestDashboardApiEndpoint(t *testing.T) {
Convey("Given a dashboard with a parent folder which does not have an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = false
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
viewerRole := m.ROLE_VIEWER
editorRole := m.ROLE_EDITOR
aclMockResp := []*m.DashboardAclInfoDTO{
{Role: &viewerRole, Permission: m.PERMISSION_VIEW},
{Role: &editorRole, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
"id": fakeDash.Id,
}),
}
Convey("When user is an Org Viewer", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
Convey("When saving a dashboard folder in another folder", func() {
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
query.Result.IsFolder = true
return nil
})
invalidCmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
IsFolder: true,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("Should return an error", func() {
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, invalidCmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 400)
})
})
})
})
})
Convey("Given a dashboard with a parent folder which has an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = true
setting.ViewersCanEdit = false
aclMockResp := []*m.DashboardAclInfoDTO{
{
DashboardId: 1,
Permission: m.PERMISSION_EDIT,
UserId: 200,
},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"id": fakeDash.Id,
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("When user is an Org Viewer and has no permissions for this dashboard", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor and has no permissions for this dashboard", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Viewer but has an edit permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Viewer and viewers can edit", func() {
role := m.ROLE_VIEWER
setting.ViewersCanEdit = true
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
})
Convey("When user is an Org Viewer but has an admin permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_ADMIN},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Editor but has a view permission", func() {
role := m.ROLE_EDITOR
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
})
}
func GetDashboardShouldReturn200(sc *scenarioContext) dtos.DashboardFullWithMeta {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
So(sc.resp.Code, ShouldEqual, 200)
dash := dtos.DashboardFullWithMeta{}
err := json.NewDecoder(sc.resp.Body).Decode(&dash)
So(err, ShouldBeNil)
return dash
}
func GetDashboardUidBySlugShouldReturn200(sc *scenarioContext) string {
CallGetDashboardUidBySlug(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
return result.Get("uid").MustString()
}
func CallGetDashboardUidBySlug(sc *scenarioContext) {
sc.handlerFunc = GetDashboardUidBySlug
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersion(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error {
query.Result = &m.DashboardVersion{}
return nil
})
sc.handlerFunc = GetDashboardVersion
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersions(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionsQuery) error {
query.Result = []*m.DashboardVersionDTO{}
return nil
})
sc.handlerFunc = GetDashboardVersions
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallDeleteDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error {
return nil
})
sc.handlerFunc = DeleteDashboard
sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec()
}
func CallPostDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *alerting.ValidateDashboardAlertsCommand) error {
return nil
})
bus.AddHandler("test", func(cmd *m.SaveDashboardCommand) error {
cmd.Result = &m.Dashboard{Id: 2, Slug: "Dash", Version: 2}
return nil
})
bus.AddHandler("test", func(cmd *alerting.UpdateDashboardAlertsCommand) error {
return nil
})
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec()
}
func postDashboardScenario(desc string, url string, routePattern string, role m.RoleType, cmd m.SaveDashboardCommand, fn scenarioFunc) {
Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers()
sc := &scenarioContext{
url: url,
}
viewsPath, _ := filepath.Abs("../../public/views")
sc.m = macaron.New()
sc.m.Use(macaron.Renderer(macaron.RenderOptions{
Directory: viewsPath,
Delims: macaron.Delims{Left: "[[", Right: "]]"},
}))
sc.m.Use(middleware.GetContextHandler())
sc.m.Use(middleware.Sessioner(&session.Options{}))
sc.defaultHandler = wrap(func(c *middleware.Context) Response {
sc.context = c
sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID
sc.context.OrgRole = role
return PostDashboard(c, cmd)
})
fakeRepo = &fakeDashboardRepo{}
dashboards.SetRepository(fakeRepo)
sc.m.Post(routePattern, sc.defaultHandler)
fn(sc)
})
}
func (sc *scenarioContext) ToJson() *simplejson.Json {
var result *simplejson.Json
err := json.NewDecoder(sc.resp.Body).Decode(&result)
So(err, ShouldBeNil)
return result
}
| pkg/api/dashboard_test.go | 1 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.9973589777946472,
0.034280624240636826,
0.00016295908426400274,
0.0031180246733129025,
0.1527843475341797
]
|
{
"id": 5,
"code_window": [
"\t\t\tgetDashboardQueries = append(getDashboardQueries, query)\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tbus.AddHandler(\"test\", func(query *m.GetDashboardUidBySlugQuery) error {\n",
"\t\t\tquery.Result = fakeDash.Uid\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tbus.AddHandler(\"test\", func(query *m.GetTeamsByUserQuery) error {\n",
"\t\t\tquery.Result = []*m.Team{}\n",
"\t\t\treturn nil\n",
"\t\t})\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 264
} | .playlist-description {
width: 555px;
margin-bottom: 20px;
}
.playlist-search-container {
z-index: 1000;
position: relative;
width: 700px;
box-shadow: 0px 0px 55px 0px black;
background-color: $panel-bg;
.label-tag {
margin-left: 6px;
font-size: 11px;
padding: 2px 6px;
}
}
.playlist-search-switches {
position: absolute;
top: 8px;
right: 11px;
}
.playlist-search-containerwrapper {
margin-bottom: 15px;
}
.playlist-search-field-wrapper {
input {
width: 100%;
padding: 8px 8px;
height: 100%;
box-sizing: border-box;
}
button {
margin: 0 4px 0 0;
}
> span {
display: block;
overflow: hidden;
}
}
.playlist-search-results-container {
min-height: 100px;
overflow: auto;
display: block;
line-height: 28px;
.search-item:hover,
.search-item.selected {
background-color: $list-item-hover-bg;
}
.selected {
.search-result-tag {
opacity: 0.7;
color: white;
}
}
.fa-star,
.fa-star-o {
padding-left: 13px;
}
.fa-star {
color: $orange;
}
.search-result-link {
color: $list-item-link-color;
.fa {
padding-right: 10px;
}
}
.search-item {
display: block;
padding: 3px 10px;
white-space: nowrap;
background-color: $list-item-bg;
margin-bottom: 4px;
.search-result-icon:before {
content: "\f009";
}
&.search-item-dash-home .search-result-icon:before {
content: "\f015";
}
}
.search-result-tags {
float: right;
}
.search-result-actions {
float: right;
padding-left: 20px;
}
}
.playlist-available-list {
td {
line-height: 2rem;
white-space: nowrap;
}
.add-dashboard {
text-align: center;
}
.fa-star {
color: $orange;
}
}
.playlist-column-header {
border-bottom: thin solid $gray-1;
padding-bottom: 3px;
margin-bottom: 15px;
}
.selected-playlistitem-settings {
text-align: right;
}
| public/sass/pages/_playlist.scss | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017996312817558646,
0.00017636941629461944,
0.0001719636347843334,
0.00017736184236127883,
0.0000022321553387882886
]
|
{
"id": 5,
"code_window": [
"\t\t\tgetDashboardQueries = append(getDashboardQueries, query)\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tbus.AddHandler(\"test\", func(query *m.GetDashboardUidBySlugQuery) error {\n",
"\t\t\tquery.Result = fakeDash.Uid\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tbus.AddHandler(\"test\", func(query *m.GetTeamsByUserQuery) error {\n",
"\t\t\tquery.Result = []*m.Team{}\n",
"\t\t\treturn nil\n",
"\t\t})\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 264
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`CollorPalette renders correctly 1`] = `
<div
className="graph-legend-popover"
>
<p
className="m-b-0"
>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#890f02",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#58140c",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#99440a",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#c15c17",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#967302",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#cca300",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#3f6833",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#2f575e",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#64b0c8",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#052b51",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#0a50a1",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#584477",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#3f2b5b",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#511749",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#e24d42",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#bf1b00",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#ef843c",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#f4d598",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#e5ac0e",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#9ac48a",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#508642",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#6ed0e0",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#65c5db",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#0a437c",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#447ebc",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#614d93",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#d683ce",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#6d1f62",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#ea6460",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#e0752d",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#f9934e",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#fceaca",
}
}
>
</i>
<i
className="pointer fa fa-circle-o"
onClick={[Function]}
style={
Object {
"color": "#eab839",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#b7dbab",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#629e51",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#70dbed",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#82b5d8",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#1f78c1",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#aea2e0",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#705da0",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#e5a8e2",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#962d82",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#f29191",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#fce2de",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#f9ba8f",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#f9e2d2",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#f2c96d",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#e0f9d7",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#7eb26d",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#cffaff",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#badff4",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#5195ce",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#dedaf7",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#806eb7",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#f9d9f9",
}
}
>
</i>
<i
className="pointer fa fa-circle"
onClick={[Function]}
style={
Object {
"color": "#ba43a9",
}
}
>
</i>
</p>
</div>
`;
| public/app/core/specs/__snapshots__/ColorPalette.jest.tsx.snap | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017695946735329926,
0.00017444837430957705,
0.00017242385365534574,
0.00017459210357628763,
9.58382543103653e-7
]
|
{
"id": 5,
"code_window": [
"\t\t\tgetDashboardQueries = append(getDashboardQueries, query)\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tbus.AddHandler(\"test\", func(query *m.GetDashboardUidBySlugQuery) error {\n",
"\t\t\tquery.Result = fakeDash.Uid\n",
"\t\t\treturn nil\n",
"\t\t})\n",
"\n",
"\t\tbus.AddHandler(\"test\", func(query *m.GetTeamsByUserQuery) error {\n",
"\t\t\tquery.Result = []*m.Team{}\n",
"\t\t\treturn nil\n",
"\t\t})\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 264
} | // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in the
// LICENSE file.
// +build appengine
package websocket
func maskBytes(key [4]byte, pos int, b []byte) int {
for i := range b {
b[i] ^= key[pos&3]
pos++
}
return pos & 3
}
| vendor/github.com/gorilla/websocket/mask_safe.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017785753880161792,
0.0001771536481101066,
0.00017644977197051048,
0.0001771536481101066,
7.038834155537188e-7
]
|
{
"id": 6,
"code_window": [
"\t\t\t\tConvey(\"Should be denied access\", func() {\n",
"\t\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallGetDashboardUidBySlug(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should be denied access\", func() {\n",
"\t\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 312
} | package api
import (
"github.com/go-macaron/binding"
"github.com/grafana/grafana/pkg/api/avatar"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
)
// Register adds http routes
func (hs *HttpServer) registerRoutes() {
macaronR := hs.macaron
reqSignedIn := middleware.Auth(&middleware.AuthOptions{ReqSignedIn: true})
reqGrafanaAdmin := middleware.Auth(&middleware.AuthOptions{ReqSignedIn: true, ReqGrafanaAdmin: true})
reqEditorRole := middleware.RoleAuth(m.ROLE_EDITOR, m.ROLE_ADMIN)
reqOrgAdmin := middleware.RoleAuth(m.ROLE_ADMIN)
quota := middleware.Quota
bind := binding.Bind
// automatically set HEAD for every GET
macaronR.SetAutoHead(true)
r := newRouteRegister(middleware.RequestMetrics, middleware.RequestTracing)
// not logged in views
r.Get("/", reqSignedIn, Index)
r.Get("/logout", Logout)
r.Post("/login", quota("session"), bind(dtos.LoginCommand{}), wrap(LoginPost))
r.Get("/login/:name", quota("session"), OAuthLogin)
r.Get("/login", LoginView)
r.Get("/invite/:code", Index)
// authed views
r.Get("/profile/", reqSignedIn, Index)
r.Get("/profile/password", reqSignedIn, Index)
r.Get("/profile/switch-org/:id", reqSignedIn, ChangeActiveOrgAndRedirectToHome)
r.Get("/org/", reqSignedIn, Index)
r.Get("/org/new", reqSignedIn, Index)
r.Get("/datasources/", reqSignedIn, Index)
r.Get("/datasources/new", reqSignedIn, Index)
r.Get("/datasources/edit/*", reqSignedIn, Index)
r.Get("/org/users", reqSignedIn, Index)
r.Get("/org/users/new", reqSignedIn, Index)
r.Get("/org/users/invite", reqSignedIn, Index)
r.Get("/org/teams", reqSignedIn, Index)
r.Get("/org/teams/*", reqSignedIn, Index)
r.Get("/org/apikeys/", reqSignedIn, Index)
r.Get("/dashboard/import/", reqSignedIn, Index)
r.Get("/configuration", reqGrafanaAdmin, Index)
r.Get("/admin", reqGrafanaAdmin, Index)
r.Get("/admin/settings", reqGrafanaAdmin, Index)
r.Get("/admin/users", reqGrafanaAdmin, Index)
r.Get("/admin/users/create", reqGrafanaAdmin, Index)
r.Get("/admin/users/edit/:id", reqGrafanaAdmin, Index)
r.Get("/admin/orgs", reqGrafanaAdmin, Index)
r.Get("/admin/orgs/edit/:id", reqGrafanaAdmin, Index)
r.Get("/admin/stats", reqGrafanaAdmin, Index)
r.Get("/styleguide", reqSignedIn, Index)
r.Get("/plugins", reqSignedIn, Index)
r.Get("/plugins/:id/edit", reqSignedIn, Index)
r.Get("/plugins/:id/page/:page", reqSignedIn, Index)
r.Get("/dashboard/*", reqSignedIn, Index)
r.Get("/dashboard-solo/snapshot/*", Index)
r.Get("/dashboard-solo/*", reqSignedIn, Index)
r.Get("/import/dashboard", reqSignedIn, Index)
r.Get("/dashboards/", reqSignedIn, Index)
r.Get("/dashboards/*", reqSignedIn, Index)
r.Get("/playlists/", reqSignedIn, Index)
r.Get("/playlists/*", reqSignedIn, Index)
r.Get("/alerting/", reqSignedIn, Index)
r.Get("/alerting/*", reqSignedIn, Index)
// sign up
r.Get("/signup", Index)
r.Get("/api/user/signup/options", wrap(GetSignUpOptions))
r.Post("/api/user/signup", quota("user"), bind(dtos.SignUpForm{}), wrap(SignUp))
r.Post("/api/user/signup/step2", bind(dtos.SignUpStep2Form{}), wrap(SignUpStep2))
// invited
r.Get("/api/user/invite/:code", wrap(GetInviteInfoByCode))
r.Post("/api/user/invite/complete", bind(dtos.CompleteInviteForm{}), wrap(CompleteInvite))
// reset password
r.Get("/user/password/send-reset-email", Index)
r.Get("/user/password/reset", Index)
r.Post("/api/user/password/send-reset-email", bind(dtos.SendResetPasswordEmailForm{}), wrap(SendResetPasswordEmail))
r.Post("/api/user/password/reset", bind(dtos.ResetUserPasswordForm{}), wrap(ResetPassword))
// dashboard snapshots
r.Get("/dashboard/snapshot/*", Index)
r.Get("/dashboard/snapshots/", reqSignedIn, Index)
// api for dashboard snapshots
r.Post("/api/snapshots/", bind(m.CreateDashboardSnapshotCommand{}), CreateDashboardSnapshot)
r.Get("/api/snapshot/shared-options/", GetSharingOptions)
r.Get("/api/snapshots/:key", GetDashboardSnapshot)
r.Get("/api/snapshots-delete/:key", reqEditorRole, DeleteDashboardSnapshot)
// api renew session based on remember cookie
r.Get("/api/login/ping", quota("session"), LoginApiPing)
// authed api
r.Group("/api", func(apiRoute RouteRegister) {
// user (signed in)
apiRoute.Group("/user", func(userRoute RouteRegister) {
userRoute.Get("/", wrap(GetSignedInUser))
userRoute.Put("/", bind(m.UpdateUserCommand{}), wrap(UpdateSignedInUser))
userRoute.Post("/using/:id", wrap(UserSetUsingOrg))
userRoute.Get("/orgs", wrap(GetSignedInUserOrgList))
userRoute.Post("/stars/dashboard/:id", wrap(StarDashboard))
userRoute.Delete("/stars/dashboard/:id", wrap(UnstarDashboard))
userRoute.Put("/password", bind(m.ChangeUserPasswordCommand{}), wrap(ChangeUserPassword))
userRoute.Get("/quotas", wrap(GetUserQuotas))
userRoute.Put("/helpflags/:id", wrap(SetHelpFlag))
// For dev purpose
userRoute.Get("/helpflags/clear", wrap(ClearHelpFlags))
userRoute.Get("/preferences", wrap(GetUserPreferences))
userRoute.Put("/preferences", bind(dtos.UpdatePrefsCmd{}), wrap(UpdateUserPreferences))
})
// users (admin permission required)
apiRoute.Group("/users", func(usersRoute RouteRegister) {
usersRoute.Get("/", wrap(SearchUsers))
usersRoute.Get("/search", wrap(SearchUsersWithPaging))
usersRoute.Get("/:id", wrap(GetUserById))
usersRoute.Get("/:id/orgs", wrap(GetUserOrgList))
// query parameters /users/[email protected]
usersRoute.Get("/lookup", wrap(GetUserByLoginOrEmail))
usersRoute.Put("/:id", bind(m.UpdateUserCommand{}), wrap(UpdateUser))
usersRoute.Post("/:id/using/:orgId", wrap(UpdateUserActiveOrg))
}, reqGrafanaAdmin)
// team (admin permission required)
apiRoute.Group("/teams", func(teamsRoute RouteRegister) {
teamsRoute.Get("/:teamId", wrap(GetTeamById))
teamsRoute.Get("/search", wrap(SearchTeams))
teamsRoute.Post("/", quota("teams"), bind(m.CreateTeamCommand{}), wrap(CreateTeam))
teamsRoute.Put("/:teamId", bind(m.UpdateTeamCommand{}), wrap(UpdateTeam))
teamsRoute.Delete("/:teamId", wrap(DeleteTeamById))
teamsRoute.Get("/:teamId/members", wrap(GetTeamMembers))
teamsRoute.Post("/:teamId/members", quota("teams"), bind(m.AddTeamMemberCommand{}), wrap(AddTeamMember))
teamsRoute.Delete("/:teamId/members/:userId", wrap(RemoveTeamMember))
}, reqOrgAdmin)
// org information available to all users.
apiRoute.Group("/org", func(orgRoute RouteRegister) {
orgRoute.Get("/", wrap(GetOrgCurrent))
orgRoute.Get("/quotas", wrap(GetOrgQuotas))
})
// current org
apiRoute.Group("/org", func(orgRoute RouteRegister) {
orgRoute.Put("/", bind(dtos.UpdateOrgForm{}), wrap(UpdateOrgCurrent))
orgRoute.Put("/address", bind(dtos.UpdateOrgAddressForm{}), wrap(UpdateOrgAddressCurrent))
orgRoute.Post("/users", quota("user"), bind(m.AddOrgUserCommand{}), wrap(AddOrgUserToCurrentOrg))
orgRoute.Get("/users", wrap(GetOrgUsersForCurrentOrg))
orgRoute.Patch("/users/:userId", bind(m.UpdateOrgUserCommand{}), wrap(UpdateOrgUserForCurrentOrg))
orgRoute.Delete("/users/:userId", wrap(RemoveOrgUserForCurrentOrg))
// invites
orgRoute.Get("/invites", wrap(GetPendingOrgInvites))
orgRoute.Post("/invites", quota("user"), bind(dtos.AddInviteForm{}), wrap(AddOrgInvite))
orgRoute.Patch("/invites/:code/revoke", wrap(RevokeInvite))
// prefs
orgRoute.Get("/preferences", wrap(GetOrgPreferences))
orgRoute.Put("/preferences", bind(dtos.UpdatePrefsCmd{}), wrap(UpdateOrgPreferences))
}, reqOrgAdmin)
// create new org
apiRoute.Post("/orgs", quota("org"), bind(m.CreateOrgCommand{}), wrap(CreateOrg))
// search all orgs
apiRoute.Get("/orgs", reqGrafanaAdmin, wrap(SearchOrgs))
// orgs (admin routes)
apiRoute.Group("/orgs/:orgId", func(orgsRoute RouteRegister) {
orgsRoute.Get("/", wrap(GetOrgById))
orgsRoute.Put("/", bind(dtos.UpdateOrgForm{}), wrap(UpdateOrg))
orgsRoute.Put("/address", bind(dtos.UpdateOrgAddressForm{}), wrap(UpdateOrgAddress))
orgsRoute.Delete("/", wrap(DeleteOrgById))
orgsRoute.Get("/users", wrap(GetOrgUsers))
orgsRoute.Post("/users", bind(m.AddOrgUserCommand{}), wrap(AddOrgUser))
orgsRoute.Patch("/users/:userId", bind(m.UpdateOrgUserCommand{}), wrap(UpdateOrgUser))
orgsRoute.Delete("/users/:userId", wrap(RemoveOrgUser))
orgsRoute.Get("/quotas", wrap(GetOrgQuotas))
orgsRoute.Put("/quotas/:target", bind(m.UpdateOrgQuotaCmd{}), wrap(UpdateOrgQuota))
}, reqGrafanaAdmin)
// orgs (admin routes)
apiRoute.Group("/orgs/name/:name", func(orgsRoute RouteRegister) {
orgsRoute.Get("/", wrap(GetOrgByName))
}, reqGrafanaAdmin)
// auth api keys
apiRoute.Group("/auth/keys", func(keysRoute RouteRegister) {
keysRoute.Get("/", wrap(GetApiKeys))
keysRoute.Post("/", quota("api_key"), bind(m.AddApiKeyCommand{}), wrap(AddApiKey))
keysRoute.Delete("/:id", wrap(DeleteApiKey))
}, reqOrgAdmin)
// Preferences
apiRoute.Group("/preferences", func(prefRoute RouteRegister) {
prefRoute.Post("/set-home-dash", bind(m.SavePreferencesCommand{}), wrap(SetHomeDashboard))
})
// Data sources
apiRoute.Group("/datasources", func(datasourceRoute RouteRegister) {
datasourceRoute.Get("/", wrap(GetDataSources))
datasourceRoute.Post("/", quota("data_source"), bind(m.AddDataSourceCommand{}), wrap(AddDataSource))
datasourceRoute.Put("/:id", bind(m.UpdateDataSourceCommand{}), wrap(UpdateDataSource))
datasourceRoute.Delete("/:id", wrap(DeleteDataSourceById))
datasourceRoute.Delete("/name/:name", wrap(DeleteDataSourceByName))
datasourceRoute.Get("/:id", wrap(GetDataSourceById))
datasourceRoute.Get("/name/:name", wrap(GetDataSourceByName))
}, reqOrgAdmin)
apiRoute.Get("/datasources/id/:name", wrap(GetDataSourceIdByName), reqSignedIn)
apiRoute.Get("/plugins", wrap(GetPluginList))
apiRoute.Get("/plugins/:pluginId/settings", wrap(GetPluginSettingById))
apiRoute.Get("/plugins/:pluginId/markdown/:name", wrap(GetPluginMarkdown))
apiRoute.Group("/plugins", func(pluginRoute RouteRegister) {
pluginRoute.Get("/:pluginId/dashboards/", wrap(GetPluginDashboards))
pluginRoute.Post("/:pluginId/settings", bind(m.UpdatePluginSettingCmd{}), wrap(UpdatePluginSetting))
}, reqOrgAdmin)
apiRoute.Get("/frontend/settings/", GetFrontendSettings)
apiRoute.Any("/datasources/proxy/:id/*", reqSignedIn, hs.ProxyDataSourceRequest)
apiRoute.Any("/datasources/proxy/:id", reqSignedIn, hs.ProxyDataSourceRequest)
// Dashboard
apiRoute.Group("/dashboards", func(dashboardRoute RouteRegister) {
dashboardRoute.Get("/uid/:uid", wrap(GetDashboard))
dashboardRoute.Get("/db/:slug", wrap(GetDashboard))
dashboardRoute.Get("/db/:slug/uid", wrap(GetDashboardUidBySlug))
dashboardRoute.Delete("/db/:slug", reqEditorRole, wrap(DeleteDashboard))
dashboardRoute.Post("/calculate-diff", bind(dtos.CalculateDiffOptions{}), wrap(CalculateDashboardDiff))
dashboardRoute.Post("/db", reqEditorRole, bind(m.SaveDashboardCommand{}), wrap(PostDashboard))
dashboardRoute.Get("/home", wrap(GetHomeDashboard))
dashboardRoute.Get("/tags", GetDashboardTags)
dashboardRoute.Post("/import", bind(dtos.ImportDashboardCommand{}), wrap(ImportDashboard))
dashboardRoute.Group("/id/:dashboardId", func(dashIdRoute RouteRegister) {
dashIdRoute.Get("/versions", wrap(GetDashboardVersions))
dashIdRoute.Get("/versions/:id", wrap(GetDashboardVersion))
dashIdRoute.Post("/restore", reqEditorRole, bind(dtos.RestoreDashboardVersionCommand{}), wrap(RestoreDashboardVersion))
dashIdRoute.Group("/acl", func(aclRoute RouteRegister) {
aclRoute.Get("/", wrap(GetDashboardAclList))
aclRoute.Post("/", bind(dtos.UpdateDashboardAclCommand{}), wrap(UpdateDashboardAcl))
aclRoute.Delete("/:aclId", wrap(DeleteDashboardAcl))
})
})
})
// Dashboard snapshots
apiRoute.Group("/dashboard/snapshots", func(dashboardRoute RouteRegister) {
dashboardRoute.Get("/", wrap(SearchDashboardSnapshots))
})
// Playlist
apiRoute.Group("/playlists", func(playlistRoute RouteRegister) {
playlistRoute.Get("/", wrap(SearchPlaylists))
playlistRoute.Get("/:id", ValidateOrgPlaylist, wrap(GetPlaylist))
playlistRoute.Get("/:id/items", ValidateOrgPlaylist, wrap(GetPlaylistItems))
playlistRoute.Get("/:id/dashboards", ValidateOrgPlaylist, wrap(GetPlaylistDashboards))
playlistRoute.Delete("/:id", reqEditorRole, ValidateOrgPlaylist, wrap(DeletePlaylist))
playlistRoute.Put("/:id", reqEditorRole, bind(m.UpdatePlaylistCommand{}), ValidateOrgPlaylist, wrap(UpdatePlaylist))
playlistRoute.Post("/", reqEditorRole, bind(m.CreatePlaylistCommand{}), wrap(CreatePlaylist))
})
// Search
apiRoute.Get("/search/", Search)
// metrics
apiRoute.Post("/tsdb/query", bind(dtos.MetricRequest{}), wrap(QueryMetrics))
apiRoute.Get("/tsdb/testdata/scenarios", wrap(GetTestDataScenarios))
apiRoute.Get("/tsdb/testdata/gensql", reqGrafanaAdmin, wrap(GenerateSqlTestData))
apiRoute.Get("/tsdb/testdata/random-walk", wrap(GetTestDataRandomWalk))
apiRoute.Group("/alerts", func(alertsRoute RouteRegister) {
alertsRoute.Post("/test", bind(dtos.AlertTestCommand{}), wrap(AlertTest))
alertsRoute.Post("/:alertId/pause", reqEditorRole, bind(dtos.PauseAlertCommand{}), wrap(PauseAlert))
alertsRoute.Get("/:alertId", ValidateOrgAlert, wrap(GetAlert))
alertsRoute.Get("/", wrap(GetAlerts))
alertsRoute.Get("/states-for-dashboard", wrap(GetAlertStatesForDashboard))
})
apiRoute.Get("/alert-notifications", wrap(GetAlertNotifications))
apiRoute.Get("/alert-notifiers", wrap(GetAlertNotifiers))
apiRoute.Group("/alert-notifications", func(alertNotifications RouteRegister) {
alertNotifications.Post("/test", bind(dtos.NotificationTestCommand{}), wrap(NotificationTest))
alertNotifications.Post("/", bind(m.CreateAlertNotificationCommand{}), wrap(CreateAlertNotification))
alertNotifications.Put("/:notificationId", bind(m.UpdateAlertNotificationCommand{}), wrap(UpdateAlertNotification))
alertNotifications.Get("/:notificationId", wrap(GetAlertNotificationById))
alertNotifications.Delete("/:notificationId", wrap(DeleteAlertNotification))
}, reqEditorRole)
apiRoute.Get("/annotations", wrap(GetAnnotations))
apiRoute.Post("/annotations/mass-delete", reqOrgAdmin, bind(dtos.DeleteAnnotationsCmd{}), wrap(DeleteAnnotations))
apiRoute.Group("/annotations", func(annotationsRoute RouteRegister) {
annotationsRoute.Post("/", bind(dtos.PostAnnotationsCmd{}), wrap(PostAnnotation))
annotationsRoute.Delete("/:annotationId", wrap(DeleteAnnotationById))
annotationsRoute.Put("/:annotationId", bind(dtos.UpdateAnnotationsCmd{}), wrap(UpdateAnnotation))
annotationsRoute.Delete("/region/:regionId", wrap(DeleteAnnotationRegion))
annotationsRoute.Post("/graphite", bind(dtos.PostGraphiteAnnotationsCmd{}), wrap(PostGraphiteAnnotation))
}, reqEditorRole)
// error test
r.Get("/metrics/error", wrap(GenerateError))
}, reqSignedIn)
// admin api
r.Group("/api/admin", func(adminRoute RouteRegister) {
adminRoute.Get("/settings", AdminGetSettings)
adminRoute.Post("/users", bind(dtos.AdminCreateUserForm{}), AdminCreateUser)
adminRoute.Put("/users/:id/password", bind(dtos.AdminUpdateUserPasswordForm{}), AdminUpdateUserPassword)
adminRoute.Put("/users/:id/permissions", bind(dtos.AdminUpdateUserPermissionsForm{}), AdminUpdateUserPermissions)
adminRoute.Delete("/users/:id", AdminDeleteUser)
adminRoute.Get("/users/:id/quotas", wrap(GetUserQuotas))
adminRoute.Put("/users/:id/quotas/:target", bind(m.UpdateUserQuotaCmd{}), wrap(UpdateUserQuota))
adminRoute.Get("/stats", AdminGetStats)
adminRoute.Post("/pause-all-alerts", bind(dtos.PauseAllAlertsCommand{}), wrap(PauseAllAlerts))
}, reqGrafanaAdmin)
// rendering
r.Get("/render/*", reqSignedIn, RenderToPng)
// grafana.net proxy
r.Any("/api/gnet/*", reqSignedIn, ProxyGnetRequest)
// Gravatar service.
avatarCacheServer := avatar.NewCacheServer()
r.Get("/avatar/:hash", avatarCacheServer.Handler)
// Websocket
r.Any("/ws", hs.streamManager.Serve)
// streams
//r.Post("/api/streams/push", reqSignedIn, bind(dtos.StreamMessage{}), liveConn.PushToStream)
r.Register(macaronR)
InitAppPluginRoutes(macaronR)
macaronR.NotFound(NotFoundHandler)
}
| pkg/api/api.go | 1 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.006706511601805687,
0.0003442350425757468,
0.0001627461751922965,
0.00016674607468303293,
0.0010603828122839332
]
|
{
"id": 6,
"code_window": [
"\t\t\t\tConvey(\"Should be denied access\", func() {\n",
"\t\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallGetDashboardUidBySlug(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should be denied access\", func() {\n",
"\t\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 312
} | import angular from 'angular';
import _ from 'lodash';
import * as dateMath from 'app/core/utils/datemath';
import kbn from 'app/core/utils/kbn';
import * as templatingVariable from 'app/features/templating/variable';
// import * as moment from 'moment';
export default class CloudWatchDatasource {
type: any;
name: any;
supportMetrics: any;
proxyUrl: any;
defaultRegion: any;
instanceSettings: any;
standardStatistics: any;
/** @ngInject */
constructor(instanceSettings, private $q, private backendSrv, private templateSrv, private timeSrv) {
this.type = 'cloudwatch';
this.name = instanceSettings.name;
this.supportMetrics = true;
this.proxyUrl = instanceSettings.url;
this.defaultRegion = instanceSettings.jsonData.defaultRegion;
this.instanceSettings = instanceSettings;
this.standardStatistics = ['Average', 'Maximum', 'Minimum', 'Sum', 'SampleCount'];
}
query(options) {
options = angular.copy(options);
options.targets = this.expandTemplateVariable(options.targets, options.scopedVars, this.templateSrv);
var queries = _.filter(options.targets, item => {
return (
item.hide !== true && !!item.region && !!item.namespace && !!item.metricName && !_.isEmpty(item.statistics)
);
}).map(item => {
item.region = this.templateSrv.replace(this.getActualRegion(item.region), options.scopedVars);
item.namespace = this.templateSrv.replace(item.namespace, options.scopedVars);
item.metricName = this.templateSrv.replace(item.metricName, options.scopedVars);
item.dimensions = this.convertDimensionFormat(item.dimensions, options.scopedVars);
item.period = String(this.getPeriod(item, options)); // use string format for period in graph query, and alerting
return _.extend(
{
refId: item.refId,
intervalMs: options.intervalMs,
maxDataPoints: options.maxDataPoints,
datasourceId: this.instanceSettings.id,
type: 'timeSeriesQuery',
},
item
);
});
// No valid targets, return the empty result to save a round trip.
if (_.isEmpty(queries)) {
var d = this.$q.defer();
d.resolve({ data: [] });
return d.promise;
}
var request = {
from: options.range.from.valueOf().toString(),
to: options.range.to.valueOf().toString(),
queries: queries,
};
return this.performTimeSeriesQuery(request);
}
getPeriod(target, options, now?) {
var start = this.convertToCloudWatchTime(options.range.from, false);
var end = this.convertToCloudWatchTime(options.range.to, true);
now = Math.round((now || Date.now()) / 1000);
var period;
var range = end - start;
var hourSec = 60 * 60;
var daySec = hourSec * 24;
var periodUnit = 60;
if (!target.period) {
if (now - start <= daySec * 15) {
// until 15 days ago
if (target.namespace === 'AWS/EC2') {
periodUnit = period = 300;
} else {
periodUnit = period = 60;
}
} else if (now - start <= daySec * 63) {
// until 63 days ago
periodUnit = period = 60 * 5;
} else if (now - start <= daySec * 455) {
// until 455 days ago
periodUnit = period = 60 * 60;
} else {
// over 455 days, should return error, but try to long period
periodUnit = period = 60 * 60;
}
} else {
if (/^\d+$/.test(target.period)) {
period = parseInt(target.period, 10);
} else {
period = kbn.interval_to_seconds(this.templateSrv.replace(target.period, options.scopedVars));
}
}
if (period < 1) {
period = 1;
}
if (range / period >= 1440) {
period = Math.ceil(range / 1440 / periodUnit) * periodUnit;
}
return period;
}
performTimeSeriesQuery(request) {
return this.awsRequest('/api/tsdb/query', request).then(res => {
var data = [];
if (res.results) {
_.forEach(res.results, queryRes => {
_.forEach(queryRes.series, series => {
data.push({ target: series.name, datapoints: series.points });
});
});
}
return { data: data };
});
}
transformSuggestDataFromTable(suggestData) {
return _.map(suggestData.results['metricFindQuery'].tables[0].rows, v => {
return {
text: v[0],
value: v[1],
};
});
}
doMetricQueryRequest(subtype, parameters) {
var range = this.timeSrv.timeRange();
return this.awsRequest('/api/tsdb/query', {
from: range.from.valueOf().toString(),
to: range.to.valueOf().toString(),
queries: [
_.extend(
{
refId: 'metricFindQuery',
intervalMs: 1, // dummy
maxDataPoints: 1, // dummy
datasourceId: this.instanceSettings.id,
type: 'metricFindQuery',
subtype: subtype,
},
parameters
),
],
}).then(r => {
return this.transformSuggestDataFromTable(r);
});
}
getRegions() {
return this.doMetricQueryRequest('regions', null);
}
getNamespaces() {
return this.doMetricQueryRequest('namespaces', null);
}
getMetrics(namespace, region) {
return this.doMetricQueryRequest('metrics', {
region: this.templateSrv.replace(this.getActualRegion(region)),
namespace: this.templateSrv.replace(namespace),
});
}
getDimensionKeys(namespace, region) {
return this.doMetricQueryRequest('dimension_keys', {
region: this.templateSrv.replace(this.getActualRegion(region)),
namespace: this.templateSrv.replace(namespace),
});
}
getDimensionValues(region, namespace, metricName, dimensionKey, filterDimensions) {
return this.doMetricQueryRequest('dimension_values', {
region: this.templateSrv.replace(this.getActualRegion(region)),
namespace: this.templateSrv.replace(namespace),
metricName: this.templateSrv.replace(metricName),
dimensionKey: this.templateSrv.replace(dimensionKey),
dimensions: this.convertDimensionFormat(filterDimensions, {}),
});
}
getEbsVolumeIds(region, instanceId) {
return this.doMetricQueryRequest('ebs_volume_ids', {
region: this.templateSrv.replace(this.getActualRegion(region)),
instanceId: this.templateSrv.replace(instanceId),
});
}
getEc2InstanceAttribute(region, attributeName, filters) {
return this.doMetricQueryRequest('ec2_instance_attribute', {
region: this.templateSrv.replace(this.getActualRegion(region)),
attributeName: this.templateSrv.replace(attributeName),
filters: filters,
});
}
metricFindQuery(query) {
var region;
var namespace;
var metricName;
var regionQuery = query.match(/^regions\(\)/);
if (regionQuery) {
return this.getRegions();
}
var namespaceQuery = query.match(/^namespaces\(\)/);
if (namespaceQuery) {
return this.getNamespaces();
}
var metricNameQuery = query.match(/^metrics\(([^\)]+?)(,\s?([^,]+?))?\)/);
if (metricNameQuery) {
namespace = metricNameQuery[1];
region = metricNameQuery[3];
return this.getMetrics(namespace, region);
}
var dimensionKeysQuery = query.match(/^dimension_keys\(([^\)]+?)(,\s?([^,]+?))?\)/);
if (dimensionKeysQuery) {
namespace = dimensionKeysQuery[1];
region = dimensionKeysQuery[3];
return this.getDimensionKeys(namespace, region);
}
var dimensionValuesQuery = query.match(/^dimension_values\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?)\)/);
if (dimensionValuesQuery) {
region = dimensionValuesQuery[1];
namespace = dimensionValuesQuery[2];
metricName = dimensionValuesQuery[3];
var dimensionKey = dimensionValuesQuery[4];
return this.getDimensionValues(region, namespace, metricName, dimensionKey, {});
}
var ebsVolumeIdsQuery = query.match(/^ebs_volume_ids\(([^,]+?),\s?([^,]+?)\)/);
if (ebsVolumeIdsQuery) {
region = ebsVolumeIdsQuery[1];
var instanceId = ebsVolumeIdsQuery[2];
return this.getEbsVolumeIds(region, instanceId);
}
var ec2InstanceAttributeQuery = query.match(/^ec2_instance_attribute\(([^,]+?),\s?([^,]+?),\s?(.+?)\)/);
if (ec2InstanceAttributeQuery) {
region = ec2InstanceAttributeQuery[1];
var targetAttributeName = ec2InstanceAttributeQuery[2];
var filterJson = JSON.parse(this.templateSrv.replace(ec2InstanceAttributeQuery[3]));
return this.getEc2InstanceAttribute(region, targetAttributeName, filterJson);
}
return this.$q.when([]);
}
annotationQuery(options) {
var annotation = options.annotation;
var statistics = _.map(annotation.statistics, s => {
return this.templateSrv.replace(s);
});
var defaultPeriod = annotation.prefixMatching ? '' : '300';
var period = annotation.period || defaultPeriod;
period = parseInt(period, 10);
var parameters = {
prefixMatching: annotation.prefixMatching,
region: this.templateSrv.replace(this.getActualRegion(annotation.region)),
namespace: this.templateSrv.replace(annotation.namespace),
metricName: this.templateSrv.replace(annotation.metricName),
dimensions: this.convertDimensionFormat(annotation.dimensions, {}),
statistics: statistics,
period: period,
actionPrefix: annotation.actionPrefix || '',
alarmNamePrefix: annotation.alarmNamePrefix || '',
};
return this.awsRequest('/api/tsdb/query', {
from: options.range.from.valueOf().toString(),
to: options.range.to.valueOf().toString(),
queries: [
_.extend(
{
refId: 'annotationQuery',
intervalMs: 1, // dummy
maxDataPoints: 1, // dummy
datasourceId: this.instanceSettings.id,
type: 'annotationQuery',
},
parameters
),
],
}).then(r => {
return _.map(r.results['annotationQuery'].tables[0].rows, v => {
return {
annotation: annotation,
time: Date.parse(v[0]),
title: v[1],
tags: [v[2]],
text: v[3],
};
});
});
}
targetContainsTemplate(target) {
return (
this.templateSrv.variableExists(target.region) ||
this.templateSrv.variableExists(target.namespace) ||
this.templateSrv.variableExists(target.metricName) ||
_.find(target.dimensions, (v, k) => {
return this.templateSrv.variableExists(k) || this.templateSrv.variableExists(v);
})
);
}
testDatasource() {
/* use billing metrics for test */
var region = this.defaultRegion;
var namespace = 'AWS/Billing';
var metricName = 'EstimatedCharges';
var dimensions = {};
return this.getDimensionValues(region, namespace, metricName, 'ServiceName', dimensions).then(
() => {
return { status: 'success', message: 'Data source is working' };
},
err => {
return { status: 'error', message: err.message };
}
);
}
awsRequest(url, data) {
var options = {
method: 'POST',
url: url,
data: data,
};
return this.backendSrv.datasourceRequest(options).then(result => {
return result.data;
});
}
getDefaultRegion() {
return this.defaultRegion;
}
getActualRegion(region) {
if (region === 'default' || _.isEmpty(region)) {
return this.getDefaultRegion();
}
return region;
}
getExpandedVariables(target, dimensionKey, variable, templateSrv) {
/* if the all checkbox is marked we should add all values to the targets */
var allSelected = _.find(variable.options, { selected: true, text: 'All' });
return _.chain(variable.options)
.filter(v => {
if (allSelected) {
return v.text !== 'All';
} else {
return v.selected;
}
})
.map(v => {
var t = angular.copy(target);
var scopedVar = {};
scopedVar[variable.name] = v;
t.refId = target.refId + '_' + v.value;
t.dimensions[dimensionKey] = templateSrv.replace(t.dimensions[dimensionKey], scopedVar);
return t;
})
.value();
}
expandTemplateVariable(targets, scopedVars, templateSrv) {
return _.chain(targets)
.map(target => {
var dimensionKey = _.findKey(target.dimensions, v => {
return templateSrv.variableExists(v) && !_.has(scopedVars, templateSrv.getVariableName(v));
});
if (dimensionKey) {
var multiVariable = _.find(templateSrv.variables, variable => {
return (
templatingVariable.containsVariable(target.dimensions[dimensionKey], variable.name) && variable.multi
);
});
var variable = _.find(templateSrv.variables, variable => {
return templatingVariable.containsVariable(target.dimensions[dimensionKey], variable.name);
});
return this.getExpandedVariables(target, dimensionKey, multiVariable || variable, templateSrv);
} else {
return [target];
}
})
.flatten()
.value();
}
convertToCloudWatchTime(date, roundUp) {
if (_.isString(date)) {
date = dateMath.parse(date, roundUp);
}
return Math.round(date.valueOf() / 1000);
}
convertDimensionFormat(dimensions, scopedVars) {
var convertedDimensions = {};
_.each(dimensions, (value, key) => {
convertedDimensions[this.templateSrv.replace(key, scopedVars)] = this.templateSrv.replace(value, scopedVars);
});
return convertedDimensions;
}
}
| public/app/plugins/datasource/cloudwatch/datasource.ts | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.0001741372252581641,
0.0001706103066680953,
0.0001654817897360772,
0.00017090518667828292,
0.0000022131232526589883
]
|
{
"id": 6,
"code_window": [
"\t\t\t\tConvey(\"Should be denied access\", func() {\n",
"\t\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallGetDashboardUidBySlug(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should be denied access\", func() {\n",
"\t\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 312
} | <?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 20.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="18px" height="18px" viewBox="0 0 18 18" style="enable-background:new 0 0 18 18;" xml:space="preserve">
<style type="text/css">
.st0{fill:#35373F;}
</style>
<g>
<g>
<path class="st0" d="M6.9,8.7H1.7C0.8,8.7,0,7.9,0,7V1.8c0-0.9,0.8-1.7,1.7-1.7h5.2c0.9,0,1.7,0.8,1.7,1.7V7
C8.6,7.9,7.8,8.7,6.9,8.7z"/>
</g>
<g>
<path class="st0" d="M16.3,8.7h-5.2c-0.9,0-1.7-0.8-1.7-1.7V1.8c0-0.9,0.8-1.7,1.7-1.7h5.2c0.9,0,1.7,0.8,1.7,1.7V7
C18,7.9,17.2,8.7,16.3,8.7z"/>
</g>
<g>
<path class="st0" d="M6.9,17.9H1.7c-0.9,0-1.7-0.8-1.7-1.7V11c0-0.9,0.8-1.7,1.7-1.7h5.2c0.9,0,1.7,0.8,1.7,1.7v5.2
C8.6,17.1,7.8,17.9,6.9,17.9z"/>
</g>
<g>
<path class="st0" d="M16.3,17.9h-5.2c-0.9,0-1.7-0.8-1.7-1.7V11c0-0.9,0.8-1.7,1.7-1.7h5.2c0.9,0,1.7,0.8,1.7,1.7v5.2
C18,17.1,17.2,17.9,16.3,17.9z"/>
</g>
</g>
</svg>
| public/img/icons_light_theme/icon_dashboard_list.svg | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.0001710858487058431,
0.00016935616440605372,
0.00016598209913354367,
0.00017100055993068963,
0.000002386081860095146
]
|
{
"id": 6,
"code_window": [
"\t\t\t\tConvey(\"Should be denied access\", func() {\n",
"\t\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallGetDashboardUidBySlug(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should be denied access\", func() {\n",
"\t\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 312
} | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />
<style>body {
width: 100% !important; min-width: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; margin: 0; padding: 0;
}
img {
outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; width: auto; float: left; clear: both; display: block;
}
body {
color: #222222; font-family: "Helvetica", "Arial", sans-serif; font-weight: normal; padding: 0; margin: 0; text-align: left; line-height: 1.3;
}
body {
font-size: 14px; line-height: 19px;
}
a:hover {
color: #2795b6 !important;
}
a:active {
color: #2795b6 !important;
}
a:visited {
color: #2ba6cb !important;
}
body {
font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none;
}
a:hover {
color: #ff8f2b !important;
}
a:active {
color: #F2821E !important;
}
a:visited {
color: #E67612 !important;
}
.better-button:hover a {
color: #FFFFFF !important; background-color: #F2821E; border: 1px solid #F2821E;
}
.better-button:visited a {
color: #FFFFFF !important;
}
.better-button:active a {
color: #FFFFFF !important;
}
.better-button-alt:hover a {
color: #ff8f2b !important; background-color: #DDDDDD; border: 1px solid #F2821E;
}
.better-button-alt:visited a {
color: #ff8f2b !important;
}
.better-button-alt:active a {
color: #ff8f2b !important;
}
body {
height: 100% !important; width: 100% !important;
}
body .copy {
-ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;
}
.ExternalClass {
width: 100%;
}
.ExternalClass {
line-height: 100%;
}
img {
-ms-interpolation-mode: bicubic;
}
img {
border: 0 !important; outline: none !important; text-decoration: none !important;
}
a:hover {
text-decoration: underline;
}
@media only screen and (max-width: 600px) {
table[class="body"] center {
min-width: 0 !important;
}
table[class="body"] .container {
width: 95% !important;
}
table[class="body"] .row {
width: 100% !important; display: block !important;
}
table[class="body"] .wrapper {
display: block !important; padding-right: 0 !important;
}
table[class="body"] .columns {
table-layout: fixed !important; float: none !important; width: 100% !important; padding-right: 0px !important; padding-left: 0px !important; display: block !important;
}
table[class="body"] table.columns td {
width: 100% !important;
}
table[class="body"] .columns td.six {
width: 50% !important;
}
table[class="body"] .columns td.twelve {
width: 100% !important;
}
table[class="body"] table.columns td.expander {
width: 1px !important;
}
.logo {
margin-left: 10px;
}
}
@media (max-width: 600px) {
table[class="email-container"] {
width: 95% !important;
}
img[class="fluid"] {
width: 100% !important; max-width: 100% !important; height: auto !important; margin: auto !important;
}
img[class="fluid-centered"] {
width: 100% !important; max-width: 100% !important; height: auto !important; margin: auto !important;
}
img[class="fluid-centered"] {
margin: auto !important;
}
td[class="comms-content"] {
padding: 20px !important;
}
td[class="stack-column"] {
display: block !important; width: 100% !important; direction: ltr !important;
}
td[class="stack-column-center"] {
display: block !important; width: 100% !important; direction: ltr !important;
}
td[class="stack-column-center"] {
text-align: center !important;
}
td[class="copy"] {
font-size: 14px !important; line-height: 24px !important; padding: 0 30px !important;
}
td[class="copy -center"] {
font-size: 14px !important; line-height: 24px !important; padding: 0 30px !important;
}
td[class="copy -bold"] {
font-size: 14px !important; line-height: 24px !important; padding: 0 30px !important;
}
td[class="small-text"] {
font-size: 14px !important; line-height: 24px !important; padding: 0 30px !important;
}
td[class="mini-centered-text"] {
font-size: 14px !important; line-height: 24px !important; padding: 15px 30px !important;
}
td[class="copy -padd"] {
padding: 0 40px !important;
}
span[class="sep"] {
display: none !important;
}
td[class="mb-hide"] {
display: none !important; height: 0 !important;
}
td[class="spacer mb-shorten"] {
height: 25px !important;
}
.two-up td {
width: 270px;
}
}
</style></head>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" class="main" style="height: 100% !important; width: 100% !important; min-width: 100%; -webkit-text-size-adjust: none; -ms-text-size-adjust: 100%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; text-align: left; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; margin: 0 auto; padding: 0;" bgcolor="#2e2e2e">
<table class="body" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; height: 100%; width: 100%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" bgcolor="#2e2e2e">
<tr style="vertical-align: top; padding: 0;" align="left">
<td class="center" align="center" valign="top" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;">
<center style="width: 100%; min-width: 580px;">
<table class="row header" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; margin-top: 25px; margin-bottom: 25px; padding: 0px;">
<tr style="vertical-align: top; padding: 0;" align="left">
<td class="center" align="center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" valign="top">
<center style="width: 100%; min-width: 580px;">
<table class="container" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: inherit; width: 580px; margin: 0 auto; padding: 0;">
<tr style="vertical-align: top; padding: 0;" align="left">
<td class="wrapper last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; position: relative; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 10px 0px 0px;" align="left" valign="top">
<table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;">
<tr style="vertical-align: top; padding: 0;" align="left">
<td class="twelve sub-columns center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; min-width: 0px; width: 100%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 10px 10px 0px;" align="center" valign="top">
<img class="logo" src="http://grafana.org/assets/img/logo_new_transparent_200x48.png" style="width: 200px; display: inline; outline: none !important; text-decoration: none !important; -ms-interpolation-mode: bicubic; clear: both; border: 0;" align="none" />
</td>
<td class="expander" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; visibility: hidden; width: 0px; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="left" valign="top"></td>
</tr>
</table>
</td>
</tr>
</table>
</center>
</td>
</tr>
</table>
<table class="container" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: inherit; width: 580px; margin: 0 auto; padding: 0;" width="600" bgcolor="#efefef">
<tr style="vertical-align: top; padding: 0;" align="left">
<td height="2" class="spacer mb-shorten" style="font-size: 0; line-height: 0; mso-table-lspace: 0pt; mso-table-rspace: 0pt; background-image: linear-gradient(to right, #ffed00 0%, #f26529 75%); height: 2px !important; word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0; border: 0;" valign="top" align="left"> </td>
</tr>
<tr style="vertical-align: top; padding: 0;" align="left">
<td class="mini-centered-text" style="color: #343b41; mso-table-lspace: 0pt; mso-table-rspace: 0pt; word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 25px 35px; font: 400 16px/27px 'Helvetica Neue', Helvetica, Arial, sans-serif;" align="center" valign="top">
{{Subject .Subject "{{.InvitedBy}} has added you to the {{.OrgName}} organization"}}
<table class="row" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; display: block; padding: 0px;">
<tr style="vertical-align: top; padding: 0;" align="left">
<td class="wrapper last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; position: relative; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 10px 0px 0px;" align="left" valign="top">
<table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;">
<tr style="vertical-align: top; padding: 0;" align="left">
<td style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="left" valign="top">
<h4 class="center" style="color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 1.3; word-break: normal; font-size: 20px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="center">You have been added to {{.OrgName}}</h4>
</td>
<td class="expander" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; visibility: hidden; width: 0px; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="left" valign="top"></td>
</tr>
</table>
</td>
</tr>
</table>
<table class="row" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; display: block; padding: 0px;">
<tr style="vertical-align: top; padding: 0;" align="left">
<td class="wrapper last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; position: relative; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 10px 0px 0px;" align="left" valign="top">
<table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;">
<tr style="vertical-align: top; padding: 0;" align="left">
<td class="center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="center" valign="top">
<p style="color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0 0 10px; padding: 0;" align="left"><b>{{.InvitedBy}}</b> has added you to the <b>{{.OrgName}}</b> organization in Grafana.
</p><p style="color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0 0 10px; padding: 0;" align="left">Once logged in, {{.OrgName}} will be available in the left side menu, in the dropdown below your username.</p>
</td>
<td class="expander" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; visibility: hidden; width: 0px; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="left" valign="top"></td>
</tr>
<tr style="vertical-align: top; padding: 0;" align="left">
<td class="center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="center" valign="top">
<table class="better-button" align="center" border="0" cellspacing="0" cellpadding="0" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; margin-top: 10px; margin-bottom: 20px; padding: 0;">
<tr style="vertical-align: top; padding: 0;" align="left">
<td align="center" class="better-button" bgcolor="#ff8f2b" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; margin: 0; padding: 0px;" valign="top"><a href="{{.AppUrl}}" target="_blank" style="color: #FFF; text-decoration: none; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; display: inline-block; padding: 12px 25px; border: 1px solid #ff8f2b;">Log in now</a></td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
<table class="footer center" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: center; color: #999999; margin-top: 20px; padding: 0;" bgcolor="#2e2e2e">
<tr style="vertical-align: top; padding: 0;" align="left">
<td class="wrapper last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; position: relative; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 10px 20px 0px 0px;" align="left" valign="top">
<table class="twelve columns center" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: center; width: 580px; margin: 0 auto; padding: 0;">
<tr style="vertical-align: top; padding: 0;" align="left">
<td class="twelve" align="center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; width: 100%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" valign="top">
<center style="width: 100%; min-width: 580px;">
<p style="font-size: 12px; color: #999999; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0 0 10px; padding: 0;" align="center">
Sent by <a href="{{.AppUrl}}" style="color: #E67612; text-decoration: none;">Grafana v{{.BuildVersion}}</a>
<br />© 2016 Grafana and raintank
</p>
</center>
</td>
<td class="expander" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; visibility: hidden; width: 0px; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="left" valign="top"></td>
</tr>
</table>
</td>
</tr>
</table>
</center>
</td>
</tr>
</table>
</body>
</html>
| public/emails/invited_to_org.html | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017720040341373533,
0.00017087289597839117,
0.00016686123854015023,
0.0001700410939520225,
0.0000024547130124119576
]
|
{
"id": 7,
"code_window": [
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallGetDashboardUidBySlug(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should be denied access\", func() {\n",
"\t\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n",
"\t\t\t\tConvey(\"Should lookup dashboard by slug\", func() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 374
} | package api
import (
"github.com/go-macaron/binding"
"github.com/grafana/grafana/pkg/api/avatar"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
)
// Register adds http routes
func (hs *HttpServer) registerRoutes() {
macaronR := hs.macaron
reqSignedIn := middleware.Auth(&middleware.AuthOptions{ReqSignedIn: true})
reqGrafanaAdmin := middleware.Auth(&middleware.AuthOptions{ReqSignedIn: true, ReqGrafanaAdmin: true})
reqEditorRole := middleware.RoleAuth(m.ROLE_EDITOR, m.ROLE_ADMIN)
reqOrgAdmin := middleware.RoleAuth(m.ROLE_ADMIN)
quota := middleware.Quota
bind := binding.Bind
// automatically set HEAD for every GET
macaronR.SetAutoHead(true)
r := newRouteRegister(middleware.RequestMetrics, middleware.RequestTracing)
// not logged in views
r.Get("/", reqSignedIn, Index)
r.Get("/logout", Logout)
r.Post("/login", quota("session"), bind(dtos.LoginCommand{}), wrap(LoginPost))
r.Get("/login/:name", quota("session"), OAuthLogin)
r.Get("/login", LoginView)
r.Get("/invite/:code", Index)
// authed views
r.Get("/profile/", reqSignedIn, Index)
r.Get("/profile/password", reqSignedIn, Index)
r.Get("/profile/switch-org/:id", reqSignedIn, ChangeActiveOrgAndRedirectToHome)
r.Get("/org/", reqSignedIn, Index)
r.Get("/org/new", reqSignedIn, Index)
r.Get("/datasources/", reqSignedIn, Index)
r.Get("/datasources/new", reqSignedIn, Index)
r.Get("/datasources/edit/*", reqSignedIn, Index)
r.Get("/org/users", reqSignedIn, Index)
r.Get("/org/users/new", reqSignedIn, Index)
r.Get("/org/users/invite", reqSignedIn, Index)
r.Get("/org/teams", reqSignedIn, Index)
r.Get("/org/teams/*", reqSignedIn, Index)
r.Get("/org/apikeys/", reqSignedIn, Index)
r.Get("/dashboard/import/", reqSignedIn, Index)
r.Get("/configuration", reqGrafanaAdmin, Index)
r.Get("/admin", reqGrafanaAdmin, Index)
r.Get("/admin/settings", reqGrafanaAdmin, Index)
r.Get("/admin/users", reqGrafanaAdmin, Index)
r.Get("/admin/users/create", reqGrafanaAdmin, Index)
r.Get("/admin/users/edit/:id", reqGrafanaAdmin, Index)
r.Get("/admin/orgs", reqGrafanaAdmin, Index)
r.Get("/admin/orgs/edit/:id", reqGrafanaAdmin, Index)
r.Get("/admin/stats", reqGrafanaAdmin, Index)
r.Get("/styleguide", reqSignedIn, Index)
r.Get("/plugins", reqSignedIn, Index)
r.Get("/plugins/:id/edit", reqSignedIn, Index)
r.Get("/plugins/:id/page/:page", reqSignedIn, Index)
r.Get("/dashboard/*", reqSignedIn, Index)
r.Get("/dashboard-solo/snapshot/*", Index)
r.Get("/dashboard-solo/*", reqSignedIn, Index)
r.Get("/import/dashboard", reqSignedIn, Index)
r.Get("/dashboards/", reqSignedIn, Index)
r.Get("/dashboards/*", reqSignedIn, Index)
r.Get("/playlists/", reqSignedIn, Index)
r.Get("/playlists/*", reqSignedIn, Index)
r.Get("/alerting/", reqSignedIn, Index)
r.Get("/alerting/*", reqSignedIn, Index)
// sign up
r.Get("/signup", Index)
r.Get("/api/user/signup/options", wrap(GetSignUpOptions))
r.Post("/api/user/signup", quota("user"), bind(dtos.SignUpForm{}), wrap(SignUp))
r.Post("/api/user/signup/step2", bind(dtos.SignUpStep2Form{}), wrap(SignUpStep2))
// invited
r.Get("/api/user/invite/:code", wrap(GetInviteInfoByCode))
r.Post("/api/user/invite/complete", bind(dtos.CompleteInviteForm{}), wrap(CompleteInvite))
// reset password
r.Get("/user/password/send-reset-email", Index)
r.Get("/user/password/reset", Index)
r.Post("/api/user/password/send-reset-email", bind(dtos.SendResetPasswordEmailForm{}), wrap(SendResetPasswordEmail))
r.Post("/api/user/password/reset", bind(dtos.ResetUserPasswordForm{}), wrap(ResetPassword))
// dashboard snapshots
r.Get("/dashboard/snapshot/*", Index)
r.Get("/dashboard/snapshots/", reqSignedIn, Index)
// api for dashboard snapshots
r.Post("/api/snapshots/", bind(m.CreateDashboardSnapshotCommand{}), CreateDashboardSnapshot)
r.Get("/api/snapshot/shared-options/", GetSharingOptions)
r.Get("/api/snapshots/:key", GetDashboardSnapshot)
r.Get("/api/snapshots-delete/:key", reqEditorRole, DeleteDashboardSnapshot)
// api renew session based on remember cookie
r.Get("/api/login/ping", quota("session"), LoginApiPing)
// authed api
r.Group("/api", func(apiRoute RouteRegister) {
// user (signed in)
apiRoute.Group("/user", func(userRoute RouteRegister) {
userRoute.Get("/", wrap(GetSignedInUser))
userRoute.Put("/", bind(m.UpdateUserCommand{}), wrap(UpdateSignedInUser))
userRoute.Post("/using/:id", wrap(UserSetUsingOrg))
userRoute.Get("/orgs", wrap(GetSignedInUserOrgList))
userRoute.Post("/stars/dashboard/:id", wrap(StarDashboard))
userRoute.Delete("/stars/dashboard/:id", wrap(UnstarDashboard))
userRoute.Put("/password", bind(m.ChangeUserPasswordCommand{}), wrap(ChangeUserPassword))
userRoute.Get("/quotas", wrap(GetUserQuotas))
userRoute.Put("/helpflags/:id", wrap(SetHelpFlag))
// For dev purpose
userRoute.Get("/helpflags/clear", wrap(ClearHelpFlags))
userRoute.Get("/preferences", wrap(GetUserPreferences))
userRoute.Put("/preferences", bind(dtos.UpdatePrefsCmd{}), wrap(UpdateUserPreferences))
})
// users (admin permission required)
apiRoute.Group("/users", func(usersRoute RouteRegister) {
usersRoute.Get("/", wrap(SearchUsers))
usersRoute.Get("/search", wrap(SearchUsersWithPaging))
usersRoute.Get("/:id", wrap(GetUserById))
usersRoute.Get("/:id/orgs", wrap(GetUserOrgList))
// query parameters /users/[email protected]
usersRoute.Get("/lookup", wrap(GetUserByLoginOrEmail))
usersRoute.Put("/:id", bind(m.UpdateUserCommand{}), wrap(UpdateUser))
usersRoute.Post("/:id/using/:orgId", wrap(UpdateUserActiveOrg))
}, reqGrafanaAdmin)
// team (admin permission required)
apiRoute.Group("/teams", func(teamsRoute RouteRegister) {
teamsRoute.Get("/:teamId", wrap(GetTeamById))
teamsRoute.Get("/search", wrap(SearchTeams))
teamsRoute.Post("/", quota("teams"), bind(m.CreateTeamCommand{}), wrap(CreateTeam))
teamsRoute.Put("/:teamId", bind(m.UpdateTeamCommand{}), wrap(UpdateTeam))
teamsRoute.Delete("/:teamId", wrap(DeleteTeamById))
teamsRoute.Get("/:teamId/members", wrap(GetTeamMembers))
teamsRoute.Post("/:teamId/members", quota("teams"), bind(m.AddTeamMemberCommand{}), wrap(AddTeamMember))
teamsRoute.Delete("/:teamId/members/:userId", wrap(RemoveTeamMember))
}, reqOrgAdmin)
// org information available to all users.
apiRoute.Group("/org", func(orgRoute RouteRegister) {
orgRoute.Get("/", wrap(GetOrgCurrent))
orgRoute.Get("/quotas", wrap(GetOrgQuotas))
})
// current org
apiRoute.Group("/org", func(orgRoute RouteRegister) {
orgRoute.Put("/", bind(dtos.UpdateOrgForm{}), wrap(UpdateOrgCurrent))
orgRoute.Put("/address", bind(dtos.UpdateOrgAddressForm{}), wrap(UpdateOrgAddressCurrent))
orgRoute.Post("/users", quota("user"), bind(m.AddOrgUserCommand{}), wrap(AddOrgUserToCurrentOrg))
orgRoute.Get("/users", wrap(GetOrgUsersForCurrentOrg))
orgRoute.Patch("/users/:userId", bind(m.UpdateOrgUserCommand{}), wrap(UpdateOrgUserForCurrentOrg))
orgRoute.Delete("/users/:userId", wrap(RemoveOrgUserForCurrentOrg))
// invites
orgRoute.Get("/invites", wrap(GetPendingOrgInvites))
orgRoute.Post("/invites", quota("user"), bind(dtos.AddInviteForm{}), wrap(AddOrgInvite))
orgRoute.Patch("/invites/:code/revoke", wrap(RevokeInvite))
// prefs
orgRoute.Get("/preferences", wrap(GetOrgPreferences))
orgRoute.Put("/preferences", bind(dtos.UpdatePrefsCmd{}), wrap(UpdateOrgPreferences))
}, reqOrgAdmin)
// create new org
apiRoute.Post("/orgs", quota("org"), bind(m.CreateOrgCommand{}), wrap(CreateOrg))
// search all orgs
apiRoute.Get("/orgs", reqGrafanaAdmin, wrap(SearchOrgs))
// orgs (admin routes)
apiRoute.Group("/orgs/:orgId", func(orgsRoute RouteRegister) {
orgsRoute.Get("/", wrap(GetOrgById))
orgsRoute.Put("/", bind(dtos.UpdateOrgForm{}), wrap(UpdateOrg))
orgsRoute.Put("/address", bind(dtos.UpdateOrgAddressForm{}), wrap(UpdateOrgAddress))
orgsRoute.Delete("/", wrap(DeleteOrgById))
orgsRoute.Get("/users", wrap(GetOrgUsers))
orgsRoute.Post("/users", bind(m.AddOrgUserCommand{}), wrap(AddOrgUser))
orgsRoute.Patch("/users/:userId", bind(m.UpdateOrgUserCommand{}), wrap(UpdateOrgUser))
orgsRoute.Delete("/users/:userId", wrap(RemoveOrgUser))
orgsRoute.Get("/quotas", wrap(GetOrgQuotas))
orgsRoute.Put("/quotas/:target", bind(m.UpdateOrgQuotaCmd{}), wrap(UpdateOrgQuota))
}, reqGrafanaAdmin)
// orgs (admin routes)
apiRoute.Group("/orgs/name/:name", func(orgsRoute RouteRegister) {
orgsRoute.Get("/", wrap(GetOrgByName))
}, reqGrafanaAdmin)
// auth api keys
apiRoute.Group("/auth/keys", func(keysRoute RouteRegister) {
keysRoute.Get("/", wrap(GetApiKeys))
keysRoute.Post("/", quota("api_key"), bind(m.AddApiKeyCommand{}), wrap(AddApiKey))
keysRoute.Delete("/:id", wrap(DeleteApiKey))
}, reqOrgAdmin)
// Preferences
apiRoute.Group("/preferences", func(prefRoute RouteRegister) {
prefRoute.Post("/set-home-dash", bind(m.SavePreferencesCommand{}), wrap(SetHomeDashboard))
})
// Data sources
apiRoute.Group("/datasources", func(datasourceRoute RouteRegister) {
datasourceRoute.Get("/", wrap(GetDataSources))
datasourceRoute.Post("/", quota("data_source"), bind(m.AddDataSourceCommand{}), wrap(AddDataSource))
datasourceRoute.Put("/:id", bind(m.UpdateDataSourceCommand{}), wrap(UpdateDataSource))
datasourceRoute.Delete("/:id", wrap(DeleteDataSourceById))
datasourceRoute.Delete("/name/:name", wrap(DeleteDataSourceByName))
datasourceRoute.Get("/:id", wrap(GetDataSourceById))
datasourceRoute.Get("/name/:name", wrap(GetDataSourceByName))
}, reqOrgAdmin)
apiRoute.Get("/datasources/id/:name", wrap(GetDataSourceIdByName), reqSignedIn)
apiRoute.Get("/plugins", wrap(GetPluginList))
apiRoute.Get("/plugins/:pluginId/settings", wrap(GetPluginSettingById))
apiRoute.Get("/plugins/:pluginId/markdown/:name", wrap(GetPluginMarkdown))
apiRoute.Group("/plugins", func(pluginRoute RouteRegister) {
pluginRoute.Get("/:pluginId/dashboards/", wrap(GetPluginDashboards))
pluginRoute.Post("/:pluginId/settings", bind(m.UpdatePluginSettingCmd{}), wrap(UpdatePluginSetting))
}, reqOrgAdmin)
apiRoute.Get("/frontend/settings/", GetFrontendSettings)
apiRoute.Any("/datasources/proxy/:id/*", reqSignedIn, hs.ProxyDataSourceRequest)
apiRoute.Any("/datasources/proxy/:id", reqSignedIn, hs.ProxyDataSourceRequest)
// Dashboard
apiRoute.Group("/dashboards", func(dashboardRoute RouteRegister) {
dashboardRoute.Get("/uid/:uid", wrap(GetDashboard))
dashboardRoute.Get("/db/:slug", wrap(GetDashboard))
dashboardRoute.Get("/db/:slug/uid", wrap(GetDashboardUidBySlug))
dashboardRoute.Delete("/db/:slug", reqEditorRole, wrap(DeleteDashboard))
dashboardRoute.Post("/calculate-diff", bind(dtos.CalculateDiffOptions{}), wrap(CalculateDashboardDiff))
dashboardRoute.Post("/db", reqEditorRole, bind(m.SaveDashboardCommand{}), wrap(PostDashboard))
dashboardRoute.Get("/home", wrap(GetHomeDashboard))
dashboardRoute.Get("/tags", GetDashboardTags)
dashboardRoute.Post("/import", bind(dtos.ImportDashboardCommand{}), wrap(ImportDashboard))
dashboardRoute.Group("/id/:dashboardId", func(dashIdRoute RouteRegister) {
dashIdRoute.Get("/versions", wrap(GetDashboardVersions))
dashIdRoute.Get("/versions/:id", wrap(GetDashboardVersion))
dashIdRoute.Post("/restore", reqEditorRole, bind(dtos.RestoreDashboardVersionCommand{}), wrap(RestoreDashboardVersion))
dashIdRoute.Group("/acl", func(aclRoute RouteRegister) {
aclRoute.Get("/", wrap(GetDashboardAclList))
aclRoute.Post("/", bind(dtos.UpdateDashboardAclCommand{}), wrap(UpdateDashboardAcl))
aclRoute.Delete("/:aclId", wrap(DeleteDashboardAcl))
})
})
})
// Dashboard snapshots
apiRoute.Group("/dashboard/snapshots", func(dashboardRoute RouteRegister) {
dashboardRoute.Get("/", wrap(SearchDashboardSnapshots))
})
// Playlist
apiRoute.Group("/playlists", func(playlistRoute RouteRegister) {
playlistRoute.Get("/", wrap(SearchPlaylists))
playlistRoute.Get("/:id", ValidateOrgPlaylist, wrap(GetPlaylist))
playlistRoute.Get("/:id/items", ValidateOrgPlaylist, wrap(GetPlaylistItems))
playlistRoute.Get("/:id/dashboards", ValidateOrgPlaylist, wrap(GetPlaylistDashboards))
playlistRoute.Delete("/:id", reqEditorRole, ValidateOrgPlaylist, wrap(DeletePlaylist))
playlistRoute.Put("/:id", reqEditorRole, bind(m.UpdatePlaylistCommand{}), ValidateOrgPlaylist, wrap(UpdatePlaylist))
playlistRoute.Post("/", reqEditorRole, bind(m.CreatePlaylistCommand{}), wrap(CreatePlaylist))
})
// Search
apiRoute.Get("/search/", Search)
// metrics
apiRoute.Post("/tsdb/query", bind(dtos.MetricRequest{}), wrap(QueryMetrics))
apiRoute.Get("/tsdb/testdata/scenarios", wrap(GetTestDataScenarios))
apiRoute.Get("/tsdb/testdata/gensql", reqGrafanaAdmin, wrap(GenerateSqlTestData))
apiRoute.Get("/tsdb/testdata/random-walk", wrap(GetTestDataRandomWalk))
apiRoute.Group("/alerts", func(alertsRoute RouteRegister) {
alertsRoute.Post("/test", bind(dtos.AlertTestCommand{}), wrap(AlertTest))
alertsRoute.Post("/:alertId/pause", reqEditorRole, bind(dtos.PauseAlertCommand{}), wrap(PauseAlert))
alertsRoute.Get("/:alertId", ValidateOrgAlert, wrap(GetAlert))
alertsRoute.Get("/", wrap(GetAlerts))
alertsRoute.Get("/states-for-dashboard", wrap(GetAlertStatesForDashboard))
})
apiRoute.Get("/alert-notifications", wrap(GetAlertNotifications))
apiRoute.Get("/alert-notifiers", wrap(GetAlertNotifiers))
apiRoute.Group("/alert-notifications", func(alertNotifications RouteRegister) {
alertNotifications.Post("/test", bind(dtos.NotificationTestCommand{}), wrap(NotificationTest))
alertNotifications.Post("/", bind(m.CreateAlertNotificationCommand{}), wrap(CreateAlertNotification))
alertNotifications.Put("/:notificationId", bind(m.UpdateAlertNotificationCommand{}), wrap(UpdateAlertNotification))
alertNotifications.Get("/:notificationId", wrap(GetAlertNotificationById))
alertNotifications.Delete("/:notificationId", wrap(DeleteAlertNotification))
}, reqEditorRole)
apiRoute.Get("/annotations", wrap(GetAnnotations))
apiRoute.Post("/annotations/mass-delete", reqOrgAdmin, bind(dtos.DeleteAnnotationsCmd{}), wrap(DeleteAnnotations))
apiRoute.Group("/annotations", func(annotationsRoute RouteRegister) {
annotationsRoute.Post("/", bind(dtos.PostAnnotationsCmd{}), wrap(PostAnnotation))
annotationsRoute.Delete("/:annotationId", wrap(DeleteAnnotationById))
annotationsRoute.Put("/:annotationId", bind(dtos.UpdateAnnotationsCmd{}), wrap(UpdateAnnotation))
annotationsRoute.Delete("/region/:regionId", wrap(DeleteAnnotationRegion))
annotationsRoute.Post("/graphite", bind(dtos.PostGraphiteAnnotationsCmd{}), wrap(PostGraphiteAnnotation))
}, reqEditorRole)
// error test
r.Get("/metrics/error", wrap(GenerateError))
}, reqSignedIn)
// admin api
r.Group("/api/admin", func(adminRoute RouteRegister) {
adminRoute.Get("/settings", AdminGetSettings)
adminRoute.Post("/users", bind(dtos.AdminCreateUserForm{}), AdminCreateUser)
adminRoute.Put("/users/:id/password", bind(dtos.AdminUpdateUserPasswordForm{}), AdminUpdateUserPassword)
adminRoute.Put("/users/:id/permissions", bind(dtos.AdminUpdateUserPermissionsForm{}), AdminUpdateUserPermissions)
adminRoute.Delete("/users/:id", AdminDeleteUser)
adminRoute.Get("/users/:id/quotas", wrap(GetUserQuotas))
adminRoute.Put("/users/:id/quotas/:target", bind(m.UpdateUserQuotaCmd{}), wrap(UpdateUserQuota))
adminRoute.Get("/stats", AdminGetStats)
adminRoute.Post("/pause-all-alerts", bind(dtos.PauseAllAlertsCommand{}), wrap(PauseAllAlerts))
}, reqGrafanaAdmin)
// rendering
r.Get("/render/*", reqSignedIn, RenderToPng)
// grafana.net proxy
r.Any("/api/gnet/*", reqSignedIn, ProxyGnetRequest)
// Gravatar service.
avatarCacheServer := avatar.NewCacheServer()
r.Get("/avatar/:hash", avatarCacheServer.Handler)
// Websocket
r.Any("/ws", hs.streamManager.Serve)
// streams
//r.Post("/api/streams/push", reqSignedIn, bind(dtos.StreamMessage{}), liveConn.PushToStream)
r.Register(macaronR)
InitAppPluginRoutes(macaronR)
macaronR.NotFound(NotFoundHandler)
}
| pkg/api/api.go | 1 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.9878177046775818,
0.026863887906074524,
0.000163051561685279,
0.00017021126404870301,
0.16015897691249847
]
|
{
"id": 7,
"code_window": [
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallGetDashboardUidBySlug(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should be denied access\", func() {\n",
"\t\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n",
"\t\t\t\tConvey(\"Should lookup dashboard by slug\", func() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 374
} | Copyright 2015 James Saryerwinnie
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| vendor/github.com/jmespath/go-jmespath/LICENSE | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017882049723993987,
0.0001735145051497966,
0.00016820852761156857,
0.0001735145051497966,
0.000005305984814185649
]
|
{
"id": 7,
"code_window": [
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallGetDashboardUidBySlug(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should be denied access\", func() {\n",
"\t\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n",
"\t\t\t\tConvey(\"Should lookup dashboard by slug\", func() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 374
} | .get-more-plugins-link {
color: $gray-3;
font-size: $font-size-sm;
position: relative;
top: 1.2rem;
&:hover {
color: $link-hover-color;
}
img {
vertical-align: top;
}
}
@include media-breakpoint-down(sm) {
.get-more-plugins-link {
display: none;
}
}
.plugin-info-list-item {
img {
width: 16px;
}
white-space: nowrap;
max-width: $page-sidebar-width;
text-overflow: ellipsis;
overflow: hidden;
}
| public/sass/pages/_plugins.scss | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.0001736509002512321,
0.00017158302944153547,
0.00016745654284022748,
0.00017364163068123162,
0.0000029178656859585317
]
|
{
"id": 7,
"code_window": [
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallGetDashboardUidBySlug(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should be denied access\", func() {\n",
"\t\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n",
"\t\t\t\tConvey(\"Should lookup dashboard by slug\", func() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 374
} | package notifiers
import (
"testing"
"github.com/grafana/grafana/pkg/components/simplejson"
m "github.com/grafana/grafana/pkg/models"
. "github.com/smartystreets/goconvey/convey"
)
func TestHipChatNotifier(t *testing.T) {
Convey("HipChat notifier tests", t, func() {
Convey("Parsing alert notification from settings", func() {
Convey("empty settings should return error", func() {
json := `{ }`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &m.AlertNotification{
Name: "ops",
Type: "hipchat",
Settings: settingsJSON,
}
_, err := NewHipChatNotifier(model)
So(err, ShouldNotBeNil)
})
Convey("from settings", func() {
json := `
{
"url": "http://google.com"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &m.AlertNotification{
Name: "ops",
Type: "hipchat",
Settings: settingsJSON,
}
not, err := NewHipChatNotifier(model)
hipchatNotifier := not.(*HipChatNotifier)
So(err, ShouldBeNil)
So(hipchatNotifier.Name, ShouldEqual, "ops")
So(hipchatNotifier.Type, ShouldEqual, "hipchat")
So(hipchatNotifier.Url, ShouldEqual, "http://google.com")
So(hipchatNotifier.ApiKey, ShouldEqual, "")
So(hipchatNotifier.RoomId, ShouldEqual, "")
})
Convey("from settings with Recipient and Mention", func() {
json := `
{
"url": "http://www.hipchat.com",
"apikey": "1234",
"roomid": "1234"
}`
settingsJSON, _ := simplejson.NewJson([]byte(json))
model := &m.AlertNotification{
Name: "ops",
Type: "hipchat",
Settings: settingsJSON,
}
not, err := NewHipChatNotifier(model)
hipchatNotifier := not.(*HipChatNotifier)
So(err, ShouldBeNil)
So(hipchatNotifier.Name, ShouldEqual, "ops")
So(hipchatNotifier.Type, ShouldEqual, "hipchat")
So(hipchatNotifier.Url, ShouldEqual, "http://www.hipchat.com")
So(hipchatNotifier.ApiKey, ShouldEqual, "1234")
So(hipchatNotifier.RoomId, ShouldEqual, "1234")
})
})
})
}
| pkg/services/alerting/notifiers/hipchat_test.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.0002927394525613636,
0.00018086792260874063,
0.00016499431512784213,
0.00016737751138862222,
0.00003956737418775447
]
|
{
"id": 8,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanSave, ShouldBeTrue)\n",
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeFalse)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 200)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 447
} | package api
import (
"encoding/json"
"path/filepath"
"testing"
macaron "gopkg.in/macaron.v1"
"github.com/go-macaron/session"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
type fakeDashboardRepo struct {
inserted []*dashboards.SaveDashboardItem
getDashboard []*m.Dashboard
}
func (repo *fakeDashboardRepo) SaveDashboard(json *dashboards.SaveDashboardItem) (*m.Dashboard, error) {
repo.inserted = append(repo.inserted, json)
return json.Dashboard, nil
}
var fakeRepo *fakeDashboardRepo
func TestDashboardApiEndpoint(t *testing.T) {
Convey("Given a dashboard with a parent folder which does not have an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = false
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
viewerRole := m.ROLE_VIEWER
editorRole := m.ROLE_EDITOR
aclMockResp := []*m.DashboardAclInfoDTO{
{Role: &viewerRole, Permission: m.PERMISSION_VIEW},
{Role: &editorRole, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
"id": fakeDash.Id,
}),
}
Convey("When user is an Org Viewer", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
Convey("When saving a dashboard folder in another folder", func() {
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
query.Result.IsFolder = true
return nil
})
invalidCmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
IsFolder: true,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("Should return an error", func() {
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, invalidCmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 400)
})
})
})
})
})
Convey("Given a dashboard with a parent folder which has an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = true
setting.ViewersCanEdit = false
aclMockResp := []*m.DashboardAclInfoDTO{
{
DashboardId: 1,
Permission: m.PERMISSION_EDIT,
UserId: 200,
},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"id": fakeDash.Id,
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("When user is an Org Viewer and has no permissions for this dashboard", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor and has no permissions for this dashboard", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Viewer but has an edit permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Viewer and viewers can edit", func() {
role := m.ROLE_VIEWER
setting.ViewersCanEdit = true
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
})
Convey("When user is an Org Viewer but has an admin permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_ADMIN},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Editor but has a view permission", func() {
role := m.ROLE_EDITOR
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
})
}
func GetDashboardShouldReturn200(sc *scenarioContext) dtos.DashboardFullWithMeta {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
So(sc.resp.Code, ShouldEqual, 200)
dash := dtos.DashboardFullWithMeta{}
err := json.NewDecoder(sc.resp.Body).Decode(&dash)
So(err, ShouldBeNil)
return dash
}
func GetDashboardUidBySlugShouldReturn200(sc *scenarioContext) string {
CallGetDashboardUidBySlug(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
return result.Get("uid").MustString()
}
func CallGetDashboardUidBySlug(sc *scenarioContext) {
sc.handlerFunc = GetDashboardUidBySlug
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersion(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error {
query.Result = &m.DashboardVersion{}
return nil
})
sc.handlerFunc = GetDashboardVersion
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersions(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionsQuery) error {
query.Result = []*m.DashboardVersionDTO{}
return nil
})
sc.handlerFunc = GetDashboardVersions
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallDeleteDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error {
return nil
})
sc.handlerFunc = DeleteDashboard
sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec()
}
func CallPostDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *alerting.ValidateDashboardAlertsCommand) error {
return nil
})
bus.AddHandler("test", func(cmd *m.SaveDashboardCommand) error {
cmd.Result = &m.Dashboard{Id: 2, Slug: "Dash", Version: 2}
return nil
})
bus.AddHandler("test", func(cmd *alerting.UpdateDashboardAlertsCommand) error {
return nil
})
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec()
}
func postDashboardScenario(desc string, url string, routePattern string, role m.RoleType, cmd m.SaveDashboardCommand, fn scenarioFunc) {
Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers()
sc := &scenarioContext{
url: url,
}
viewsPath, _ := filepath.Abs("../../public/views")
sc.m = macaron.New()
sc.m.Use(macaron.Renderer(macaron.RenderOptions{
Directory: viewsPath,
Delims: macaron.Delims{Left: "[[", Right: "]]"},
}))
sc.m.Use(middleware.GetContextHandler())
sc.m.Use(middleware.Sessioner(&session.Options{}))
sc.defaultHandler = wrap(func(c *middleware.Context) Response {
sc.context = c
sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID
sc.context.OrgRole = role
return PostDashboard(c, cmd)
})
fakeRepo = &fakeDashboardRepo{}
dashboards.SetRepository(fakeRepo)
sc.m.Post(routePattern, sc.defaultHandler)
fn(sc)
})
}
func (sc *scenarioContext) ToJson() *simplejson.Json {
var result *simplejson.Json
err := json.NewDecoder(sc.resp.Body).Decode(&result)
So(err, ShouldBeNil)
return result
}
| pkg/api/dashboard_test.go | 1 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.9981622099876404,
0.11709406226873398,
0.00016388545918744057,
0.006864690221846104,
0.29288169741630554
]
|
{
"id": 8,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanSave, ShouldBeTrue)\n",
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeFalse)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 200)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 447
} | import coreModule from '../../core/core_module';
export class PlaylistSearchCtrl {
query: any;
tagsMode: boolean;
searchStarted: any;
/** @ngInject */
constructor($timeout, private backendSrv) {
this.query = { query: '', tag: [], starred: false, limit: 30 };
$timeout(() => {
this.query.query = '';
this.searchDashboards();
}, 100);
}
searchDashboards() {
this.tagsMode = false;
var prom: any = {};
prom.promise = this.backendSrv.search(this.query).then(result => {
return {
dashboardResult: result,
tagResult: [],
};
});
this.searchStarted(prom);
}
showStarred() {
this.query.starred = !this.query.starred;
this.searchDashboards();
}
queryHasNoFilters() {
return this.query.query === '' && this.query.starred === false && this.query.tag.length === 0;
}
filterByTag(tag, evt) {
this.query.tag.push(tag);
this.searchDashboards();
if (evt) {
evt.stopPropagation();
evt.preventDefault();
}
}
getTags() {
var prom: any = {};
prom.promise = this.backendSrv.get('/api/dashboards/tags').then(result => {
return {
dashboardResult: [],
tagResult: result,
};
});
this.searchStarted(prom);
}
}
export function playlistSearchDirective() {
return {
restrict: 'E',
templateUrl: 'public/app/features/playlist/partials/playlist_search.html',
controller: PlaylistSearchCtrl,
bindToController: true,
controllerAs: 'ctrl',
scope: {
searchStarted: '&',
},
};
}
coreModule.directive('playlistSearch', playlistSearchDirective);
| public/app/features/playlist/playlist_search.ts | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00018059673311654478,
0.00016962530207820237,
0.00016409670934081078,
0.00016814815171528608,
0.0000052731479627254885
]
|
{
"id": 8,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanSave, ShouldBeTrue)\n",
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeFalse)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 200)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 447
} | <?xml version="1.0" encoding="iso-8859-1"?>
<!-- Generator: Adobe Illustrator 19.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="100px" height="100px" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve">
<polyline style="fill:none;stroke:#898989;stroke-width:2;stroke-miterlimit:10;" points="4.734,34.349 36.05,19.26 64.876,36.751
96.308,6.946 "/>
<circle style="fill:#898989;" cx="4.885" cy="33.929" r="4.885"/>
<circle style="fill:#898989;" cx="35.95" cy="19.545" r="4.885"/>
<circle style="fill:#898989;" cx="65.047" cy="36.046" r="4.885"/>
<circle style="fill:#898989;" cx="94.955" cy="7.135" r="4.885"/>
<g>
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="5" y1="103.7019" x2="5" y2="32.0424">
<stop offset="0" style="stop-color:#FFF33B"/>
<stop offset="0" style="stop-color:#FFD53F"/>
<stop offset="0" style="stop-color:#FBBC40"/>
<stop offset="0" style="stop-color:#F7A840"/>
<stop offset="0" style="stop-color:#F59B40"/>
<stop offset="0" style="stop-color:#F3933F"/>
<stop offset="0" style="stop-color:#F3903F"/>
<stop offset="0.8423" style="stop-color:#ED683C"/>
<stop offset="1" style="stop-color:#E93E3A"/>
</linearGradient>
<path style="fill:url(#SVGID_1_);" d="M9.001,48.173H0.999C0.447,48.173,0,48.62,0,49.172V100h10V49.172
C10,48.62,9.553,48.173,9.001,48.173z"/>
<linearGradient id="SVGID_2_" gradientUnits="userSpaceOnUse" x1="5" y1="98.9423" x2="5" y2="53.1961">
<stop offset="0" style="stop-color:#FEBC11"/>
<stop offset="1" style="stop-color:#F99B1C"/>
</linearGradient>
<path style="fill:url(#SVGID_2_);" d="M0,69.173v30.563h10V69.173"/>
<linearGradient id="SVGID_3_" gradientUnits="userSpaceOnUse" x1="5" y1="99.4343" x2="5" y2="74.4359">
<stop offset="0" style="stop-color:#FEBC11"/>
<stop offset="1" style="stop-color:#FFDE17"/>
</linearGradient>
<path style="fill:url(#SVGID_3_);" d="M0,83.166v16.701h10V83.166"/>
</g>
<g>
<linearGradient id="SVGID_4_" gradientUnits="userSpaceOnUse" x1="20" y1="103.7019" x2="20" y2="32.0424">
<stop offset="0" style="stop-color:#FFF33B"/>
<stop offset="0" style="stop-color:#FFD53F"/>
<stop offset="0" style="stop-color:#FBBC40"/>
<stop offset="0" style="stop-color:#F7A840"/>
<stop offset="0" style="stop-color:#F59B40"/>
<stop offset="0" style="stop-color:#F3933F"/>
<stop offset="0" style="stop-color:#F3903F"/>
<stop offset="0.8423" style="stop-color:#ED683C"/>
<stop offset="1" style="stop-color:#E93E3A"/>
</linearGradient>
<path style="fill:url(#SVGID_4_);" d="M24.001,40.769h-8.002c-0.552,0-0.999,0.447-0.999,0.999V100h10V41.768
C25,41.216,24.553,40.769,24.001,40.769z"/>
<linearGradient id="SVGID_5_" gradientUnits="userSpaceOnUse" x1="20" y1="98.9423" x2="20" y2="53.1961">
<stop offset="0" style="stop-color:#FEBC11"/>
<stop offset="1" style="stop-color:#F99B1C"/>
</linearGradient>
<path style="fill:url(#SVGID_5_);" d="M15,64.716v35.02h10v-35.02"/>
<linearGradient id="SVGID_6_" gradientUnits="userSpaceOnUse" x1="20" y1="99.4343" x2="20" y2="74.4359">
<stop offset="0" style="stop-color:#FEBC11"/>
<stop offset="1" style="stop-color:#FFDE17"/>
</linearGradient>
<path style="fill:url(#SVGID_6_);" d="M15,80.731v19.137h10V80.731"/>
</g>
<g>
<linearGradient id="SVGID_7_" gradientUnits="userSpaceOnUse" x1="35" y1="103.7019" x2="35" y2="32.0424">
<stop offset="0" style="stop-color:#FFF33B"/>
<stop offset="0" style="stop-color:#FFD53F"/>
<stop offset="0" style="stop-color:#FBBC40"/>
<stop offset="0" style="stop-color:#F7A840"/>
<stop offset="0" style="stop-color:#F59B40"/>
<stop offset="0" style="stop-color:#F3933F"/>
<stop offset="0" style="stop-color:#F3903F"/>
<stop offset="0.8423" style="stop-color:#ED683C"/>
<stop offset="1" style="stop-color:#E93E3A"/>
</linearGradient>
<path style="fill:url(#SVGID_7_);" d="M39.001,34.423h-8.002c-0.552,0-0.999,0.447-0.999,0.999V100h10V35.422
C40,34.87,39.553,34.423,39.001,34.423z"/>
<linearGradient id="SVGID_8_" gradientUnits="userSpaceOnUse" x1="35" y1="98.9423" x2="35" y2="53.1961">
<stop offset="0" style="stop-color:#FEBC11"/>
<stop offset="1" style="stop-color:#F99B1C"/>
</linearGradient>
<path style="fill:url(#SVGID_8_);" d="M30,60.895v38.84h10v-38.84"/>
<linearGradient id="SVGID_9_" gradientUnits="userSpaceOnUse" x1="35" y1="99.4343" x2="35" y2="74.4359">
<stop offset="0" style="stop-color:#FEBC11"/>
<stop offset="1" style="stop-color:#FFDE17"/>
</linearGradient>
<path style="fill:url(#SVGID_9_);" d="M30,78.643v21.225h10V78.643"/>
</g>
<g>
<linearGradient id="SVGID_10_" gradientUnits="userSpaceOnUse" x1="50" y1="103.7019" x2="50" y2="32.0424">
<stop offset="0" style="stop-color:#FFF33B"/>
<stop offset="0" style="stop-color:#FFD53F"/>
<stop offset="0" style="stop-color:#FBBC40"/>
<stop offset="0" style="stop-color:#F7A840"/>
<stop offset="0" style="stop-color:#F59B40"/>
<stop offset="0" style="stop-color:#F3933F"/>
<stop offset="0" style="stop-color:#F3903F"/>
<stop offset="0.8423" style="stop-color:#ED683C"/>
<stop offset="1" style="stop-color:#E93E3A"/>
</linearGradient>
<path style="fill:url(#SVGID_10_);" d="M54.001,41.827h-8.002c-0.552,0-0.999,0.447-0.999,0.999V100h10V42.826
C55,42.274,54.553,41.827,54.001,41.827z"/>
<linearGradient id="SVGID_11_" gradientUnits="userSpaceOnUse" x1="50" y1="98.9423" x2="50" y2="53.1961">
<stop offset="0" style="stop-color:#FEBC11"/>
<stop offset="1" style="stop-color:#F99B1C"/>
</linearGradient>
<path style="fill:url(#SVGID_11_);" d="M45,65.352v34.383h10V65.352"/>
<linearGradient id="SVGID_12_" gradientUnits="userSpaceOnUse" x1="50" y1="99.4343" x2="50" y2="74.4359">
<stop offset="0" style="stop-color:#FEBC11"/>
<stop offset="1" style="stop-color:#FFDE17"/>
</linearGradient>
<path style="fill:url(#SVGID_12_);" d="M45,81.079v18.789h10V81.079"/>
</g>
<g>
<linearGradient id="SVGID_13_" gradientUnits="userSpaceOnUse" x1="65" y1="103.8575" x2="65" y2="29.1875">
<stop offset="0" style="stop-color:#FFF33B"/>
<stop offset="0" style="stop-color:#FFD53F"/>
<stop offset="0" style="stop-color:#FBBC40"/>
<stop offset="0" style="stop-color:#F7A840"/>
<stop offset="0" style="stop-color:#F59B40"/>
<stop offset="0" style="stop-color:#F3933F"/>
<stop offset="0" style="stop-color:#F3903F"/>
<stop offset="0.8423" style="stop-color:#ED683C"/>
<stop offset="1" style="stop-color:#E93E3A"/>
</linearGradient>
<path style="fill:url(#SVGID_13_);" d="M69.001,50.404h-8.002c-0.552,0-0.999,0.447-0.999,0.999V100h10V51.403
C70,50.851,69.553,50.404,69.001,50.404z"/>
<linearGradient id="SVGID_14_" gradientUnits="userSpaceOnUse" x1="65" y1="98.8979" x2="65" y2="51.2298">
<stop offset="0" style="stop-color:#FEBC11"/>
<stop offset="1" style="stop-color:#F99B1C"/>
</linearGradient>
<path style="fill:url(#SVGID_14_);" d="M60,70.531v29.193h10V70.531"/>
<linearGradient id="SVGID_15_" gradientUnits="userSpaceOnUse" x1="65" y1="99.4105" x2="65" y2="73.3619">
<stop offset="0" style="stop-color:#FEBC11"/>
<stop offset="1" style="stop-color:#FFDE17"/>
</linearGradient>
<path style="fill:url(#SVGID_15_);" d="M60,83.909v15.953h10V83.909"/>
</g>
<g>
<linearGradient id="SVGID_16_" gradientUnits="userSpaceOnUse" x1="80" y1="104.4108" x2="80" y2="19.0293">
<stop offset="0" style="stop-color:#FFF33B"/>
<stop offset="0" style="stop-color:#FFD53F"/>
<stop offset="0" style="stop-color:#FBBC40"/>
<stop offset="0" style="stop-color:#F7A840"/>
<stop offset="0" style="stop-color:#F59B40"/>
<stop offset="0" style="stop-color:#F3933F"/>
<stop offset="0" style="stop-color:#F3903F"/>
<stop offset="0.8423" style="stop-color:#ED683C"/>
<stop offset="1" style="stop-color:#E93E3A"/>
</linearGradient>
<path style="fill:url(#SVGID_16_);" d="M84.001,40.769h-8.002c-0.552,0-0.999,0.447-0.999,0.999V100h10V41.768
C85,41.216,84.553,40.769,84.001,40.769z"/>
<linearGradient id="SVGID_17_" gradientUnits="userSpaceOnUse" x1="80" y1="98.9423" x2="80" y2="53.1961">
<stop offset="0" style="stop-color:#FEBC11"/>
<stop offset="1" style="stop-color:#F99B1C"/>
</linearGradient>
<path style="fill:url(#SVGID_17_);" d="M75,64.716v35.02h10v-35.02"/>
<linearGradient id="SVGID_18_" gradientUnits="userSpaceOnUse" x1="80" y1="99.4343" x2="80" y2="74.4359">
<stop offset="0" style="stop-color:#FEBC11"/>
<stop offset="1" style="stop-color:#FFDE17"/>
</linearGradient>
<path style="fill:url(#SVGID_18_);" d="M75,80.731v19.137h10V80.731"/>
</g>
<g>
<linearGradient id="SVGID_19_" gradientUnits="userSpaceOnUse" x1="95" y1="103.5838" x2="95" y2="34.2115">
<stop offset="0" style="stop-color:#FFF33B"/>
<stop offset="0" style="stop-color:#FFD53F"/>
<stop offset="0" style="stop-color:#FBBC40"/>
<stop offset="0" style="stop-color:#F7A840"/>
<stop offset="0" style="stop-color:#F59B40"/>
<stop offset="0" style="stop-color:#F3933F"/>
<stop offset="0" style="stop-color:#F3903F"/>
<stop offset="0.8423" style="stop-color:#ED683C"/>
<stop offset="1" style="stop-color:#E93E3A"/>
</linearGradient>
<path style="fill:url(#SVGID_19_);" d="M99.001,21.157h-8.002c-0.552,0-0.999,0.447-0.999,0.999V100h10V22.156
C100,21.604,99.553,21.157,99.001,21.157z"/>
<linearGradient id="SVGID_20_" gradientUnits="userSpaceOnUse" x1="95" y1="98.9761" x2="95" y2="54.69">
<stop offset="0" style="stop-color:#FEBC11"/>
<stop offset="1" style="stop-color:#F99B1C"/>
</linearGradient>
<path style="fill:url(#SVGID_20_);" d="M90,52.898v46.846h10V52.898"/>
<linearGradient id="SVGID_21_" gradientUnits="userSpaceOnUse" x1="95" y1="99.4524" x2="95" y2="75.2518">
<stop offset="0" style="stop-color:#FEBC11"/>
<stop offset="1" style="stop-color:#FFDE17"/>
</linearGradient>
<path style="fill:url(#SVGID_21_);" d="M90,74.272v25.6h10v-25.6"/>
</g>
</svg>
| public/app/plugins/panel/graph/img/icn-graph-panel.svg | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017218694847542793,
0.00016889901598915458,
0.0001654420339036733,
0.00016841779870446771,
0.0000016637640101180295
]
|
{
"id": 8,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanSave, ShouldBeTrue)\n",
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeFalse)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 200)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 447
} | import store from 'app/core/store';
import _ from 'lodash';
import config from 'app/core/config';
export class ImpressionSrv {
constructor() {}
addDashboardImpression(dashboardId) {
var impressionsKey = this.impressionKey(config);
var impressions = [];
if (store.exists(impressionsKey)) {
impressions = JSON.parse(store.get(impressionsKey));
if (!_.isArray(impressions)) {
impressions = [];
}
}
impressions = impressions.filter(imp => {
return dashboardId !== imp;
});
impressions.unshift(dashboardId);
if (impressions.length > 50) {
impressions.pop();
}
store.set(impressionsKey, JSON.stringify(impressions));
}
getDashboardOpened() {
var impressions = store.get(this.impressionKey(config)) || '[]';
impressions = JSON.parse(impressions);
impressions = _.filter(impressions, el => {
return _.isNumber(el);
});
return impressions;
}
impressionKey(config) {
return 'dashboard_impressions-' + config.bootData.user.orgId;
}
}
const impressionSrv = new ImpressionSrv();
export default impressionSrv;
| public/app/core/services/impression_srv.ts | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00019921862985938787,
0.00017311805277131498,
0.00016470273840241134,
0.00016648742894176394,
0.000013155485248717014
]
|
{
"id": 9,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeFalse)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 526
} | package api
import (
"encoding/json"
"path/filepath"
"testing"
macaron "gopkg.in/macaron.v1"
"github.com/go-macaron/session"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
type fakeDashboardRepo struct {
inserted []*dashboards.SaveDashboardItem
getDashboard []*m.Dashboard
}
func (repo *fakeDashboardRepo) SaveDashboard(json *dashboards.SaveDashboardItem) (*m.Dashboard, error) {
repo.inserted = append(repo.inserted, json)
return json.Dashboard, nil
}
var fakeRepo *fakeDashboardRepo
func TestDashboardApiEndpoint(t *testing.T) {
Convey("Given a dashboard with a parent folder which does not have an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = false
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
viewerRole := m.ROLE_VIEWER
editorRole := m.ROLE_EDITOR
aclMockResp := []*m.DashboardAclInfoDTO{
{Role: &viewerRole, Permission: m.PERMISSION_VIEW},
{Role: &editorRole, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
"id": fakeDash.Id,
}),
}
Convey("When user is an Org Viewer", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
Convey("When saving a dashboard folder in another folder", func() {
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
query.Result.IsFolder = true
return nil
})
invalidCmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
IsFolder: true,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("Should return an error", func() {
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, invalidCmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 400)
})
})
})
})
})
Convey("Given a dashboard with a parent folder which has an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = true
setting.ViewersCanEdit = false
aclMockResp := []*m.DashboardAclInfoDTO{
{
DashboardId: 1,
Permission: m.PERMISSION_EDIT,
UserId: 200,
},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"id": fakeDash.Id,
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("When user is an Org Viewer and has no permissions for this dashboard", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor and has no permissions for this dashboard", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Viewer but has an edit permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Viewer and viewers can edit", func() {
role := m.ROLE_VIEWER
setting.ViewersCanEdit = true
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
})
Convey("When user is an Org Viewer but has an admin permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_ADMIN},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Editor but has a view permission", func() {
role := m.ROLE_EDITOR
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
})
}
func GetDashboardShouldReturn200(sc *scenarioContext) dtos.DashboardFullWithMeta {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
So(sc.resp.Code, ShouldEqual, 200)
dash := dtos.DashboardFullWithMeta{}
err := json.NewDecoder(sc.resp.Body).Decode(&dash)
So(err, ShouldBeNil)
return dash
}
func GetDashboardUidBySlugShouldReturn200(sc *scenarioContext) string {
CallGetDashboardUidBySlug(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
return result.Get("uid").MustString()
}
func CallGetDashboardUidBySlug(sc *scenarioContext) {
sc.handlerFunc = GetDashboardUidBySlug
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersion(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error {
query.Result = &m.DashboardVersion{}
return nil
})
sc.handlerFunc = GetDashboardVersion
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersions(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionsQuery) error {
query.Result = []*m.DashboardVersionDTO{}
return nil
})
sc.handlerFunc = GetDashboardVersions
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallDeleteDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error {
return nil
})
sc.handlerFunc = DeleteDashboard
sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec()
}
func CallPostDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *alerting.ValidateDashboardAlertsCommand) error {
return nil
})
bus.AddHandler("test", func(cmd *m.SaveDashboardCommand) error {
cmd.Result = &m.Dashboard{Id: 2, Slug: "Dash", Version: 2}
return nil
})
bus.AddHandler("test", func(cmd *alerting.UpdateDashboardAlertsCommand) error {
return nil
})
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec()
}
func postDashboardScenario(desc string, url string, routePattern string, role m.RoleType, cmd m.SaveDashboardCommand, fn scenarioFunc) {
Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers()
sc := &scenarioContext{
url: url,
}
viewsPath, _ := filepath.Abs("../../public/views")
sc.m = macaron.New()
sc.m.Use(macaron.Renderer(macaron.RenderOptions{
Directory: viewsPath,
Delims: macaron.Delims{Left: "[[", Right: "]]"},
}))
sc.m.Use(middleware.GetContextHandler())
sc.m.Use(middleware.Sessioner(&session.Options{}))
sc.defaultHandler = wrap(func(c *middleware.Context) Response {
sc.context = c
sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID
sc.context.OrgRole = role
return PostDashboard(c, cmd)
})
fakeRepo = &fakeDashboardRepo{}
dashboards.SetRepository(fakeRepo)
sc.m.Post(routePattern, sc.defaultHandler)
fn(sc)
})
}
func (sc *scenarioContext) ToJson() *simplejson.Json {
var result *simplejson.Json
err := json.NewDecoder(sc.resp.Body).Decode(&result)
So(err, ShouldBeNil)
return result
}
| pkg/api/dashboard_test.go | 1 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.9983488321304321,
0.11753503233194351,
0.00016336840053554624,
0.00565273966640234,
0.29096198081970215
]
|
{
"id": 9,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeFalse)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 526
} | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
// +build !gccgo
package unix
import "syscall"
func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno)
func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno)
func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
| vendor/golang.org/x/sys/unix/syscall_unix_gc.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017676687275525182,
0.00017349881818518043,
0.0001702307490631938,
0.00017349881818518043,
0.0000032680618460290134
]
|
{
"id": 9,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeFalse)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 526
} | // Copyright 2013 com authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package com
import (
"errors"
"fmt"
"os"
"path"
"strings"
)
// IsDir returns true if given path is a directory,
// or returns false when it's a file or does not exist.
func IsDir(dir string) bool {
f, e := os.Stat(dir)
if e != nil {
return false
}
return f.IsDir()
}
func statDir(dirPath, recPath string, includeDir, isDirOnly bool) ([]string, error) {
dir, err := os.Open(dirPath)
if err != nil {
return nil, err
}
defer dir.Close()
fis, err := dir.Readdir(0)
if err != nil {
return nil, err
}
statList := make([]string, 0)
for _, fi := range fis {
if strings.Contains(fi.Name(), ".DS_Store") {
continue
}
relPath := path.Join(recPath, fi.Name())
curPath := path.Join(dirPath, fi.Name())
if fi.IsDir() {
if includeDir {
statList = append(statList, relPath+"/")
}
s, err := statDir(curPath, relPath, includeDir, isDirOnly)
if err != nil {
return nil, err
}
statList = append(statList, s...)
} else if !isDirOnly {
statList = append(statList, relPath)
}
}
return statList, nil
}
// StatDir gathers information of given directory by depth-first.
// It returns slice of file list and includes subdirectories if enabled;
// it returns error and nil slice when error occurs in underlying functions,
// or given path is not a directory or does not exist.
//
// Slice does not include given path itself.
// If subdirectories is enabled, they will have suffix '/'.
func StatDir(rootPath string, includeDir ...bool) ([]string, error) {
if !IsDir(rootPath) {
return nil, errors.New("not a directory or does not exist: " + rootPath)
}
isIncludeDir := false
if len(includeDir) >= 1 {
isIncludeDir = includeDir[0]
}
return statDir(rootPath, "", isIncludeDir, false)
}
// GetAllSubDirs returns all subdirectories of given root path.
// Slice does not include given path itself.
func GetAllSubDirs(rootPath string) ([]string, error) {
if !IsDir(rootPath) {
return nil, errors.New("not a directory or does not exist: " + rootPath)
}
return statDir(rootPath, "", true, true)
}
// GetFileListBySuffix returns an ordered list of file paths.
// It recognize if given path is a file, and don't do recursive find.
func GetFileListBySuffix(dirPath, suffix string) ([]string, error) {
if !IsExist(dirPath) {
return nil, fmt.Errorf("given path does not exist: %s", dirPath)
} else if IsFile(dirPath) {
return []string{dirPath}, nil
}
// Given path is a directory.
dir, err := os.Open(dirPath)
if err != nil {
return nil, err
}
fis, err := dir.Readdir(0)
if err != nil {
return nil, err
}
files := make([]string, 0, len(fis))
for _, fi := range fis {
if strings.HasSuffix(fi.Name(), suffix) {
files = append(files, path.Join(dirPath, fi.Name()))
}
}
return files, nil
}
// CopyDir copy files recursively from source to target directory.
//
// The filter accepts a function that process the path info.
// and should return true for need to filter.
//
// It returns error when error occurs in underlying functions.
func CopyDir(srcPath, destPath string, filters ...func(filePath string) bool) error {
// Check if target directory exists.
if IsExist(destPath) {
return errors.New("file or directory alreay exists: " + destPath)
}
err := os.MkdirAll(destPath, os.ModePerm)
if err != nil {
return err
}
// Gather directory info.
infos, err := StatDir(srcPath, true)
if err != nil {
return err
}
var filter func(filePath string) bool
if len(filters) > 0 {
filter = filters[0]
}
for _, info := range infos {
if filter != nil && filter(info) {
continue
}
curPath := path.Join(destPath, info)
if strings.HasSuffix(info, "/") {
err = os.MkdirAll(curPath, os.ModePerm)
} else {
err = Copy(path.Join(srcPath, info), curPath)
}
if err != nil {
return err
}
}
return nil
}
| vendor/github.com/Unknwon/com/dir.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017994064546655864,
0.00016785814659669995,
0.00016292395594064146,
0.00016707973554730415,
0.000003711639010361978
]
|
{
"id": 9,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeFalse)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 526
} | .dashboard-list {
.search-results-container {
padding: 5px 0 0 0;
}
}
.search-results {
margin-top: 2rem;
}
.search-results-filter-row {
height: 35px;
display: flex;
justify-content: space-between;
.gf-form-button-row {
padding-top: 0;
button:last-child {
margin-right: 0;
}
}
}
.search-results-filter-row__filters {
display: flex;
}
.search-results-filter-row__filters-item {
width: 150px;
margin-right: 0;
}
| public/sass/components/_dashboard_list.scss | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017230222874786705,
0.00016953216982074082,
0.0001657342945691198,
0.00017004608525894582,
0.000002492889962013578
]
|
{
"id": 10,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeTrue)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 200)\n",
"\n",
"\t\t\t\tConvey(\"Should lookup dashboard by slug\", func() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 584
} | package api
import (
"encoding/json"
"fmt"
"os"
"path"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/dashdiffs"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/metrics"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
func isDashboardStarredByUser(c *middleware.Context, dashId int64) (bool, error) {
if !c.IsSignedIn {
return false, nil
}
query := m.IsStarredByUserQuery{UserId: c.UserId, DashboardId: dashId}
if err := bus.Dispatch(&query); err != nil {
return false, err
}
return query.Result, nil
}
func dashboardGuardianResponse(err error) Response {
if err != nil {
return ApiError(500, "Error while checking dashboard permissions", err)
} else {
return ApiError(403, "Access denied to this dashboard", nil)
}
}
func GetDashboard(c *middleware.Context) Response {
dash, rsp := getDashboardHelper(c.OrgId, c.Params(":slug"), 0, c.Params(":uid"))
if rsp != nil {
return rsp
}
guardian := guardian.NewDashboardGuardian(dash.Id, c.OrgId, c.SignedInUser)
if canView, err := guardian.CanView(); err != nil || !canView {
fmt.Printf("%v", err)
return dashboardGuardianResponse(err)
}
canEdit, _ := guardian.CanEdit()
canSave, _ := guardian.CanSave()
canAdmin, _ := guardian.CanAdmin()
isStarred, err := isDashboardStarredByUser(c, dash.Id)
if err != nil {
return ApiError(500, "Error while checking if dashboard was starred by user", err)
}
// Finding creator and last updater of the dashboard
updater, creator := "Anonymous", "Anonymous"
if dash.UpdatedBy > 0 {
updater = getUserLogin(dash.UpdatedBy)
}
if dash.CreatedBy > 0 {
creator = getUserLogin(dash.CreatedBy)
}
meta := dtos.DashboardMeta{
IsStarred: isStarred,
Slug: dash.Slug,
Type: m.DashTypeDB,
CanStar: c.IsSignedIn,
CanSave: canSave,
CanEdit: canEdit,
CanAdmin: canAdmin,
Created: dash.Created,
Updated: dash.Updated,
UpdatedBy: updater,
CreatedBy: creator,
Version: dash.Version,
HasAcl: dash.HasAcl,
IsFolder: dash.IsFolder,
FolderId: dash.FolderId,
FolderTitle: "Root",
}
// lookup folder title
if dash.FolderId > 0 {
query := m.GetDashboardQuery{Id: dash.FolderId, OrgId: c.OrgId}
if err := bus.Dispatch(&query); err != nil {
return ApiError(500, "Dashboard folder could not be read", err)
}
meta.FolderTitle = query.Result.Title
}
if dash.IsFolder {
meta.Url = m.GetFolderUrl(dash.Uid, dash.Slug)
} else {
meta.Url = m.GetDashboardUrl(dash.Uid, dash.Slug)
}
// make sure db version is in sync with json model version
dash.Data.Set("version", dash.Version)
dto := dtos.DashboardFullWithMeta{
Dashboard: dash.Data,
Meta: meta,
}
c.TimeRequest(metrics.M_Api_Dashboard_Get)
return Json(200, dto)
}
func GetDashboardUidBySlug(c *middleware.Context) Response {
dash, rsp := getDashboardHelper(c.OrgId, c.Params(":slug"), 0, "")
if rsp != nil {
return rsp
}
guardian := guardian.NewDashboardGuardian(dash.Id, c.OrgId, c.SignedInUser)
if canView, err := guardian.CanView(); err != nil || !canView {
fmt.Printf("%v", err)
return dashboardGuardianResponse(err)
}
return Json(200, util.DynMap{"uid": dash.Uid})
}
func getUserLogin(userId int64) string {
query := m.GetUserByIdQuery{Id: userId}
err := bus.Dispatch(&query)
if err != nil {
return "Anonymous"
} else {
user := query.Result
return user.Login
}
}
func getDashboardHelper(orgId int64, slug string, id int64, uid string) (*m.Dashboard, Response) {
var query m.GetDashboardQuery
if len(uid) > 0 {
query = m.GetDashboardQuery{Uid: uid, Id: id, OrgId: orgId}
} else {
query = m.GetDashboardQuery{Slug: slug, Id: id, OrgId: orgId}
}
if err := bus.Dispatch(&query); err != nil {
return nil, ApiError(404, "Dashboard not found", err)
}
return query.Result, nil
}
func DeleteDashboard(c *middleware.Context) Response {
dash, rsp := getDashboardHelper(c.OrgId, c.Params(":slug"), 0, "")
if rsp != nil {
return rsp
}
guardian := guardian.NewDashboardGuardian(dash.Id, c.OrgId, c.SignedInUser)
if canSave, err := guardian.CanSave(); err != nil || !canSave {
return dashboardGuardianResponse(err)
}
cmd := m.DeleteDashboardCommand{OrgId: c.OrgId, Id: dash.Id}
if err := bus.Dispatch(&cmd); err != nil {
return ApiError(500, "Failed to delete dashboard", err)
}
var resp = map[string]interface{}{"title": dash.Title}
return Json(200, resp)
}
func PostDashboard(c *middleware.Context, cmd m.SaveDashboardCommand) Response {
cmd.OrgId = c.OrgId
cmd.UserId = c.UserId
dash := cmd.GetDashboardModel()
guardian := guardian.NewDashboardGuardian(dash.Id, c.OrgId, c.SignedInUser)
if canSave, err := guardian.CanSave(); err != nil || !canSave {
return dashboardGuardianResponse(err)
}
if dash.IsFolder && dash.FolderId > 0 {
return ApiError(400, m.ErrDashboardFolderCannotHaveParent.Error(), nil)
}
// Check if Title is empty
if dash.Title == "" {
return ApiError(400, m.ErrDashboardTitleEmpty.Error(), nil)
}
if dash.Id == 0 {
limitReached, err := middleware.QuotaReached(c, "dashboard")
if err != nil {
return ApiError(500, "failed to get quota", err)
}
if limitReached {
return ApiError(403, "Quota reached", nil)
}
}
dashItem := &dashboards.SaveDashboardItem{
Dashboard: dash,
Message: cmd.Message,
OrgId: c.OrgId,
UserId: c.UserId,
Overwrite: cmd.Overwrite,
}
dashboard, err := dashboards.GetRepository().SaveDashboard(dashItem)
if err == m.ErrDashboardTitleEmpty {
return ApiError(400, m.ErrDashboardTitleEmpty.Error(), nil)
}
if err == m.ErrDashboardContainsInvalidAlertData {
return ApiError(500, "Invalid alert data. Cannot save dashboard", err)
}
if err != nil {
if err == m.ErrDashboardWithSameNameExists {
return Json(412, util.DynMap{"status": "name-exists", "message": err.Error()})
}
if err == m.ErrDashboardVersionMismatch {
return Json(412, util.DynMap{"status": "version-mismatch", "message": err.Error()})
}
if pluginErr, ok := err.(m.UpdatePluginDashboardError); ok {
message := "The dashboard belongs to plugin " + pluginErr.PluginId + "."
// look up plugin name
if pluginDef, exist := plugins.Plugins[pluginErr.PluginId]; exist {
message = "The dashboard belongs to plugin " + pluginDef.Name + "."
}
return Json(412, util.DynMap{"status": "plugin-dashboard", "message": message})
}
if err == m.ErrDashboardNotFound {
return Json(404, util.DynMap{"status": "not-found", "message": err.Error()})
}
return ApiError(500, "Failed to save dashboard", err)
}
if err == m.ErrDashboardFailedToUpdateAlertData {
return ApiError(500, "Invalid alert data. Cannot save dashboard", err)
}
c.TimeRequest(metrics.M_Api_Dashboard_Save)
return Json(200, util.DynMap{"status": "success", "slug": dashboard.Slug, "version": dashboard.Version, "id": dashboard.Id, "uid": dashboard.Uid})
}
func GetHomeDashboard(c *middleware.Context) Response {
prefsQuery := m.GetPreferencesWithDefaultsQuery{OrgId: c.OrgId, UserId: c.UserId}
if err := bus.Dispatch(&prefsQuery); err != nil {
return ApiError(500, "Failed to get preferences", err)
}
if prefsQuery.Result.HomeDashboardId != 0 {
slugQuery := m.GetDashboardSlugByIdQuery{Id: prefsQuery.Result.HomeDashboardId}
err := bus.Dispatch(&slugQuery)
if err == nil {
dashRedirect := dtos.DashboardRedirect{RedirectUri: "db/" + slugQuery.Result}
return Json(200, &dashRedirect)
} else {
log.Warn("Failed to get slug from database, %s", err.Error())
}
}
filePath := path.Join(setting.StaticRootPath, "dashboards/home.json")
file, err := os.Open(filePath)
if err != nil {
return ApiError(500, "Failed to load home dashboard", err)
}
dash := dtos.DashboardFullWithMeta{}
dash.Meta.IsHome = true
dash.Meta.CanEdit = c.SignedInUser.HasRole(m.ROLE_EDITOR)
dash.Meta.FolderTitle = "Root"
jsonParser := json.NewDecoder(file)
if err := jsonParser.Decode(&dash.Dashboard); err != nil {
return ApiError(500, "Failed to load home dashboard", err)
}
if c.HasUserRole(m.ROLE_ADMIN) && !c.HasHelpFlag(m.HelpFlagGettingStartedPanelDismissed) {
addGettingStartedPanelToHomeDashboard(dash.Dashboard)
}
return Json(200, &dash)
}
func addGettingStartedPanelToHomeDashboard(dash *simplejson.Json) {
panels := dash.Get("panels").MustArray()
newpanel := simplejson.NewFromAny(map[string]interface{}{
"type": "gettingstarted",
"id": 123123,
"gridPos": map[string]interface{}{
"x": 0,
"y": 3,
"w": 24,
"h": 4,
},
})
panels = append(panels, newpanel)
dash.Set("panels", panels)
}
// GetDashboardVersions returns all dashboard versions as JSON
func GetDashboardVersions(c *middleware.Context) Response {
dashId := c.ParamsInt64(":dashboardId")
guardian := guardian.NewDashboardGuardian(dashId, c.OrgId, c.SignedInUser)
if canSave, err := guardian.CanSave(); err != nil || !canSave {
return dashboardGuardianResponse(err)
}
query := m.GetDashboardVersionsQuery{
OrgId: c.OrgId,
DashboardId: dashId,
Limit: c.QueryInt("limit"),
Start: c.QueryInt("start"),
}
if err := bus.Dispatch(&query); err != nil {
return ApiError(404, fmt.Sprintf("No versions found for dashboardId %d", dashId), err)
}
for _, version := range query.Result {
if version.RestoredFrom == version.Version {
version.Message = "Initial save (created by migration)"
continue
}
if version.RestoredFrom > 0 {
version.Message = fmt.Sprintf("Restored from version %d", version.RestoredFrom)
continue
}
if version.ParentVersion == 0 {
version.Message = "Initial save"
}
}
return Json(200, query.Result)
}
// GetDashboardVersion returns the dashboard version with the given ID.
func GetDashboardVersion(c *middleware.Context) Response {
dashId := c.ParamsInt64(":dashboardId")
guardian := guardian.NewDashboardGuardian(dashId, c.OrgId, c.SignedInUser)
if canSave, err := guardian.CanSave(); err != nil || !canSave {
return dashboardGuardianResponse(err)
}
query := m.GetDashboardVersionQuery{
OrgId: c.OrgId,
DashboardId: dashId,
Version: c.ParamsInt(":id"),
}
if err := bus.Dispatch(&query); err != nil {
return ApiError(500, fmt.Sprintf("Dashboard version %d not found for dashboardId %d", query.Version, dashId), err)
}
creator := "Anonymous"
if query.Result.CreatedBy > 0 {
creator = getUserLogin(query.Result.CreatedBy)
}
dashVersionMeta := &m.DashboardVersionMeta{
DashboardVersion: *query.Result,
CreatedBy: creator,
}
return Json(200, dashVersionMeta)
}
// POST /api/dashboards/calculate-diff performs diffs on two dashboards
func CalculateDashboardDiff(c *middleware.Context, apiOptions dtos.CalculateDiffOptions) Response {
options := dashdiffs.Options{
OrgId: c.OrgId,
DiffType: dashdiffs.ParseDiffType(apiOptions.DiffType),
Base: dashdiffs.DiffTarget{
DashboardId: apiOptions.Base.DashboardId,
Version: apiOptions.Base.Version,
UnsavedDashboard: apiOptions.Base.UnsavedDashboard,
},
New: dashdiffs.DiffTarget{
DashboardId: apiOptions.New.DashboardId,
Version: apiOptions.New.Version,
UnsavedDashboard: apiOptions.New.UnsavedDashboard,
},
}
result, err := dashdiffs.CalculateDiff(&options)
if err != nil {
if err == m.ErrDashboardVersionNotFound {
return ApiError(404, "Dashboard version not found", err)
}
return ApiError(500, "Unable to compute diff", err)
}
if options.DiffType == dashdiffs.DiffDelta {
return Respond(200, result.Delta).Header("Content-Type", "application/json")
} else {
return Respond(200, result.Delta).Header("Content-Type", "text/html")
}
}
// RestoreDashboardVersion restores a dashboard to the given version.
func RestoreDashboardVersion(c *middleware.Context, apiCmd dtos.RestoreDashboardVersionCommand) Response {
dash, rsp := getDashboardHelper(c.OrgId, "", c.ParamsInt64(":dashboardId"), "")
if rsp != nil {
return rsp
}
guardian := guardian.NewDashboardGuardian(dash.Id, c.OrgId, c.SignedInUser)
if canSave, err := guardian.CanSave(); err != nil || !canSave {
return dashboardGuardianResponse(err)
}
versionQuery := m.GetDashboardVersionQuery{DashboardId: dash.Id, Version: apiCmd.Version, OrgId: c.OrgId}
if err := bus.Dispatch(&versionQuery); err != nil {
return ApiError(404, "Dashboard version not found", nil)
}
version := versionQuery.Result
saveCmd := m.SaveDashboardCommand{}
saveCmd.RestoredFrom = version.Version
saveCmd.OrgId = c.OrgId
saveCmd.UserId = c.UserId
saveCmd.Dashboard = version.Data
saveCmd.Dashboard.Set("version", dash.Version)
saveCmd.Message = fmt.Sprintf("Restored from version %d", version.Version)
return PostDashboard(c, saveCmd)
}
func GetDashboardTags(c *middleware.Context) {
query := m.GetDashboardTagsQuery{OrgId: c.OrgId}
err := bus.Dispatch(&query)
if err != nil {
c.JsonApiErr(500, "Failed to get tags from database", err)
return
}
c.JSON(200, query.Result)
}
| pkg/api/dashboard.go | 1 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.008490106090903282,
0.0012714603217318654,
0.00016553117893636227,
0.00034535719896666706,
0.0017324790824204683
]
|
{
"id": 10,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeTrue)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 200)\n",
"\n",
"\t\t\t\tConvey(\"Should lookup dashboard by slug\", func() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 584
} | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !gccgo
#include "textflag.h"
//
// System call support for AMD64, Darwin
//
// Just jump to package syscall's implementation for all these functions.
// The runtime may know about them.
TEXT ·Syscall(SB),NOSPLIT,$0-56
JMP syscall·Syscall(SB)
TEXT ·Syscall6(SB),NOSPLIT,$0-80
JMP syscall·Syscall6(SB)
TEXT ·Syscall9(SB),NOSPLIT,$0-104
JMP syscall·Syscall9(SB)
TEXT ·RawSyscall(SB),NOSPLIT,$0-56
JMP syscall·RawSyscall(SB)
TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
JMP syscall·RawSyscall6(SB)
| vendor/golang.org/x/sys/unix/asm_darwin_amd64.s | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017341659986414015,
0.00017029792070388794,
0.00016827366198413074,
0.00016920347115956247,
0.0000022376775632437784
]
|
{
"id": 10,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeTrue)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 200)\n",
"\n",
"\t\t\t\tConvey(\"Should lookup dashboard by slug\", func() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 584
} | <?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 20.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="64px" height="64px" viewBox="0 0 64 64" style="enable-background:new 0 0 64 64;" xml:space="preserve">
<style type="text/css">
.st0{fill:#E3E2E2;}
</style>
<g>
<path class="st0" d="M64,36.1v-8.1l-8.7-2.5c-0.5-1.8-1.3-3.6-2.2-5.2l4.4-7.9l-5.7-5.7l-7.9,4.4c-1.6-0.9-3.4-1.7-5.2-2.2L36.1,0
h-8.1l-2.5,8.7c-1.8,0.5-3.6,1.3-5.2,2.2l-7.9-4.4l-5.7,5.7l4.4,7.9c-0.9,1.6-1.7,3.4-2.2,5.2L0,27.9v8.1l8.7,2.5
c0.5,1.8,1.3,3.6,2.2,5.2l-4.4,7.9l5.7,5.7l7.9-4.4c1.6,0.9,3.4,1.7,5.2,2.2l2.5,8.7h8.1l2.5-8.7c1.8-0.5,3.6-1.3,5.2-2.2l7.9,4.4
l5.7-5.7l-4.4-7.9c0.9-1.6,1.7-3.4,2.2-5.2L64,36.1z M32,37.8c-3.2,0-5.8-2.6-5.8-5.8c0-3.2,2.6-5.8,5.8-5.8s5.8,2.6,5.8,5.8
C37.8,35.2,35.2,37.8,32,37.8z"/>
</g>
</svg>
| public/img/icons_dark_theme/icon_cog.svg | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00020694469276349992,
0.000186372606549412,
0.0001658005203353241,
0.000186372606549412,
0.000020572086214087903
]
|
{
"id": 10,
"code_window": [
"\t\t\t\t\tSo(dash.Meta.CanAdmin, ShouldBeTrue)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 200)\n",
"\n",
"\t\t\t\tConvey(\"Should lookup dashboard by slug\", func() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 584
} | package commands
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"regexp"
"strings"
"github.com/fatih/color"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/logger"
m "github.com/grafana/grafana/pkg/cmd/grafana-cli/models"
s "github.com/grafana/grafana/pkg/cmd/grafana-cli/services"
)
func validateInput(c CommandLine, pluginFolder string) error {
arg := c.Args().First()
if arg == "" {
return errors.New("please specify plugin to install")
}
pluginsDir := c.PluginDirectory()
if pluginsDir == "" {
return errors.New("missing pluginsDir flag")
}
fileInfo, err := os.Stat(pluginsDir)
if err != nil {
if err = os.MkdirAll(pluginsDir, os.ModePerm); err != nil {
return errors.New(fmt.Sprintf("pluginsDir (%s) is not a directory", pluginsDir))
}
return nil
}
if !fileInfo.IsDir() {
return errors.New("path is not a directory")
}
return nil
}
func installCommand(c CommandLine) error {
pluginFolder := c.PluginDirectory()
if err := validateInput(c, pluginFolder); err != nil {
return err
}
pluginToInstall := c.Args().First()
version := c.Args().Get(1)
return InstallPlugin(pluginToInstall, version, c)
}
func InstallPlugin(pluginName, version string, c CommandLine) error {
pluginFolder := c.PluginDirectory()
downloadURL := c.PluginURL()
if downloadURL == "" {
plugin, err := s.GetPlugin(pluginName, c.RepoDirectory())
if err != nil {
return err
}
v, err := SelectVersion(plugin, version)
if err != nil {
return err
}
if version == "" {
version = v.Version
}
downloadURL = fmt.Sprintf("%s/%s/versions/%s/download",
c.GlobalString("repo"),
pluginName,
version)
}
logger.Infof("installing %v @ %v\n", pluginName, version)
logger.Infof("from url: %v\n", downloadURL)
logger.Infof("into: %v\n", pluginFolder)
logger.Info("\n")
err := downloadFile(pluginName, pluginFolder, downloadURL)
if err != nil {
return err
}
logger.Infof("%s Installed %s successfully \n", color.GreenString("✔"), pluginName)
res, _ := s.ReadPlugin(pluginFolder, pluginName)
for _, v := range res.Dependencies.Plugins {
InstallPlugin(v.Id, version, c)
logger.Infof("Installed dependency: %v ✔\n", v.Id)
}
return err
}
func SelectVersion(plugin m.Plugin, version string) (m.Version, error) {
if version == "" {
return plugin.Versions[0], nil
}
for _, v := range plugin.Versions {
if v.Version == version {
return v, nil
}
}
return m.Version{}, errors.New("Could not find the version your looking for")
}
func RemoveGitBuildFromName(pluginName, filename string) string {
r := regexp.MustCompile("^[a-zA-Z0-9_.-]*/")
return r.ReplaceAllString(filename, pluginName+"/")
}
var retryCount = 0
var permissionsDeniedMessage = "Could not create %s. Permission denied. Make sure you have write access to plugindir"
func downloadFile(pluginName, filePath, url string) (err error) {
defer func() {
if r := recover(); r != nil {
retryCount++
if retryCount < 3 {
fmt.Println("Failed downloading. Will retry once.")
err = downloadFile(pluginName, filePath, url)
} else {
failure := fmt.Sprintf("%v", r)
if failure == "runtime error: makeslice: len out of range" {
err = fmt.Errorf("Corrupt http response from source. Please try again.\n")
} else {
panic(r)
}
}
}
}()
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
r, err := zip.NewReader(bytes.NewReader(body), resp.ContentLength)
if err != nil {
return err
}
for _, zf := range r.File {
newFile := path.Join(filePath, RemoveGitBuildFromName(pluginName, zf.Name))
if zf.FileInfo().IsDir() {
err := os.Mkdir(newFile, 0777)
if PermissionsError(err) {
return fmt.Errorf(permissionsDeniedMessage, newFile)
}
} else {
dst, err := os.Create(newFile)
if PermissionsError(err) {
return fmt.Errorf(permissionsDeniedMessage, newFile)
}
src, err := zf.Open()
if err != nil {
logger.Errorf("Failed to extract file: %v", err)
}
io.Copy(dst, src)
dst.Close()
src.Close()
}
}
return nil
}
func PermissionsError(err error) bool {
return err != nil && strings.Contains(err.Error(), "permission denied")
}
| pkg/cmd/grafana-cli/commands/install_command.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.0023044035769999027,
0.0003050345985684544,
0.00016436417354270816,
0.00016853748820722103,
0.0004790727107319981
]
|
{
"id": 11,
"code_window": [
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 660
} | package api
import (
"encoding/json"
"fmt"
"os"
"path"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/dashdiffs"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/metrics"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
func isDashboardStarredByUser(c *middleware.Context, dashId int64) (bool, error) {
if !c.IsSignedIn {
return false, nil
}
query := m.IsStarredByUserQuery{UserId: c.UserId, DashboardId: dashId}
if err := bus.Dispatch(&query); err != nil {
return false, err
}
return query.Result, nil
}
func dashboardGuardianResponse(err error) Response {
if err != nil {
return ApiError(500, "Error while checking dashboard permissions", err)
} else {
return ApiError(403, "Access denied to this dashboard", nil)
}
}
func GetDashboard(c *middleware.Context) Response {
dash, rsp := getDashboardHelper(c.OrgId, c.Params(":slug"), 0, c.Params(":uid"))
if rsp != nil {
return rsp
}
guardian := guardian.NewDashboardGuardian(dash.Id, c.OrgId, c.SignedInUser)
if canView, err := guardian.CanView(); err != nil || !canView {
fmt.Printf("%v", err)
return dashboardGuardianResponse(err)
}
canEdit, _ := guardian.CanEdit()
canSave, _ := guardian.CanSave()
canAdmin, _ := guardian.CanAdmin()
isStarred, err := isDashboardStarredByUser(c, dash.Id)
if err != nil {
return ApiError(500, "Error while checking if dashboard was starred by user", err)
}
// Finding creator and last updater of the dashboard
updater, creator := "Anonymous", "Anonymous"
if dash.UpdatedBy > 0 {
updater = getUserLogin(dash.UpdatedBy)
}
if dash.CreatedBy > 0 {
creator = getUserLogin(dash.CreatedBy)
}
meta := dtos.DashboardMeta{
IsStarred: isStarred,
Slug: dash.Slug,
Type: m.DashTypeDB,
CanStar: c.IsSignedIn,
CanSave: canSave,
CanEdit: canEdit,
CanAdmin: canAdmin,
Created: dash.Created,
Updated: dash.Updated,
UpdatedBy: updater,
CreatedBy: creator,
Version: dash.Version,
HasAcl: dash.HasAcl,
IsFolder: dash.IsFolder,
FolderId: dash.FolderId,
FolderTitle: "Root",
}
// lookup folder title
if dash.FolderId > 0 {
query := m.GetDashboardQuery{Id: dash.FolderId, OrgId: c.OrgId}
if err := bus.Dispatch(&query); err != nil {
return ApiError(500, "Dashboard folder could not be read", err)
}
meta.FolderTitle = query.Result.Title
}
if dash.IsFolder {
meta.Url = m.GetFolderUrl(dash.Uid, dash.Slug)
} else {
meta.Url = m.GetDashboardUrl(dash.Uid, dash.Slug)
}
// make sure db version is in sync with json model version
dash.Data.Set("version", dash.Version)
dto := dtos.DashboardFullWithMeta{
Dashboard: dash.Data,
Meta: meta,
}
c.TimeRequest(metrics.M_Api_Dashboard_Get)
return Json(200, dto)
}
func GetDashboardUidBySlug(c *middleware.Context) Response {
dash, rsp := getDashboardHelper(c.OrgId, c.Params(":slug"), 0, "")
if rsp != nil {
return rsp
}
guardian := guardian.NewDashboardGuardian(dash.Id, c.OrgId, c.SignedInUser)
if canView, err := guardian.CanView(); err != nil || !canView {
fmt.Printf("%v", err)
return dashboardGuardianResponse(err)
}
return Json(200, util.DynMap{"uid": dash.Uid})
}
func getUserLogin(userId int64) string {
query := m.GetUserByIdQuery{Id: userId}
err := bus.Dispatch(&query)
if err != nil {
return "Anonymous"
} else {
user := query.Result
return user.Login
}
}
func getDashboardHelper(orgId int64, slug string, id int64, uid string) (*m.Dashboard, Response) {
var query m.GetDashboardQuery
if len(uid) > 0 {
query = m.GetDashboardQuery{Uid: uid, Id: id, OrgId: orgId}
} else {
query = m.GetDashboardQuery{Slug: slug, Id: id, OrgId: orgId}
}
if err := bus.Dispatch(&query); err != nil {
return nil, ApiError(404, "Dashboard not found", err)
}
return query.Result, nil
}
func DeleteDashboard(c *middleware.Context) Response {
dash, rsp := getDashboardHelper(c.OrgId, c.Params(":slug"), 0, "")
if rsp != nil {
return rsp
}
guardian := guardian.NewDashboardGuardian(dash.Id, c.OrgId, c.SignedInUser)
if canSave, err := guardian.CanSave(); err != nil || !canSave {
return dashboardGuardianResponse(err)
}
cmd := m.DeleteDashboardCommand{OrgId: c.OrgId, Id: dash.Id}
if err := bus.Dispatch(&cmd); err != nil {
return ApiError(500, "Failed to delete dashboard", err)
}
var resp = map[string]interface{}{"title": dash.Title}
return Json(200, resp)
}
func PostDashboard(c *middleware.Context, cmd m.SaveDashboardCommand) Response {
cmd.OrgId = c.OrgId
cmd.UserId = c.UserId
dash := cmd.GetDashboardModel()
guardian := guardian.NewDashboardGuardian(dash.Id, c.OrgId, c.SignedInUser)
if canSave, err := guardian.CanSave(); err != nil || !canSave {
return dashboardGuardianResponse(err)
}
if dash.IsFolder && dash.FolderId > 0 {
return ApiError(400, m.ErrDashboardFolderCannotHaveParent.Error(), nil)
}
// Check if Title is empty
if dash.Title == "" {
return ApiError(400, m.ErrDashboardTitleEmpty.Error(), nil)
}
if dash.Id == 0 {
limitReached, err := middleware.QuotaReached(c, "dashboard")
if err != nil {
return ApiError(500, "failed to get quota", err)
}
if limitReached {
return ApiError(403, "Quota reached", nil)
}
}
dashItem := &dashboards.SaveDashboardItem{
Dashboard: dash,
Message: cmd.Message,
OrgId: c.OrgId,
UserId: c.UserId,
Overwrite: cmd.Overwrite,
}
dashboard, err := dashboards.GetRepository().SaveDashboard(dashItem)
if err == m.ErrDashboardTitleEmpty {
return ApiError(400, m.ErrDashboardTitleEmpty.Error(), nil)
}
if err == m.ErrDashboardContainsInvalidAlertData {
return ApiError(500, "Invalid alert data. Cannot save dashboard", err)
}
if err != nil {
if err == m.ErrDashboardWithSameNameExists {
return Json(412, util.DynMap{"status": "name-exists", "message": err.Error()})
}
if err == m.ErrDashboardVersionMismatch {
return Json(412, util.DynMap{"status": "version-mismatch", "message": err.Error()})
}
if pluginErr, ok := err.(m.UpdatePluginDashboardError); ok {
message := "The dashboard belongs to plugin " + pluginErr.PluginId + "."
// look up plugin name
if pluginDef, exist := plugins.Plugins[pluginErr.PluginId]; exist {
message = "The dashboard belongs to plugin " + pluginDef.Name + "."
}
return Json(412, util.DynMap{"status": "plugin-dashboard", "message": message})
}
if err == m.ErrDashboardNotFound {
return Json(404, util.DynMap{"status": "not-found", "message": err.Error()})
}
return ApiError(500, "Failed to save dashboard", err)
}
if err == m.ErrDashboardFailedToUpdateAlertData {
return ApiError(500, "Invalid alert data. Cannot save dashboard", err)
}
c.TimeRequest(metrics.M_Api_Dashboard_Save)
return Json(200, util.DynMap{"status": "success", "slug": dashboard.Slug, "version": dashboard.Version, "id": dashboard.Id, "uid": dashboard.Uid})
}
func GetHomeDashboard(c *middleware.Context) Response {
prefsQuery := m.GetPreferencesWithDefaultsQuery{OrgId: c.OrgId, UserId: c.UserId}
if err := bus.Dispatch(&prefsQuery); err != nil {
return ApiError(500, "Failed to get preferences", err)
}
if prefsQuery.Result.HomeDashboardId != 0 {
slugQuery := m.GetDashboardSlugByIdQuery{Id: prefsQuery.Result.HomeDashboardId}
err := bus.Dispatch(&slugQuery)
if err == nil {
dashRedirect := dtos.DashboardRedirect{RedirectUri: "db/" + slugQuery.Result}
return Json(200, &dashRedirect)
} else {
log.Warn("Failed to get slug from database, %s", err.Error())
}
}
filePath := path.Join(setting.StaticRootPath, "dashboards/home.json")
file, err := os.Open(filePath)
if err != nil {
return ApiError(500, "Failed to load home dashboard", err)
}
dash := dtos.DashboardFullWithMeta{}
dash.Meta.IsHome = true
dash.Meta.CanEdit = c.SignedInUser.HasRole(m.ROLE_EDITOR)
dash.Meta.FolderTitle = "Root"
jsonParser := json.NewDecoder(file)
if err := jsonParser.Decode(&dash.Dashboard); err != nil {
return ApiError(500, "Failed to load home dashboard", err)
}
if c.HasUserRole(m.ROLE_ADMIN) && !c.HasHelpFlag(m.HelpFlagGettingStartedPanelDismissed) {
addGettingStartedPanelToHomeDashboard(dash.Dashboard)
}
return Json(200, &dash)
}
func addGettingStartedPanelToHomeDashboard(dash *simplejson.Json) {
panels := dash.Get("panels").MustArray()
newpanel := simplejson.NewFromAny(map[string]interface{}{
"type": "gettingstarted",
"id": 123123,
"gridPos": map[string]interface{}{
"x": 0,
"y": 3,
"w": 24,
"h": 4,
},
})
panels = append(panels, newpanel)
dash.Set("panels", panels)
}
// GetDashboardVersions returns all dashboard versions as JSON
func GetDashboardVersions(c *middleware.Context) Response {
dashId := c.ParamsInt64(":dashboardId")
guardian := guardian.NewDashboardGuardian(dashId, c.OrgId, c.SignedInUser)
if canSave, err := guardian.CanSave(); err != nil || !canSave {
return dashboardGuardianResponse(err)
}
query := m.GetDashboardVersionsQuery{
OrgId: c.OrgId,
DashboardId: dashId,
Limit: c.QueryInt("limit"),
Start: c.QueryInt("start"),
}
if err := bus.Dispatch(&query); err != nil {
return ApiError(404, fmt.Sprintf("No versions found for dashboardId %d", dashId), err)
}
for _, version := range query.Result {
if version.RestoredFrom == version.Version {
version.Message = "Initial save (created by migration)"
continue
}
if version.RestoredFrom > 0 {
version.Message = fmt.Sprintf("Restored from version %d", version.RestoredFrom)
continue
}
if version.ParentVersion == 0 {
version.Message = "Initial save"
}
}
return Json(200, query.Result)
}
// GetDashboardVersion returns the dashboard version with the given ID.
func GetDashboardVersion(c *middleware.Context) Response {
dashId := c.ParamsInt64(":dashboardId")
guardian := guardian.NewDashboardGuardian(dashId, c.OrgId, c.SignedInUser)
if canSave, err := guardian.CanSave(); err != nil || !canSave {
return dashboardGuardianResponse(err)
}
query := m.GetDashboardVersionQuery{
OrgId: c.OrgId,
DashboardId: dashId,
Version: c.ParamsInt(":id"),
}
if err := bus.Dispatch(&query); err != nil {
return ApiError(500, fmt.Sprintf("Dashboard version %d not found for dashboardId %d", query.Version, dashId), err)
}
creator := "Anonymous"
if query.Result.CreatedBy > 0 {
creator = getUserLogin(query.Result.CreatedBy)
}
dashVersionMeta := &m.DashboardVersionMeta{
DashboardVersion: *query.Result,
CreatedBy: creator,
}
return Json(200, dashVersionMeta)
}
// POST /api/dashboards/calculate-diff performs diffs on two dashboards
func CalculateDashboardDiff(c *middleware.Context, apiOptions dtos.CalculateDiffOptions) Response {
options := dashdiffs.Options{
OrgId: c.OrgId,
DiffType: dashdiffs.ParseDiffType(apiOptions.DiffType),
Base: dashdiffs.DiffTarget{
DashboardId: apiOptions.Base.DashboardId,
Version: apiOptions.Base.Version,
UnsavedDashboard: apiOptions.Base.UnsavedDashboard,
},
New: dashdiffs.DiffTarget{
DashboardId: apiOptions.New.DashboardId,
Version: apiOptions.New.Version,
UnsavedDashboard: apiOptions.New.UnsavedDashboard,
},
}
result, err := dashdiffs.CalculateDiff(&options)
if err != nil {
if err == m.ErrDashboardVersionNotFound {
return ApiError(404, "Dashboard version not found", err)
}
return ApiError(500, "Unable to compute diff", err)
}
if options.DiffType == dashdiffs.DiffDelta {
return Respond(200, result.Delta).Header("Content-Type", "application/json")
} else {
return Respond(200, result.Delta).Header("Content-Type", "text/html")
}
}
// RestoreDashboardVersion restores a dashboard to the given version.
func RestoreDashboardVersion(c *middleware.Context, apiCmd dtos.RestoreDashboardVersionCommand) Response {
dash, rsp := getDashboardHelper(c.OrgId, "", c.ParamsInt64(":dashboardId"), "")
if rsp != nil {
return rsp
}
guardian := guardian.NewDashboardGuardian(dash.Id, c.OrgId, c.SignedInUser)
if canSave, err := guardian.CanSave(); err != nil || !canSave {
return dashboardGuardianResponse(err)
}
versionQuery := m.GetDashboardVersionQuery{DashboardId: dash.Id, Version: apiCmd.Version, OrgId: c.OrgId}
if err := bus.Dispatch(&versionQuery); err != nil {
return ApiError(404, "Dashboard version not found", nil)
}
version := versionQuery.Result
saveCmd := m.SaveDashboardCommand{}
saveCmd.RestoredFrom = version.Version
saveCmd.OrgId = c.OrgId
saveCmd.UserId = c.UserId
saveCmd.Dashboard = version.Data
saveCmd.Dashboard.Set("version", dash.Version)
saveCmd.Message = fmt.Sprintf("Restored from version %d", version.Version)
return PostDashboard(c, saveCmd)
}
func GetDashboardTags(c *middleware.Context) {
query := m.GetDashboardTagsQuery{OrgId: c.OrgId}
err := bus.Dispatch(&query)
if err != nil {
c.JsonApiErr(500, "Failed to get tags from database", err)
return
}
c.JSON(200, query.Result)
}
| pkg/api/dashboard.go | 1 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.007200016174465418,
0.0010908516123890877,
0.00016245702863670886,
0.00017545692389830947,
0.0018317324575036764
]
|
{
"id": 11,
"code_window": [
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 660
} | package sqlstore
import (
"strconv"
"strings"
"time"
"fmt"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/events"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
func init() {
bus.AddHandler("sql", CreateUser)
bus.AddHandler("sql", GetUserById)
bus.AddHandler("sql", UpdateUser)
bus.AddHandler("sql", ChangeUserPassword)
bus.AddHandler("sql", GetUserByLogin)
bus.AddHandler("sql", GetUserByEmail)
bus.AddHandler("sql", SetUsingOrg)
bus.AddHandler("sql", UpdateUserLastSeenAt)
bus.AddHandler("sql", GetUserProfile)
bus.AddHandler("sql", GetSignedInUser)
bus.AddHandler("sql", SearchUsers)
bus.AddHandler("sql", GetUserOrgList)
bus.AddHandler("sql", DeleteUser)
bus.AddHandler("sql", UpdateUserPermissions)
bus.AddHandler("sql", SetUserHelpFlag)
}
func getOrgIdForNewUser(cmd *m.CreateUserCommand, sess *DBSession) (int64, error) {
if cmd.SkipOrgSetup {
return -1, nil
}
var org m.Org
if setting.AutoAssignOrg {
// right now auto assign to org with id 1
has, err := sess.Where("id=?", 1).Get(&org)
if err != nil {
return 0, err
}
if has {
return org.Id, nil
} else {
org.Name = "Main Org."
org.Id = 1
}
} else {
org.Name = cmd.OrgName
if len(org.Name) == 0 {
org.Name = util.StringsFallback2(cmd.Email, cmd.Login)
}
}
org.Created = time.Now()
org.Updated = time.Now()
if _, err := sess.Insert(&org); err != nil {
return 0, err
}
sess.publishAfterCommit(&events.OrgCreated{
Timestamp: org.Created,
Id: org.Id,
Name: org.Name,
})
return org.Id, nil
}
func CreateUser(cmd *m.CreateUserCommand) error {
return inTransaction(func(sess *DBSession) error {
orgId, err := getOrgIdForNewUser(cmd, sess)
if err != nil {
return err
}
if cmd.Email == "" {
cmd.Email = cmd.Login
}
// create user
user := m.User{
Email: cmd.Email,
Name: cmd.Name,
Login: cmd.Login,
Company: cmd.Company,
IsAdmin: cmd.IsAdmin,
OrgId: orgId,
EmailVerified: cmd.EmailVerified,
Created: time.Now(),
Updated: time.Now(),
LastSeenAt: time.Now().AddDate(-10, 0, 0),
}
if len(cmd.Password) > 0 {
user.Salt = util.GetRandomString(10)
user.Rands = util.GetRandomString(10)
user.Password = util.EncodePassword(cmd.Password, user.Salt)
}
sess.UseBool("is_admin")
if _, err := sess.Insert(&user); err != nil {
return err
}
sess.publishAfterCommit(&events.UserCreated{
Timestamp: user.Created,
Id: user.Id,
Name: user.Name,
Login: user.Login,
Email: user.Email,
})
cmd.Result = user
// create org user link
if !cmd.SkipOrgSetup {
orgUser := m.OrgUser{
OrgId: orgId,
UserId: user.Id,
Role: m.ROLE_ADMIN,
Created: time.Now(),
Updated: time.Now(),
}
if setting.AutoAssignOrg && !user.IsAdmin {
if len(cmd.DefaultOrgRole) > 0 {
orgUser.Role = m.RoleType(cmd.DefaultOrgRole)
} else {
orgUser.Role = m.RoleType(setting.AutoAssignOrgRole)
}
}
if _, err = sess.Insert(&orgUser); err != nil {
return err
}
}
return nil
})
}
func GetUserById(query *m.GetUserByIdQuery) error {
user := new(m.User)
has, err := x.Id(query.Id).Get(user)
if err != nil {
return err
} else if has == false {
return m.ErrUserNotFound
}
query.Result = user
return nil
}
func GetUserByLogin(query *m.GetUserByLoginQuery) error {
if query.LoginOrEmail == "" {
return m.ErrUserNotFound
}
user := new(m.User)
// Try and find the user by login first.
// It's not sufficient to assume that a LoginOrEmail with an "@" is an email.
user = &m.User{Login: query.LoginOrEmail}
has, err := x.Get(user)
if err != nil {
return err
}
if has == false && strings.Contains(query.LoginOrEmail, "@") {
// If the user wasn't found, and it contains an "@" fallback to finding the
// user by email.
user = &m.User{Email: query.LoginOrEmail}
has, err = x.Get(user)
}
if err != nil {
return err
} else if has == false {
return m.ErrUserNotFound
}
query.Result = user
return nil
}
func GetUserByEmail(query *m.GetUserByEmailQuery) error {
if query.Email == "" {
return m.ErrUserNotFound
}
user := new(m.User)
user = &m.User{Email: query.Email}
has, err := x.Get(user)
if err != nil {
return err
} else if has == false {
return m.ErrUserNotFound
}
query.Result = user
return nil
}
func UpdateUser(cmd *m.UpdateUserCommand) error {
return inTransaction(func(sess *DBSession) error {
user := m.User{
Name: cmd.Name,
Email: cmd.Email,
Login: cmd.Login,
Theme: cmd.Theme,
Updated: time.Now(),
}
if _, err := sess.Id(cmd.UserId).Update(&user); err != nil {
return err
}
sess.publishAfterCommit(&events.UserUpdated{
Timestamp: user.Created,
Id: user.Id,
Name: user.Name,
Login: user.Login,
Email: user.Email,
})
return nil
})
}
func ChangeUserPassword(cmd *m.ChangeUserPasswordCommand) error {
return inTransaction(func(sess *DBSession) error {
user := m.User{
Password: cmd.NewPassword,
Updated: time.Now(),
}
if _, err := sess.Id(cmd.UserId).Update(&user); err != nil {
return err
}
return nil
})
}
func UpdateUserLastSeenAt(cmd *m.UpdateUserLastSeenAtCommand) error {
return inTransaction(func(sess *DBSession) error {
if cmd.UserId <= 0 {
}
user := m.User{
Id: cmd.UserId,
LastSeenAt: time.Now(),
}
if _, err := sess.Id(cmd.UserId).Update(&user); err != nil {
return err
}
return nil
})
}
func SetUsingOrg(cmd *m.SetUsingOrgCommand) error {
getOrgsForUserCmd := &m.GetUserOrgListQuery{UserId: cmd.UserId}
GetUserOrgList(getOrgsForUserCmd)
valid := false
for _, other := range getOrgsForUserCmd.Result {
if other.OrgId == cmd.OrgId {
valid = true
}
}
if !valid {
return fmt.Errorf("user does not belong to org")
}
return inTransaction(func(sess *DBSession) error {
user := m.User{}
sess.Id(cmd.UserId).Get(&user)
user.OrgId = cmd.OrgId
_, err := sess.Id(user.Id).Update(&user)
return err
})
}
func GetUserProfile(query *m.GetUserProfileQuery) error {
var user m.User
has, err := x.Id(query.UserId).Get(&user)
if err != nil {
return err
} else if has == false {
return m.ErrUserNotFound
}
query.Result = m.UserProfileDTO{
Name: user.Name,
Email: user.Email,
Login: user.Login,
Theme: user.Theme,
IsGrafanaAdmin: user.IsAdmin,
OrgId: user.OrgId,
}
return err
}
func GetUserOrgList(query *m.GetUserOrgListQuery) error {
query.Result = make([]*m.UserOrgDTO, 0)
sess := x.Table("org_user")
sess.Join("INNER", "org", "org_user.org_id=org.id")
sess.Where("org_user.user_id=?", query.UserId)
sess.Cols("org.name", "org_user.role", "org_user.org_id")
err := sess.Find(&query.Result)
return err
}
func GetSignedInUser(query *m.GetSignedInUserQuery) error {
orgId := "u.org_id"
if query.OrgId > 0 {
orgId = strconv.FormatInt(query.OrgId, 10)
}
var rawSql = `SELECT
u.id as user_id,
u.is_admin as is_grafana_admin,
u.email as email,
u.login as login,
u.name as name,
u.help_flags1 as help_flags1,
u.last_seen_at as last_seen_at,
(SELECT COUNT(*) FROM org_user where org_user.user_id = u.id) as org_count,
org.name as org_name,
org_user.role as org_role,
org.id as org_id
FROM ` + dialect.Quote("user") + ` as u
LEFT OUTER JOIN org_user on org_user.org_id = ` + orgId + ` and org_user.user_id = u.id
LEFT OUTER JOIN org on org.id = org_user.org_id `
sess := x.Table("user")
if query.UserId > 0 {
sess.Sql(rawSql+"WHERE u.id=?", query.UserId)
} else if query.Login != "" {
sess.Sql(rawSql+"WHERE u.login=?", query.Login)
} else if query.Email != "" {
sess.Sql(rawSql+"WHERE u.email=?", query.Email)
}
var user m.SignedInUser
has, err := sess.Get(&user)
if err != nil {
return err
} else if !has {
return m.ErrUserNotFound
}
if user.OrgRole == "" {
user.OrgId = -1
user.OrgName = "Org missing"
}
query.Result = &user
return err
}
func SearchUsers(query *m.SearchUsersQuery) error {
query.Result = m.SearchUserQueryResult{
Users: make([]*m.UserSearchHitDTO, 0),
}
queryWithWildcards := "%" + query.Query + "%"
whereConditions := make([]string, 0)
whereParams := make([]interface{}, 0)
sess := x.Table("user")
if query.OrgId > 0 {
whereConditions = append(whereConditions, "org_id = ?")
whereParams = append(whereParams, query.OrgId)
}
if query.Query != "" {
whereConditions = append(whereConditions, "(email "+dialect.LikeStr()+" ? OR name "+dialect.LikeStr()+" ? OR login "+dialect.LikeStr()+" ?)")
whereParams = append(whereParams, queryWithWildcards, queryWithWildcards, queryWithWildcards)
}
if len(whereConditions) > 0 {
sess.Where(strings.Join(whereConditions, " AND "), whereParams...)
}
offset := query.Limit * (query.Page - 1)
sess.Limit(query.Limit, offset)
sess.Cols("id", "email", "name", "login", "is_admin", "last_seen_at")
if err := sess.Find(&query.Result.Users); err != nil {
return err
}
// get total
user := m.User{}
countSess := x.Table("user")
if len(whereConditions) > 0 {
countSess.Where(strings.Join(whereConditions, " AND "), whereParams...)
}
count, err := countSess.Count(&user)
query.Result.TotalCount = count
for _, user := range query.Result.Users {
user.LastSeenAtAge = util.GetAgeString(user.LastSeenAt)
}
return err
}
func DeleteUser(cmd *m.DeleteUserCommand) error {
return inTransaction(func(sess *DBSession) error {
deletes := []string{
"DELETE FROM star WHERE user_id = ?",
"DELETE FROM " + dialect.Quote("user") + " WHERE id = ?",
"DELETE FROM org_user WHERE user_id = ?",
"DELETE FROM dashboard_acl WHERE user_id = ?",
"DELETE FROM preferences WHERE user_id = ?",
"DELETE FROM team_member WHERE user_id = ?",
}
for _, sql := range deletes {
_, err := sess.Exec(sql, cmd.UserId)
if err != nil {
return err
}
}
return nil
})
}
func UpdateUserPermissions(cmd *m.UpdateUserPermissionsCommand) error {
return inTransaction(func(sess *DBSession) error {
user := m.User{}
sess.Id(cmd.UserId).Get(&user)
user.IsAdmin = cmd.IsGrafanaAdmin
sess.UseBool("is_admin")
_, err := sess.Id(user.Id).Update(&user)
return err
})
}
func SetUserHelpFlag(cmd *m.SetUserHelpFlagCommand) error {
return inTransaction(func(sess *DBSession) error {
user := m.User{
Id: cmd.UserId,
HelpFlags1: cmd.HelpFlags1,
Updated: time.Now(),
}
if _, err := sess.Id(cmd.UserId).Cols("help_flags1").Update(&user); err != nil {
return err
}
return nil
})
}
| pkg/services/sqlstore/user.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.0013371699023991823,
0.00019585154950618744,
0.00016284568118862808,
0.00016931498248595744,
0.00016529037384316325
]
|
{
"id": 11,
"code_window": [
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 660
} | #!/bin/bash
export PYTHONPATH=/opt/graphite/webapp && exec /usr/local/bin/gunicorn wsgi --workers=4 --bind=127.0.0.1:8080 --log-file=/var/log/gunicorn.log --preload --pythonpath=/opt/graphite/webapp/graphite
| docker/blocks/graphite1/conf/etc/service/graphite/run | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017211389786098152,
0.00017211389786098152,
0.00017211389786098152,
0.00017211389786098152,
0
]
|
{
"id": 11,
"code_window": [
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling GET on\", \"GET\", \"/api/dashboards/db/child-dash/uid\", \"/api/dashboards/db/:slug/uid\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tuid := GetDashboardUidBySlugShouldReturn200(sc)\n",
"\n",
"\t\t\t\tConvey(\"Should return uid\", func() {\n",
"\t\t\t\t\tSo(uid, ShouldEqual, fakeDash.Uid)\n",
"\t\t\t\t})\n",
"\t\t\t})\n",
"\n",
"\t\t\tloggedInUserScenarioWithRole(\"When calling DELETE on\", \"DELETE\", \"/api/dashboards/db/child-dash\", \"/api/dashboards/db/:slug\", role, func(sc *scenarioContext) {\n",
"\t\t\t\tCallDeleteDashboard(sc)\n",
"\t\t\t\tSo(sc.resp.Code, ShouldEqual, 403)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 660
} | <?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 20.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="64px" height="64px" viewBox="0 0 64 64" style="enable-background:new 0 0 64 64;" xml:space="preserve">
<style type="text/css">
.st0{fill:#555555;}
.st1{fill:url(#SVGID_1_);}
</style>
<g>
<path class="st0" d="M36.4,38.5h4.1v-4.1c0-1.7,0.8-3.2,2.1-4.2V17.9l-6.5,6.5v9c0,0.9-0.8,1.7-1.7,1.7h-7v4.2L23,35.1H8.2
c-0.9,0-1.7-0.7-1.7-1.7V14c0-0.9,0.8-1.7,1.7-1.7h23.2l6.5-6.5H8.2C3.7,5.8,0,9.4,0,14v19.4c0,4.5,3.7,8.2,8.2,8.2h12.2l10.6,10
v-7.8C31,40.9,33.4,38.5,36.4,38.5z"/>
<rect x="24.6" y="13.1" transform="matrix(0.7071 -0.7071 0.7071 0.7071 -1.2013 29.9904)" class="st0" width="22" height="6.7"/>
<path class="st0" d="M47.6,9.2L47.8,9l1.3-1.3c1.3-1.3,1.3-3.4,0-4.7s-3.4-1.3-4.7,0l-1.3,1.3l-0.2,0.2L42,5.3l4.7,4.7L47.6,9.2z"
/>
<polygon class="st0" points="24.2,24.3 24.1,24.7 23.5,28.5 27.3,27.9 27.7,27.8 29.2,27.6 24.5,22.9 "/>
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="49.6596" y1="-15.1627" x2="49.6596" y2="45.3912" gradientTransform="matrix(1 0 0 -1 0 66)">
<stop offset="0" style="stop-color:#FFF23A"/>
<stop offset="4.010540e-02" style="stop-color:#FEE62D"/>
<stop offset="0.1171" style="stop-color:#FED41A"/>
<stop offset="0.1964" style="stop-color:#FDC90F"/>
<stop offset="0.2809" style="stop-color:#FDC60B"/>
<stop offset="0.6685" style="stop-color:#F28F3F"/>
<stop offset="0.8876" style="stop-color:#ED693C"/>
<stop offset="1" style="stop-color:#E83E39"/>
</linearGradient>
<path class="st1" d="M63.2,43.1h-4.8H58h-3.6v-8.7c0-0.4-0.3-0.8-0.8-0.8h-7.9c-0.4,0-0.8,0.3-0.8,0.8v8.7h-8.7
c-0.4,0-0.8,0.3-0.8,0.8v7.9c0,0.4,0.3,0.8,0.8,0.8h8.7v3v1.2v4.4c0,0.4,0.3,0.8,0.8,0.8h7.9c0.4,0,0.8-0.3,0.8-0.8v-8.7h8.7
c0.4,0,0.8-0.3,0.8-0.8v-7.9C64,43.4,63.7,43.1,63.2,43.1z"/>
</g>
</svg>
| public/img/icons_light_theme/icon_add_annotation_alt.svg | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017424070392735302,
0.00017173106607515365,
0.0001696562976576388,
0.00017151364590972662,
0.000001923639047163306
]
|
{
"id": 12,
"code_window": [
"\n",
"\treturn dash\n",
"}\n",
"\n",
"func GetDashboardUidBySlugShouldReturn200(sc *scenarioContext) string {\n",
"\tCallGetDashboardUidBySlug(sc)\n",
"\n",
"\tSo(sc.resp.Code, ShouldEqual, 200)\n",
"\n",
"\tresult := sc.ToJson()\n",
"\treturn result.Get(\"uid\").MustString()\n",
"}\n",
"\n",
"func CallGetDashboardUidBySlug(sc *scenarioContext) {\n",
"\tsc.handlerFunc = GetDashboardUidBySlug\n",
"\tsc.fakeReqWithParams(\"GET\", sc.url, map[string]string{}).exec()\n",
"}\n",
"\n",
"func CallGetDashboardVersion(sc *scenarioContext) {\n",
"\tbus.AddHandler(\"test\", func(query *m.GetDashboardVersionQuery) error {\n",
"\t\tquery.Result = &m.DashboardVersion{}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 708
} | package api
import (
"encoding/json"
"path/filepath"
"testing"
macaron "gopkg.in/macaron.v1"
"github.com/go-macaron/session"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
type fakeDashboardRepo struct {
inserted []*dashboards.SaveDashboardItem
getDashboard []*m.Dashboard
}
func (repo *fakeDashboardRepo) SaveDashboard(json *dashboards.SaveDashboardItem) (*m.Dashboard, error) {
repo.inserted = append(repo.inserted, json)
return json.Dashboard, nil
}
var fakeRepo *fakeDashboardRepo
func TestDashboardApiEndpoint(t *testing.T) {
Convey("Given a dashboard with a parent folder which does not have an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = false
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
viewerRole := m.ROLE_VIEWER
editorRole := m.ROLE_EDITOR
aclMockResp := []*m.DashboardAclInfoDTO{
{Role: &viewerRole, Permission: m.PERMISSION_VIEW},
{Role: &editorRole, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
"id": fakeDash.Id,
}),
}
Convey("When user is an Org Viewer", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
Convey("When saving a dashboard folder in another folder", func() {
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
query.Result.IsFolder = true
return nil
})
invalidCmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
IsFolder: true,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("Should return an error", func() {
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, invalidCmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 400)
})
})
})
})
})
Convey("Given a dashboard with a parent folder which has an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = true
setting.ViewersCanEdit = false
aclMockResp := []*m.DashboardAclInfoDTO{
{
DashboardId: 1,
Permission: m.PERMISSION_EDIT,
UserId: 200,
},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"id": fakeDash.Id,
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("When user is an Org Viewer and has no permissions for this dashboard", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor and has no permissions for this dashboard", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Viewer but has an edit permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Viewer and viewers can edit", func() {
role := m.ROLE_VIEWER
setting.ViewersCanEdit = true
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
})
Convey("When user is an Org Viewer but has an admin permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_ADMIN},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Editor but has a view permission", func() {
role := m.ROLE_EDITOR
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
})
}
func GetDashboardShouldReturn200(sc *scenarioContext) dtos.DashboardFullWithMeta {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
So(sc.resp.Code, ShouldEqual, 200)
dash := dtos.DashboardFullWithMeta{}
err := json.NewDecoder(sc.resp.Body).Decode(&dash)
So(err, ShouldBeNil)
return dash
}
func GetDashboardUidBySlugShouldReturn200(sc *scenarioContext) string {
CallGetDashboardUidBySlug(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
return result.Get("uid").MustString()
}
func CallGetDashboardUidBySlug(sc *scenarioContext) {
sc.handlerFunc = GetDashboardUidBySlug
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersion(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error {
query.Result = &m.DashboardVersion{}
return nil
})
sc.handlerFunc = GetDashboardVersion
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersions(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionsQuery) error {
query.Result = []*m.DashboardVersionDTO{}
return nil
})
sc.handlerFunc = GetDashboardVersions
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallDeleteDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error {
return nil
})
sc.handlerFunc = DeleteDashboard
sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec()
}
func CallPostDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *alerting.ValidateDashboardAlertsCommand) error {
return nil
})
bus.AddHandler("test", func(cmd *m.SaveDashboardCommand) error {
cmd.Result = &m.Dashboard{Id: 2, Slug: "Dash", Version: 2}
return nil
})
bus.AddHandler("test", func(cmd *alerting.UpdateDashboardAlertsCommand) error {
return nil
})
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec()
}
func postDashboardScenario(desc string, url string, routePattern string, role m.RoleType, cmd m.SaveDashboardCommand, fn scenarioFunc) {
Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers()
sc := &scenarioContext{
url: url,
}
viewsPath, _ := filepath.Abs("../../public/views")
sc.m = macaron.New()
sc.m.Use(macaron.Renderer(macaron.RenderOptions{
Directory: viewsPath,
Delims: macaron.Delims{Left: "[[", Right: "]]"},
}))
sc.m.Use(middleware.GetContextHandler())
sc.m.Use(middleware.Sessioner(&session.Options{}))
sc.defaultHandler = wrap(func(c *middleware.Context) Response {
sc.context = c
sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID
sc.context.OrgRole = role
return PostDashboard(c, cmd)
})
fakeRepo = &fakeDashboardRepo{}
dashboards.SetRepository(fakeRepo)
sc.m.Post(routePattern, sc.defaultHandler)
fn(sc)
})
}
func (sc *scenarioContext) ToJson() *simplejson.Json {
var result *simplejson.Json
err := json.NewDecoder(sc.resp.Body).Decode(&result)
So(err, ShouldBeNil)
return result
}
| pkg/api/dashboard_test.go | 1 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.99864262342453,
0.22722074389457703,
0.0001645208103582263,
0.008939545601606369,
0.4042881727218628
]
|
{
"id": 12,
"code_window": [
"\n",
"\treturn dash\n",
"}\n",
"\n",
"func GetDashboardUidBySlugShouldReturn200(sc *scenarioContext) string {\n",
"\tCallGetDashboardUidBySlug(sc)\n",
"\n",
"\tSo(sc.resp.Code, ShouldEqual, 200)\n",
"\n",
"\tresult := sc.ToJson()\n",
"\treturn result.Get(\"uid\").MustString()\n",
"}\n",
"\n",
"func CallGetDashboardUidBySlug(sc *scenarioContext) {\n",
"\tsc.handlerFunc = GetDashboardUidBySlug\n",
"\tsc.fakeReqWithParams(\"GET\", sc.url, map[string]string{}).exec()\n",
"}\n",
"\n",
"func CallGetDashboardVersion(sc *scenarioContext) {\n",
"\tbus.AddHandler(\"test\", func(query *m.GetDashboardVersionQuery) error {\n",
"\t\tquery.Result = &m.DashboardVersion{}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 708
} | // +build go1.7
package pq
import "crypto/tls"
// Accept renegotiation requests initiated by the backend.
//
// Renegotiation was deprecated then removed from PostgreSQL 9.5, but
// the default configuration of older versions has it enabled. Redshift
// also initiates renegotiations and cannot be reconfigured.
func sslRenegotiation(conf *tls.Config) {
conf.Renegotiation = tls.RenegotiateFreelyAsClient
}
| vendor/github.com/lib/pq/ssl_go1.7.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00016617373330518603,
0.0001656008535064757,
0.00016502798825968057,
0.0001656008535064757,
5.72872522752732e-7
]
|
{
"id": 12,
"code_window": [
"\n",
"\treturn dash\n",
"}\n",
"\n",
"func GetDashboardUidBySlugShouldReturn200(sc *scenarioContext) string {\n",
"\tCallGetDashboardUidBySlug(sc)\n",
"\n",
"\tSo(sc.resp.Code, ShouldEqual, 200)\n",
"\n",
"\tresult := sc.ToJson()\n",
"\treturn result.Get(\"uid\").MustString()\n",
"}\n",
"\n",
"func CallGetDashboardUidBySlug(sc *scenarioContext) {\n",
"\tsc.handlerFunc = GetDashboardUidBySlug\n",
"\tsc.fakeReqWithParams(\"GET\", sc.url, map[string]string{}).exec()\n",
"}\n",
"\n",
"func CallGetDashboardVersion(sc *scenarioContext) {\n",
"\tbus.AddHandler(\"test\", func(query *m.GetDashboardVersionQuery) error {\n",
"\t\tquery.Result = &m.DashboardVersion{}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 708
} | # This is the official list of people who can contribute
# (and typically have contributed) code to the Snappy-Go repository.
# The AUTHORS file lists the copyright holders; this file
# lists people. For example, Google employees are listed here
# but not in AUTHORS, because Google holds the copyright.
#
# The submission process automatically checks to make sure
# that people submitting code are listed in this file (by email address).
#
# Names should be added to this file only after verifying that
# the individual or the individual's organization has agreed to
# the appropriate Contributor License Agreement, found here:
#
# http://code.google.com/legal/individual-cla-v1.0.html
# http://code.google.com/legal/corporate-cla-v1.0.html
#
# The agreement for individuals can be filled out on the web.
#
# When adding J Random Contributor's name to this file,
# either J's name or J's organization's name should be
# added to the AUTHORS file, depending on whether the
# individual or corporate CLA was used.
# Names should be added to this file like so:
# Name <email address>
# Please keep the list sorted.
Damian Gryski <[email protected]>
Jan Mercl <[email protected]>
Kai Backman <[email protected]>
Marc-Antoine Ruel <[email protected]>
Nigel Tao <[email protected]>
Rob Pike <[email protected]>
Rodolfo Carvalho <[email protected]>
Russ Cox <[email protected]>
Sebastien Binet <[email protected]>
| vendor/github.com/klauspost/compress/snappy/CONTRIBUTORS | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00017256432329304516,
0.0001706732000457123,
0.0001689013879513368,
0.00017061355174519122,
0.0000017139614101324696
]
|
{
"id": 12,
"code_window": [
"\n",
"\treturn dash\n",
"}\n",
"\n",
"func GetDashboardUidBySlugShouldReturn200(sc *scenarioContext) string {\n",
"\tCallGetDashboardUidBySlug(sc)\n",
"\n",
"\tSo(sc.resp.Code, ShouldEqual, 200)\n",
"\n",
"\tresult := sc.ToJson()\n",
"\treturn result.Get(\"uid\").MustString()\n",
"}\n",
"\n",
"func CallGetDashboardUidBySlug(sc *scenarioContext) {\n",
"\tsc.handlerFunc = GetDashboardUidBySlug\n",
"\tsc.fakeReqWithParams(\"GET\", sc.url, map[string]string{}).exec()\n",
"}\n",
"\n",
"func CallGetDashboardVersion(sc *scenarioContext) {\n",
"\tbus.AddHandler(\"test\", func(query *m.GetDashboardVersionQuery) error {\n",
"\t\tquery.Result = &m.DashboardVersion{}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/dashboard_test.go",
"type": "replace",
"edit_start_line_idx": 708
} | // Copyright 2015 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xorm
import (
"bufio"
"bytes"
"database/sql"
"encoding/gob"
"errors"
"fmt"
"io"
"os"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/go-xorm/core"
)
// Engine is the major struct of xorm, it means a database manager.
// Commonly, an application only need one engine
type Engine struct {
db *core.DB
dialect core.Dialect
ColumnMapper core.IMapper
TableMapper core.IMapper
TagIdentifier string
Tables map[reflect.Type]*core.Table
mutex *sync.RWMutex
Cacher core.Cacher
showSQL bool
showExecTime bool
logger core.ILogger
TZLocation *time.Location
DatabaseTZ *time.Location // The timezone of the database
disableGlobalCache bool
tagHandlers map[string]tagHandler
}
// ShowSQL show SQL statement or not on logger if log level is great than INFO
func (engine *Engine) ShowSQL(show ...bool) {
engine.logger.ShowSQL(show...)
if len(show) == 0 {
engine.showSQL = true
} else {
engine.showSQL = show[0]
}
}
// ShowExecTime show SQL statement and execute time or not on logger if log level is great than INFO
func (engine *Engine) ShowExecTime(show ...bool) {
if len(show) == 0 {
engine.showExecTime = true
} else {
engine.showExecTime = show[0]
}
}
// Logger return the logger interface
func (engine *Engine) Logger() core.ILogger {
return engine.logger
}
// SetLogger set the new logger
func (engine *Engine) SetLogger(logger core.ILogger) {
engine.logger = logger
engine.dialect.SetLogger(logger)
}
// SetDisableGlobalCache disable global cache or not
func (engine *Engine) SetDisableGlobalCache(disable bool) {
if engine.disableGlobalCache != disable {
engine.disableGlobalCache = disable
}
}
// DriverName return the current sql driver's name
func (engine *Engine) DriverName() string {
return engine.dialect.DriverName()
}
// DataSourceName return the current connection string
func (engine *Engine) DataSourceName() string {
return engine.dialect.DataSourceName()
}
// SetMapper set the name mapping rules
func (engine *Engine) SetMapper(mapper core.IMapper) {
engine.SetTableMapper(mapper)
engine.SetColumnMapper(mapper)
}
// SetTableMapper set the table name mapping rule
func (engine *Engine) SetTableMapper(mapper core.IMapper) {
engine.TableMapper = mapper
}
// SetColumnMapper set the column name mapping rule
func (engine *Engine) SetColumnMapper(mapper core.IMapper) {
engine.ColumnMapper = mapper
}
// SupportInsertMany If engine's database support batch insert records like
// "insert into user values (name, age), (name, age)".
// When the return is ture, then engine.Insert(&users) will
// generate batch sql and exeute.
func (engine *Engine) SupportInsertMany() bool {
return engine.dialect.SupportInsertMany()
}
// QuoteStr Engine's database use which character as quote.
// mysql, sqlite use ` and postgres use "
func (engine *Engine) QuoteStr() string {
return engine.dialect.QuoteStr()
}
// Quote Use QuoteStr quote the string sql
func (engine *Engine) Quote(value string) string {
value = strings.TrimSpace(value)
if len(value) == 0 {
return value
}
if string(value[0]) == engine.dialect.QuoteStr() || value[0] == '`' {
return value
}
value = strings.Replace(value, ".", engine.dialect.QuoteStr()+"."+engine.dialect.QuoteStr(), -1)
return engine.dialect.QuoteStr() + value + engine.dialect.QuoteStr()
}
// QuoteTo quotes string and writes into the buffer
func (engine *Engine) QuoteTo(buf *bytes.Buffer, value string) {
if buf == nil {
return
}
value = strings.TrimSpace(value)
if value == "" {
return
}
if string(value[0]) == engine.dialect.QuoteStr() || value[0] == '`' {
buf.WriteString(value)
return
}
value = strings.Replace(value, ".", engine.dialect.QuoteStr()+"."+engine.dialect.QuoteStr(), -1)
buf.WriteString(engine.dialect.QuoteStr())
buf.WriteString(value)
buf.WriteString(engine.dialect.QuoteStr())
}
func (engine *Engine) quote(sql string) string {
return engine.dialect.QuoteStr() + sql + engine.dialect.QuoteStr()
}
// SqlType will be depracated, please use SQLType instead
//
// Deprecated: use SQLType instead
func (engine *Engine) SqlType(c *core.Column) string {
return engine.SQLType(c)
}
// SQLType A simple wrapper to dialect's core.SqlType method
func (engine *Engine) SQLType(c *core.Column) string {
return engine.dialect.SqlType(c)
}
// AutoIncrStr Database's autoincrement statement
func (engine *Engine) AutoIncrStr() string {
return engine.dialect.AutoIncrStr()
}
// SetMaxOpenConns is only available for go 1.2+
func (engine *Engine) SetMaxOpenConns(conns int) {
engine.db.SetMaxOpenConns(conns)
}
// SetMaxIdleConns set the max idle connections on pool, default is 2
func (engine *Engine) SetMaxIdleConns(conns int) {
engine.db.SetMaxIdleConns(conns)
}
// SetDefaultCacher set the default cacher. Xorm's default not enable cacher.
func (engine *Engine) SetDefaultCacher(cacher core.Cacher) {
engine.Cacher = cacher
}
// NoCache If you has set default cacher, and you want temporilly stop use cache,
// you can use NoCache()
func (engine *Engine) NoCache() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.NoCache()
}
// NoCascade If you do not want to auto cascade load object
func (engine *Engine) NoCascade() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.NoCascade()
}
// MapCacher Set a table use a special cacher
func (engine *Engine) MapCacher(bean interface{}, cacher core.Cacher) {
v := rValue(bean)
tb := engine.autoMapType(v)
tb.Cacher = cacher
}
// NewDB provides an interface to operate database directly
func (engine *Engine) NewDB() (*core.DB, error) {
return core.OpenDialect(engine.dialect)
}
// DB return the wrapper of sql.DB
func (engine *Engine) DB() *core.DB {
return engine.db
}
// Dialect return database dialect
func (engine *Engine) Dialect() core.Dialect {
return engine.dialect
}
// NewSession New a session
func (engine *Engine) NewSession() *Session {
session := &Session{Engine: engine}
session.Init()
return session
}
// Close the engine
func (engine *Engine) Close() error {
return engine.db.Close()
}
// Ping tests if database is alive
func (engine *Engine) Ping() error {
session := engine.NewSession()
defer session.Close()
engine.logger.Infof("PING DATABASE %v", engine.DriverName())
return session.Ping()
}
// logging sql
func (engine *Engine) logSQL(sqlStr string, sqlArgs ...interface{}) {
if engine.showSQL && !engine.showExecTime {
if len(sqlArgs) > 0 {
engine.logger.Infof("[SQL] %v %v", sqlStr, sqlArgs)
} else {
engine.logger.Infof("[SQL] %v", sqlStr)
}
}
}
func (engine *Engine) logSQLQueryTime(sqlStr string, args []interface{}, executionBlock func() (*core.Stmt, *core.Rows, error)) (*core.Stmt, *core.Rows, error) {
if engine.showSQL && engine.showExecTime {
b4ExecTime := time.Now()
stmt, res, err := executionBlock()
execDuration := time.Since(b4ExecTime)
if len(args) > 0 {
engine.logger.Infof("[SQL] %s %v - took: %v", sqlStr, args, execDuration)
} else {
engine.logger.Infof("[SQL] %s - took: %v", sqlStr, execDuration)
}
return stmt, res, err
}
return executionBlock()
}
func (engine *Engine) logSQLExecutionTime(sqlStr string, args []interface{}, executionBlock func() (sql.Result, error)) (sql.Result, error) {
if engine.showSQL && engine.showExecTime {
b4ExecTime := time.Now()
res, err := executionBlock()
execDuration := time.Since(b4ExecTime)
if len(args) > 0 {
engine.logger.Infof("[sql] %s [args] %v - took: %v", sqlStr, args, execDuration)
} else {
engine.logger.Infof("[sql] %s - took: %v", sqlStr, execDuration)
}
return res, err
}
return executionBlock()
}
// Sql provides raw sql input parameter. When you have a complex SQL statement
// and cannot use Where, Id, In and etc. Methods to describe, you can use SQL.
//
// Deprecated: use SQL instead.
func (engine *Engine) Sql(querystring string, args ...interface{}) *Session {
return engine.SQL(querystring, args...)
}
// SQL method let's you manually write raw SQL and operate
// For example:
//
// engine.SQL("select * from user").Find(&users)
//
// This code will execute "select * from user" and set the records to users
func (engine *Engine) SQL(query interface{}, args ...interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.SQL(query, args...)
}
// NoAutoTime Default if your struct has "created" or "updated" filed tag, the fields
// will automatically be filled with current time when Insert or Update
// invoked. Call NoAutoTime if you dont' want to fill automatically.
func (engine *Engine) NoAutoTime() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.NoAutoTime()
}
// NoAutoCondition disable auto generate Where condition from bean or not
func (engine *Engine) NoAutoCondition(no ...bool) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.NoAutoCondition(no...)
}
// DBMetas Retrieve all tables, columns, indexes' informations from database.
func (engine *Engine) DBMetas() ([]*core.Table, error) {
tables, err := engine.dialect.GetTables()
if err != nil {
return nil, err
}
for _, table := range tables {
colSeq, cols, err := engine.dialect.GetColumns(table.Name)
if err != nil {
return nil, err
}
for _, name := range colSeq {
table.AddColumn(cols[name])
}
indexes, err := engine.dialect.GetIndexes(table.Name)
if err != nil {
return nil, err
}
table.Indexes = indexes
for _, index := range indexes {
for _, name := range index.Cols {
if col := table.GetColumn(name); col != nil {
col.Indexes[index.Name] = index.Type
} else {
return nil, fmt.Errorf("Unknown col %s in index %v of table %v, columns %v", name, index.Name, table.Name, table.ColumnsSeq())
}
}
}
}
return tables, nil
}
// DumpAllToFile dump database all table structs and data to a file
func (engine *Engine) DumpAllToFile(fp string, tp ...core.DbType) error {
f, err := os.Create(fp)
if err != nil {
return err
}
defer f.Close()
return engine.DumpAll(f, tp...)
}
// DumpAll dump database all table structs and data to w
func (engine *Engine) DumpAll(w io.Writer, tp ...core.DbType) error {
tables, err := engine.DBMetas()
if err != nil {
return err
}
return engine.DumpTables(tables, w, tp...)
}
// DumpTablesToFile dump specified tables to SQL file.
func (engine *Engine) DumpTablesToFile(tables []*core.Table, fp string, tp ...core.DbType) error {
f, err := os.Create(fp)
if err != nil {
return err
}
defer f.Close()
return engine.DumpTables(tables, f, tp...)
}
// DumpTables dump specify tables to io.Writer
func (engine *Engine) DumpTables(tables []*core.Table, w io.Writer, tp ...core.DbType) error {
return engine.dumpTables(tables, w, tp...)
}
// dumpTables dump database all table structs and data to w with specify db type
func (engine *Engine) dumpTables(tables []*core.Table, w io.Writer, tp ...core.DbType) error {
var dialect core.Dialect
var distDBName string
if len(tp) == 0 {
dialect = engine.dialect
distDBName = string(engine.dialect.DBType())
} else {
dialect = core.QueryDialect(tp[0])
if dialect == nil {
return errors.New("Unsupported database type")
}
dialect.Init(nil, engine.dialect.URI(), "", "")
distDBName = string(tp[0])
}
_, err := io.WriteString(w, fmt.Sprintf("/*Generated by xorm v%s %s, from %s to %s*/\n\n",
Version, time.Now().In(engine.TZLocation).Format("2006-01-02 15:04:05"), engine.dialect.DBType(), strings.ToUpper(distDBName)))
if err != nil {
return err
}
for i, table := range tables {
if i > 0 {
_, err = io.WriteString(w, "\n")
if err != nil {
return err
}
}
_, err = io.WriteString(w, dialect.CreateTableSql(table, "", table.StoreEngine, "")+";\n")
if err != nil {
return err
}
for _, index := range table.Indexes {
_, err = io.WriteString(w, dialect.CreateIndexSql(table.Name, index)+";\n")
if err != nil {
return err
}
}
cols := table.ColumnsSeq()
colNames := dialect.Quote(strings.Join(cols, dialect.Quote(", ")))
rows, err := engine.DB().Query("SELECT " + colNames + " FROM " + engine.Quote(table.Name))
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
dest := make([]interface{}, len(cols))
err = rows.ScanSlice(&dest)
if err != nil {
return err
}
_, err = io.WriteString(w, "INSERT INTO "+dialect.Quote(table.Name)+" ("+colNames+") VALUES (")
if err != nil {
return err
}
var temp string
for i, d := range dest {
col := table.GetColumn(cols[i])
if col == nil {
return errors.New("unknow column error")
}
if d == nil {
temp += ", NULL"
} else if col.SQLType.IsText() || col.SQLType.IsTime() {
var v = fmt.Sprintf("%s", d)
if strings.HasSuffix(v, " +0000 UTC") {
temp += fmt.Sprintf(", '%s'", v[0:len(v)-len(" +0000 UTC")])
} else {
temp += ", '" + strings.Replace(v, "'", "''", -1) + "'"
}
} else if col.SQLType.IsBlob() {
if reflect.TypeOf(d).Kind() == reflect.Slice {
temp += fmt.Sprintf(", %s", dialect.FormatBytes(d.([]byte)))
} else if reflect.TypeOf(d).Kind() == reflect.String {
temp += fmt.Sprintf(", '%s'", d.(string))
}
} else if col.SQLType.IsNumeric() {
switch reflect.TypeOf(d).Kind() {
case reflect.Slice:
temp += fmt.Sprintf(", %s", string(d.([]byte)))
case reflect.Int16, reflect.Int8, reflect.Int32, reflect.Int64, reflect.Int:
if col.SQLType.Name == core.Bool {
temp += fmt.Sprintf(", %v", strconv.FormatBool(reflect.ValueOf(d).Int() > 0))
} else {
temp += fmt.Sprintf(", %v", d)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if col.SQLType.Name == core.Bool {
temp += fmt.Sprintf(", %v", strconv.FormatBool(reflect.ValueOf(d).Uint() > 0))
} else {
temp += fmt.Sprintf(", %v", d)
}
default:
temp += fmt.Sprintf(", %v", d)
}
} else {
s := fmt.Sprintf("%v", d)
if strings.Contains(s, ":") || strings.Contains(s, "-") {
if strings.HasSuffix(s, " +0000 UTC") {
temp += fmt.Sprintf(", '%s'", s[0:len(s)-len(" +0000 UTC")])
} else {
temp += fmt.Sprintf(", '%s'", s)
}
} else {
temp += fmt.Sprintf(", %s", s)
}
}
}
_, err = io.WriteString(w, temp[2:]+");\n")
if err != nil {
return err
}
}
// FIXME: Hack for postgres
if string(dialect.DBType()) == core.POSTGRES && table.AutoIncrColumn() != nil {
_, err = io.WriteString(w, "SELECT setval('table_id_seq', COALESCE((SELECT MAX("+table.AutoIncrColumn().Name+") FROM "+dialect.Quote(table.Name)+"), 1), false);\n")
if err != nil {
return err
}
}
}
return nil
}
func (engine *Engine) tableName(beanOrTableName interface{}) (string, error) {
v := rValue(beanOrTableName)
if v.Type().Kind() == reflect.String {
return beanOrTableName.(string), nil
} else if v.Type().Kind() == reflect.Struct {
return engine.tbName(v), nil
}
return "", errors.New("bean should be a struct or struct's point")
}
func (engine *Engine) tbName(v reflect.Value) string {
if tb, ok := v.Interface().(TableName); ok {
return tb.TableName()
}
if v.Type().Kind() == reflect.Ptr {
if tb, ok := reflect.Indirect(v).Interface().(TableName); ok {
return tb.TableName()
}
} else if v.CanAddr() {
if tb, ok := v.Addr().Interface().(TableName); ok {
return tb.TableName()
}
}
return engine.TableMapper.Obj2Table(reflect.Indirect(v).Type().Name())
}
// Cascade use cascade or not
func (engine *Engine) Cascade(trueOrFalse ...bool) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Cascade(trueOrFalse...)
}
// Where method provide a condition query
func (engine *Engine) Where(query interface{}, args ...interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Where(query, args...)
}
// Id will be depracated, please use ID instead
func (engine *Engine) Id(id interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Id(id)
}
// ID method provoide a condition as (id) = ?
func (engine *Engine) ID(id interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.ID(id)
}
// Before apply before Processor, affected bean is passed to closure arg
func (engine *Engine) Before(closures func(interface{})) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Before(closures)
}
// After apply after insert Processor, affected bean is passed to closure arg
func (engine *Engine) After(closures func(interface{})) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.After(closures)
}
// Charset set charset when create table, only support mysql now
func (engine *Engine) Charset(charset string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Charset(charset)
}
// StoreEngine set store engine when create table, only support mysql now
func (engine *Engine) StoreEngine(storeEngine string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.StoreEngine(storeEngine)
}
// Distinct use for distinct columns. Caution: when you are using cache,
// distinct will not be cached because cache system need id,
// but distinct will not provide id
func (engine *Engine) Distinct(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Distinct(columns...)
}
// Select customerize your select columns or contents
func (engine *Engine) Select(str string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Select(str)
}
// Cols only use the parameters as select or update columns
func (engine *Engine) Cols(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Cols(columns...)
}
// AllCols indicates that all columns should be use
func (engine *Engine) AllCols() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.AllCols()
}
// MustCols specify some columns must use even if they are empty
func (engine *Engine) MustCols(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.MustCols(columns...)
}
// UseBool xorm automatically retrieve condition according struct, but
// if struct has bool field, it will ignore them. So use UseBool
// to tell system to do not ignore them.
// If no parameters, it will use all the bool field of struct, or
// it will use parameters's columns
func (engine *Engine) UseBool(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.UseBool(columns...)
}
// Omit only not use the parameters as select or update columns
func (engine *Engine) Omit(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Omit(columns...)
}
// Nullable set null when column is zero-value and nullable for update
func (engine *Engine) Nullable(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Nullable(columns...)
}
// In will generate "column IN (?, ?)"
func (engine *Engine) In(column string, args ...interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.In(column, args...)
}
// Incr provides a update string like "column = column + ?"
func (engine *Engine) Incr(column string, arg ...interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Incr(column, arg...)
}
// Decr provides a update string like "column = column - ?"
func (engine *Engine) Decr(column string, arg ...interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Decr(column, arg...)
}
// SetExpr provides a update string like "column = {expression}"
func (engine *Engine) SetExpr(column string, expression string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.SetExpr(column, expression)
}
// Table temporarily change the Get, Find, Update's table
func (engine *Engine) Table(tableNameOrBean interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Table(tableNameOrBean)
}
// Alias set the table alias
func (engine *Engine) Alias(alias string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Alias(alias)
}
// Limit will generate "LIMIT start, limit"
func (engine *Engine) Limit(limit int, start ...int) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Limit(limit, start...)
}
// Desc will generate "ORDER BY column1 DESC, column2 DESC"
func (engine *Engine) Desc(colNames ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Desc(colNames...)
}
// Asc will generate "ORDER BY column1,column2 Asc"
// This method can chainable use.
//
// engine.Desc("name").Asc("age").Find(&users)
// // SELECT * FROM user ORDER BY name DESC, age ASC
//
func (engine *Engine) Asc(colNames ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Asc(colNames...)
}
// OrderBy will generate "ORDER BY order"
func (engine *Engine) OrderBy(order string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.OrderBy(order)
}
// Join the join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
func (engine *Engine) Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Join(joinOperator, tablename, condition, args...)
}
// GroupBy generate group by statement
func (engine *Engine) GroupBy(keys string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.GroupBy(keys)
}
// Having generate having statement
func (engine *Engine) Having(conditions string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Having(conditions)
}
func (engine *Engine) autoMapType(v reflect.Value) *core.Table {
t := v.Type()
engine.mutex.Lock()
defer engine.mutex.Unlock()
table, ok := engine.Tables[t]
if !ok {
var err error
table, err = engine.mapType(v)
if err != nil {
engine.logger.Error(err)
} else {
engine.Tables[t] = table
if engine.Cacher != nil {
if v.CanAddr() {
engine.GobRegister(v.Addr().Interface())
} else {
engine.GobRegister(v.Interface())
}
}
}
}
return table
}
// GobRegister register one struct to gob for cache use
func (engine *Engine) GobRegister(v interface{}) *Engine {
//fmt.Printf("Type: %[1]T => Data: %[1]#v\n", v)
gob.Register(v)
return engine
}
// Table table struct
type Table struct {
*core.Table
Name string
}
// TableInfo get table info according to bean's content
func (engine *Engine) TableInfo(bean interface{}) *Table {
v := rValue(bean)
return &Table{engine.autoMapType(v), engine.tbName(v)}
}
func addIndex(indexName string, table *core.Table, col *core.Column, indexType int) {
if index, ok := table.Indexes[indexName]; ok {
index.AddColumn(col.Name)
col.Indexes[index.Name] = indexType
} else {
index := core.NewIndex(indexName, indexType)
index.AddColumn(col.Name)
table.AddIndex(index)
col.Indexes[index.Name] = indexType
}
}
func (engine *Engine) newTable() *core.Table {
table := core.NewEmptyTable()
if !engine.disableGlobalCache {
table.Cacher = engine.Cacher
}
return table
}
// TableName table name interface to define customerize table name
type TableName interface {
TableName() string
}
var (
tpTableName = reflect.TypeOf((*TableName)(nil)).Elem()
)
func (engine *Engine) mapType(v reflect.Value) (*core.Table, error) {
t := v.Type()
table := engine.newTable()
if tb, ok := v.Interface().(TableName); ok {
table.Name = tb.TableName()
} else {
if v.CanAddr() {
if tb, ok = v.Addr().Interface().(TableName); ok {
table.Name = tb.TableName()
}
}
if table.Name == "" {
table.Name = engine.TableMapper.Obj2Table(t.Name())
}
}
table.Type = t
var idFieldColName string
var hasCacheTag, hasNoCacheTag bool
for i := 0; i < t.NumField(); i++ {
tag := t.Field(i).Tag
ormTagStr := tag.Get(engine.TagIdentifier)
var col *core.Column
fieldValue := v.Field(i)
fieldType := fieldValue.Type()
if ormTagStr != "" {
col = &core.Column{FieldName: t.Field(i).Name, Nullable: true, IsPrimaryKey: false,
IsAutoIncrement: false, MapType: core.TWOSIDES, Indexes: make(map[string]int)}
tags := splitTag(ormTagStr)
if len(tags) > 0 {
if tags[0] == "-" {
continue
}
var ctx = tagContext{
table: table,
col: col,
fieldValue: fieldValue,
indexNames: make(map[string]int),
engine: engine,
}
if strings.ToUpper(tags[0]) == "EXTENDS" {
if err := ExtendsTagHandler(&ctx); err != nil {
return nil, err
}
continue
}
for j, key := range tags {
if ctx.ignoreNext {
ctx.ignoreNext = false
continue
}
k := strings.ToUpper(key)
ctx.tagName = k
pStart := strings.Index(k, "(")
if pStart == 0 {
return nil, errors.New("( could not be the first charactor")
}
if pStart > -1 {
if !strings.HasSuffix(k, ")") {
return nil, errors.New("cannot match ) charactor")
}
ctx.tagName = k[:pStart]
ctx.params = strings.Split(k[pStart+1:len(k)-1], ",")
}
if j > 0 {
ctx.preTag = strings.ToUpper(tags[j-1])
}
if j < len(tags)-1 {
ctx.nextTag = strings.ToUpper(tags[j+1])
} else {
ctx.nextTag = ""
}
if h, ok := engine.tagHandlers[ctx.tagName]; ok {
if err := h(&ctx); err != nil {
return nil, err
}
} else {
if strings.HasPrefix(key, "'") && strings.HasSuffix(key, "'") {
col.Name = key[1 : len(key)-1]
} else {
col.Name = key
}
}
if ctx.hasCacheTag {
hasCacheTag = true
}
if ctx.hasNoCacheTag {
hasNoCacheTag = true
}
}
if col.SQLType.Name == "" {
col.SQLType = core.Type2SQLType(fieldType)
}
engine.dialect.SqlType(col)
if col.Length == 0 {
col.Length = col.SQLType.DefaultLength
}
if col.Length2 == 0 {
col.Length2 = col.SQLType.DefaultLength2
}
if col.Name == "" {
col.Name = engine.ColumnMapper.Obj2Table(t.Field(i).Name)
}
if ctx.isUnique {
ctx.indexNames[col.Name] = core.UniqueType
} else if ctx.isIndex {
ctx.indexNames[col.Name] = core.IndexType
}
for indexName, indexType := range ctx.indexNames {
addIndex(indexName, table, col, indexType)
}
}
} else {
var sqlType core.SQLType
if fieldValue.CanAddr() {
if _, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
sqlType = core.SQLType{Name: core.Text}
}
}
if _, ok := fieldValue.Interface().(core.Conversion); ok {
sqlType = core.SQLType{Name: core.Text}
} else {
sqlType = core.Type2SQLType(fieldType)
}
col = core.NewColumn(engine.ColumnMapper.Obj2Table(t.Field(i).Name),
t.Field(i).Name, sqlType, sqlType.DefaultLength,
sqlType.DefaultLength2, true)
}
if col.IsAutoIncrement {
col.Nullable = false
}
table.AddColumn(col)
if fieldType.Kind() == reflect.Int64 && (strings.ToUpper(col.FieldName) == "ID" || strings.HasSuffix(strings.ToUpper(col.FieldName), ".ID")) {
idFieldColName = col.Name
}
} // end for
if idFieldColName != "" && len(table.PrimaryKeys) == 0 {
col := table.GetColumn(idFieldColName)
col.IsPrimaryKey = true
col.IsAutoIncrement = true
col.Nullable = false
table.PrimaryKeys = append(table.PrimaryKeys, col.Name)
table.AutoIncrement = col.Name
}
if hasCacheTag {
if engine.Cacher != nil { // !nash! use engine's cacher if provided
engine.logger.Info("enable cache on table:", table.Name)
table.Cacher = engine.Cacher
} else {
engine.logger.Info("enable LRU cache on table:", table.Name)
table.Cacher = NewLRUCacher2(NewMemoryStore(), time.Hour, 10000) // !nashtsai! HACK use LRU cacher for now
}
}
if hasNoCacheTag {
engine.logger.Info("no cache on table:", table.Name)
table.Cacher = nil
}
return table, nil
}
// IsTableEmpty if a table has any reocrd
func (engine *Engine) IsTableEmpty(bean interface{}) (bool, error) {
session := engine.NewSession()
defer session.Close()
return session.IsTableEmpty(bean)
}
// IsTableExist if a table is exist
func (engine *Engine) IsTableExist(beanOrTableName interface{}) (bool, error) {
session := engine.NewSession()
defer session.Close()
return session.IsTableExist(beanOrTableName)
}
// IdOf get id from one struct
//
// Deprecated: use IDOf instead.
func (engine *Engine) IdOf(bean interface{}) core.PK {
return engine.IDOf(bean)
}
// IDOf get id from one struct
func (engine *Engine) IDOf(bean interface{}) core.PK {
return engine.IdOfV(reflect.ValueOf(bean))
}
// IdOfV get id from one value of struct
//
// Deprecated: use IDOfV instead.
func (engine *Engine) IdOfV(rv reflect.Value) core.PK {
return engine.IDOfV(rv)
}
// IDOfV get id from one value of struct
func (engine *Engine) IDOfV(rv reflect.Value) core.PK {
v := reflect.Indirect(rv)
table := engine.autoMapType(v)
pk := make([]interface{}, len(table.PrimaryKeys))
for i, col := range table.PKColumns() {
pkField := v.FieldByName(col.FieldName)
switch pkField.Kind() {
case reflect.String:
pk[i] = pkField.String()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
pk[i] = pkField.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
pk[i] = pkField.Uint()
}
}
return core.PK(pk)
}
// CreateIndexes create indexes
func (engine *Engine) CreateIndexes(bean interface{}) error {
session := engine.NewSession()
defer session.Close()
return session.CreateIndexes(bean)
}
// CreateUniques create uniques
func (engine *Engine) CreateUniques(bean interface{}) error {
session := engine.NewSession()
defer session.Close()
return session.CreateUniques(bean)
}
func (engine *Engine) getCacher2(table *core.Table) core.Cacher {
return table.Cacher
}
func (engine *Engine) getCacher(v reflect.Value) core.Cacher {
if table := engine.autoMapType(v); table != nil {
return table.Cacher
}
return engine.Cacher
}
// ClearCacheBean if enabled cache, clear the cache bean
func (engine *Engine) ClearCacheBean(bean interface{}, id string) error {
v := rValue(bean)
t := v.Type()
if t.Kind() != reflect.Struct {
return errors.New("error params")
}
tableName := engine.tbName(v)
table := engine.autoMapType(v)
cacher := table.Cacher
if cacher == nil {
cacher = engine.Cacher
}
if cacher != nil {
cacher.ClearIds(tableName)
cacher.DelBean(tableName, id)
}
return nil
}
// ClearCache if enabled cache, clear some tables' cache
func (engine *Engine) ClearCache(beans ...interface{}) error {
for _, bean := range beans {
v := rValue(bean)
t := v.Type()
if t.Kind() != reflect.Struct {
return errors.New("error params")
}
tableName := engine.tbName(v)
table := engine.autoMapType(v)
cacher := table.Cacher
if cacher == nil {
cacher = engine.Cacher
}
if cacher != nil {
cacher.ClearIds(tableName)
cacher.ClearBeans(tableName)
}
}
return nil
}
// Sync the new struct changes to database, this method will automatically add
// table, column, index, unique. but will not delete or change anything.
// If you change some field, you should change the database manually.
func (engine *Engine) Sync(beans ...interface{}) error {
for _, bean := range beans {
v := rValue(bean)
tableName := engine.tbName(v)
table := engine.autoMapType(v)
s := engine.NewSession()
defer s.Close()
isExist, err := s.Table(bean).isTableExist(tableName)
if err != nil {
return err
}
if !isExist {
err = engine.CreateTables(bean)
if err != nil {
return err
}
}
/*isEmpty, err := engine.IsEmptyTable(bean)
if err != nil {
return err
}*/
var isEmpty bool
if isEmpty {
err = engine.DropTables(bean)
if err != nil {
return err
}
err = engine.CreateTables(bean)
if err != nil {
return err
}
} else {
for _, col := range table.Columns() {
isExist, err := engine.dialect.IsColumnExist(tableName, col.Name)
if err != nil {
return err
}
if !isExist {
session := engine.NewSession()
session.Statement.setRefValue(v)
defer session.Close()
err = session.addColumn(col.Name)
if err != nil {
return err
}
}
}
for name, index := range table.Indexes {
session := engine.NewSession()
session.Statement.setRefValue(v)
defer session.Close()
if index.Type == core.UniqueType {
//isExist, err := session.isIndexExist(table.Name, name, true)
isExist, err := session.isIndexExist2(tableName, index.Cols, true)
if err != nil {
return err
}
if !isExist {
session := engine.NewSession()
session.Statement.setRefValue(v)
defer session.Close()
err = session.addUnique(tableName, name)
if err != nil {
return err
}
}
} else if index.Type == core.IndexType {
isExist, err := session.isIndexExist2(tableName, index.Cols, false)
if err != nil {
return err
}
if !isExist {
session := engine.NewSession()
session.Statement.setRefValue(v)
defer session.Close()
err = session.addIndex(tableName, name)
if err != nil {
return err
}
}
} else {
return errors.New("unknow index type")
}
}
}
}
return nil
}
// Sync2 synchronize structs to database tables
func (engine *Engine) Sync2(beans ...interface{}) error {
s := engine.NewSession()
defer s.Close()
return s.Sync2(beans...)
}
func (engine *Engine) unMap(beans ...interface{}) (e error) {
engine.mutex.Lock()
defer engine.mutex.Unlock()
for _, bean := range beans {
t := rType(bean)
if _, ok := engine.Tables[t]; ok {
delete(engine.Tables, t)
}
}
return
}
// Drop all mapped table
func (engine *Engine) dropAll() error {
session := engine.NewSession()
defer session.Close()
err := session.Begin()
if err != nil {
return err
}
err = session.dropAll()
if err != nil {
session.Rollback()
return err
}
return session.Commit()
}
// CreateTables create tabls according bean
func (engine *Engine) CreateTables(beans ...interface{}) error {
session := engine.NewSession()
defer session.Close()
err := session.Begin()
if err != nil {
return err
}
for _, bean := range beans {
err = session.CreateTable(bean)
if err != nil {
session.Rollback()
return err
}
}
return session.Commit()
}
// DropTables drop specify tables
func (engine *Engine) DropTables(beans ...interface{}) error {
session := engine.NewSession()
defer session.Close()
err := session.Begin()
if err != nil {
return err
}
for _, bean := range beans {
err = session.DropTable(bean)
if err != nil {
session.Rollback()
return err
}
}
return session.Commit()
}
func (engine *Engine) createAll() error {
session := engine.NewSession()
defer session.Close()
return session.createAll()
}
// Exec raw sql
func (engine *Engine) Exec(sql string, args ...interface{}) (sql.Result, error) {
session := engine.NewSession()
defer session.Close()
return session.Exec(sql, args...)
}
// Query a raw sql and return records as []map[string][]byte
func (engine *Engine) Query(sql string, paramStr ...interface{}) (resultsSlice []map[string][]byte, err error) {
session := engine.NewSession()
defer session.Close()
return session.Query(sql, paramStr...)
}
// Insert one or more records
func (engine *Engine) Insert(beans ...interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.Insert(beans...)
}
// InsertOne insert only one record
func (engine *Engine) InsertOne(bean interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.InsertOne(bean)
}
// Update records, bean's non-empty fields are updated contents,
// condiBean' non-empty filds are conditions
// CAUTION:
// 1.bool will defaultly be updated content nor conditions
// You should call UseBool if you have bool to use.
// 2.float32 & float64 may be not inexact as conditions
func (engine *Engine) Update(bean interface{}, condiBeans ...interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.Update(bean, condiBeans...)
}
// Delete records, bean's non-empty fields are conditions
func (engine *Engine) Delete(bean interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.Delete(bean)
}
// Get retrieve one record from table, bean's non-empty fields
// are conditions
func (engine *Engine) Get(bean interface{}) (bool, error) {
session := engine.NewSession()
defer session.Close()
return session.Get(bean)
}
// Find retrieve records from table, condiBeans's non-empty fields
// are conditions. beans could be []Struct, []*Struct, map[int64]Struct
// map[int64]*Struct
func (engine *Engine) Find(beans interface{}, condiBeans ...interface{}) error {
session := engine.NewSession()
defer session.Close()
return session.Find(beans, condiBeans...)
}
// Iterate record by record handle records from table, bean's non-empty fields
// are conditions.
func (engine *Engine) Iterate(bean interface{}, fun IterFunc) error {
session := engine.NewSession()
defer session.Close()
return session.Iterate(bean, fun)
}
// Rows return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields
// are conditions.
func (engine *Engine) Rows(bean interface{}) (*Rows, error) {
session := engine.NewSession()
return session.Rows(bean)
}
// Count counts the records. bean's non-empty fields are conditions.
func (engine *Engine) Count(bean interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.Count(bean)
}
// Sum sum the records by some column. bean's non-empty fields are conditions.
func (engine *Engine) Sum(bean interface{}, colName string) (float64, error) {
session := engine.NewSession()
defer session.Close()
return session.Sum(bean, colName)
}
// Sums sum the records by some columns. bean's non-empty fields are conditions.
func (engine *Engine) Sums(bean interface{}, colNames ...string) ([]float64, error) {
session := engine.NewSession()
defer session.Close()
return session.Sums(bean, colNames...)
}
// SumsInt like Sums but return slice of int64 instead of float64.
func (engine *Engine) SumsInt(bean interface{}, colNames ...string) ([]int64, error) {
session := engine.NewSession()
defer session.Close()
return session.SumsInt(bean, colNames...)
}
// ImportFile SQL DDL file
func (engine *Engine) ImportFile(ddlPath string) ([]sql.Result, error) {
file, err := os.Open(ddlPath)
if err != nil {
return nil, err
}
defer file.Close()
return engine.Import(file)
}
// Import SQL DDL from io.Reader
func (engine *Engine) Import(r io.Reader) ([]sql.Result, error) {
var results []sql.Result
var lastError error
scanner := bufio.NewScanner(r)
semiColSpliter := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.IndexByte(data, ';'); i >= 0 {
return i + 1, data[0:i], nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
}
scanner.Split(semiColSpliter)
for scanner.Scan() {
query := strings.Trim(scanner.Text(), " \t\n\r")
if len(query) > 0 {
engine.logSQL(query)
result, err := engine.DB().Exec(query)
results = append(results, result)
if err != nil {
return nil, err
//lastError = err
}
}
}
return results, lastError
}
// TZTime change one time to xorm time location
func (engine *Engine) TZTime(t time.Time) time.Time {
if !t.IsZero() { // if time is not initialized it's not suitable for Time.In()
return t.In(engine.TZLocation)
}
return t
}
// NowTime return current time
func (engine *Engine) NowTime(sqlTypeName string) interface{} {
t := time.Now()
return engine.FormatTime(sqlTypeName, t)
}
// NowTime2 return current time
func (engine *Engine) NowTime2(sqlTypeName string) (interface{}, time.Time) {
t := time.Now()
return engine.FormatTime(sqlTypeName, t), t
}
// FormatTime format time
func (engine *Engine) FormatTime(sqlTypeName string, t time.Time) (v interface{}) {
return engine.formatTime(engine.TZLocation, sqlTypeName, t)
}
func (engine *Engine) formatColTime(col *core.Column, t time.Time) (v interface{}) {
if col.DisableTimeZone {
return engine.formatTime(nil, col.SQLType.Name, t)
} else if col.TimeZone != nil {
return engine.formatTime(col.TimeZone, col.SQLType.Name, t)
}
return engine.formatTime(engine.TZLocation, col.SQLType.Name, t)
}
func (engine *Engine) formatTime(tz *time.Location, sqlTypeName string, t time.Time) (v interface{}) {
if engine.dialect.DBType() == core.ORACLE {
return t
}
if tz != nil {
t = t.In(tz)
} else {
t = engine.TZTime(t)
}
switch sqlTypeName {
case core.Time:
s := t.Format("2006-01-02 15:04:05") //time.RFC3339
v = s[11:19]
case core.Date:
v = t.Format("2006-01-02")
case core.DateTime, core.TimeStamp:
if engine.dialect.DBType() == "ql" {
v = t
} else if engine.dialect.DBType() == "sqlite3" {
v = t.UTC().Format("2006-01-02 15:04:05")
} else {
v = t.Format("2006-01-02 15:04:05")
}
case core.TimeStampz:
if engine.dialect.DBType() == core.MSSQL {
v = t.Format("2006-01-02T15:04:05.9999999Z07:00")
} else if engine.DriverName() == "mssql" {
v = t
} else {
v = t.Format(time.RFC3339Nano)
}
case core.BigInt, core.Int:
v = t.Unix()
default:
v = t
}
return
}
// Unscoped always disable struct tag "deleted"
func (engine *Engine) Unscoped() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Unscoped()
}
| vendor/github.com/go-xorm/xorm/engine.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.005397771019488573,
0.00024221866624429822,
0.00016049010446295142,
0.00016791335656307638,
0.00044731423258781433
]
|
{
"id": 13,
"code_window": [
"\n",
"type GetDashboardSlugByIdQuery struct {\n",
"\tId int64\n",
"\tResult string\n",
"}\n",
"\n",
"type GetDashboardUidBySlugQuery struct {\n",
"\tOrgId int64\n",
"\tSlug string\n",
"\tResult string\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "pkg/models/dashboards.go",
"type": "replace",
"edit_start_line_idx": 233
} | package api
import (
"encoding/json"
"path/filepath"
"testing"
macaron "gopkg.in/macaron.v1"
"github.com/go-macaron/session"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
type fakeDashboardRepo struct {
inserted []*dashboards.SaveDashboardItem
getDashboard []*m.Dashboard
}
func (repo *fakeDashboardRepo) SaveDashboard(json *dashboards.SaveDashboardItem) (*m.Dashboard, error) {
repo.inserted = append(repo.inserted, json)
return json.Dashboard, nil
}
var fakeRepo *fakeDashboardRepo
func TestDashboardApiEndpoint(t *testing.T) {
Convey("Given a dashboard with a parent folder which does not have an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = false
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
viewerRole := m.ROLE_VIEWER
editorRole := m.ROLE_EDITOR
aclMockResp := []*m.DashboardAclInfoDTO{
{Role: &viewerRole, Permission: m.PERMISSION_VIEW},
{Role: &editorRole, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
"id": fakeDash.Id,
}),
}
Convey("When user is an Org Viewer", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
Convey("When saving a dashboard folder in another folder", func() {
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
query.Result.IsFolder = true
return nil
})
invalidCmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
IsFolder: true,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("Should return an error", func() {
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, invalidCmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 400)
})
})
})
})
})
Convey("Given a dashboard with a parent folder which has an acl", t, func() {
fakeDash := m.NewDashboard("Child dash")
fakeDash.Id = 1
fakeDash.FolderId = 1
fakeDash.HasAcl = true
setting.ViewersCanEdit = false
aclMockResp := []*m.DashboardAclInfoDTO{
{
DashboardId: 1,
Permission: m.PERMISSION_EDIT,
UserId: 200,
},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp
return nil
})
var getDashboardQueries []*m.GetDashboardQuery
bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
query.Result = fakeDash
getDashboardQueries = append(getDashboardQueries, query)
return nil
})
bus.AddHandler("test", func(query *m.GetDashboardUidBySlugQuery) error {
query.Result = fakeDash.Uid
return nil
})
bus.AddHandler("test", func(query *m.GetTeamsByUserQuery) error {
query.Result = []*m.Team{}
return nil
})
cmd := m.SaveDashboardCommand{
FolderId: fakeDash.FolderId,
Dashboard: simplejson.NewFromAny(map[string]interface{}{
"id": fakeDash.Id,
"folderId": fakeDash.FolderId,
"title": fakeDash.Title,
}),
}
Convey("When user is an Org Viewer and has no permissions for this dashboard", func() {
role := m.ROLE_VIEWER
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Editor and has no permissions for this dashboard", func() {
role := m.ROLE_EDITOR
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
CallGetDashboardUidBySlug(sc)
Convey("Should be denied access", func() {
So(sc.resp.Code, ShouldEqual, 403)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
Convey("When user is an Org Viewer but has an edit permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_EDIT},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Viewer and viewers can edit", func() {
role := m.ROLE_VIEWER
setting.ViewersCanEdit = true
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights but can save should be false", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeFalse)
So(dash.Meta.CanAdmin, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
})
Convey("When user is an Org Viewer but has an admin permission", func() {
role := m.ROLE_VIEWER
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_ADMIN},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should be able to get dashboard with edit rights", func() {
So(dash.Meta.CanEdit, ShouldBeTrue)
So(dash.Meta.CanSave, ShouldBeTrue)
So(dash.Meta.CanAdmin, ShouldBeTrue)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 200)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
So(result.Get("status").MustString(), ShouldEqual, "success")
So(result.Get("id").MustInt64(), ShouldBeGreaterThan, 0)
So(result.Get("uid").MustString(), ShouldNotBeNil)
So(result.Get("slug").MustString(), ShouldNotBeNil)
})
})
Convey("When user is an Org Editor but has a view permission", func() {
role := m.ROLE_EDITOR
mockResult := []*m.DashboardAclInfoDTO{
{Id: 1, OrgId: 1, DashboardId: 2, UserId: 1, Permission: m.PERMISSION_VIEW},
}
bus.AddHandler("test", func(query *m.GetDashboardAclInfoListQuery) error {
query.Result = mockResult
return nil
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
dash := GetDashboardShouldReturn200(sc)
Convey("Should lookup dashboard by uid", func() {
So(getDashboardQueries[0].Uid, ShouldEqual, "abcdefghi")
})
Convey("Should not be able to edit or save dashboard", func() {
So(dash.Meta.CanEdit, ShouldBeFalse)
So(dash.Meta.CanSave, ShouldBeFalse)
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/db/child-dash/uid", "/api/dashboards/db/:slug/uid", role, func(sc *scenarioContext) {
uid := GetDashboardUidBySlugShouldReturn200(sc)
Convey("Should return uid", func() {
So(uid, ShouldEqual, fakeDash.Uid)
})
})
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/db/child-dash", "/api/dashboards/db/:slug", role, func(sc *scenarioContext) {
CallDeleteDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by slug", func() {
So(getDashboardQueries[0].Slug, ShouldEqual, "child-dash")
})
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions/1", "/api/dashboards/id/:dashboardId/versions/:id", role, func(sc *scenarioContext) {
CallGetDashboardVersion(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
loggedInUserScenarioWithRole("When calling GET on", "GET", "/api/dashboards/id/2/versions", "/api/dashboards/id/:dashboardId/versions", role, func(sc *scenarioContext) {
CallGetDashboardVersions(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
postDashboardScenario("When calling POST on", "/api/dashboards", "/api/dashboards", role, cmd, func(sc *scenarioContext) {
CallPostDashboard(sc)
So(sc.resp.Code, ShouldEqual, 403)
})
})
})
}
func GetDashboardShouldReturn200(sc *scenarioContext) dtos.DashboardFullWithMeta {
sc.handlerFunc = GetDashboard
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
So(sc.resp.Code, ShouldEqual, 200)
dash := dtos.DashboardFullWithMeta{}
err := json.NewDecoder(sc.resp.Body).Decode(&dash)
So(err, ShouldBeNil)
return dash
}
func GetDashboardUidBySlugShouldReturn200(sc *scenarioContext) string {
CallGetDashboardUidBySlug(sc)
So(sc.resp.Code, ShouldEqual, 200)
result := sc.ToJson()
return result.Get("uid").MustString()
}
func CallGetDashboardUidBySlug(sc *scenarioContext) {
sc.handlerFunc = GetDashboardUidBySlug
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersion(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionQuery) error {
query.Result = &m.DashboardVersion{}
return nil
})
sc.handlerFunc = GetDashboardVersion
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallGetDashboardVersions(sc *scenarioContext) {
bus.AddHandler("test", func(query *m.GetDashboardVersionsQuery) error {
query.Result = []*m.DashboardVersionDTO{}
return nil
})
sc.handlerFunc = GetDashboardVersions
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
}
func CallDeleteDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error {
return nil
})
sc.handlerFunc = DeleteDashboard
sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec()
}
func CallPostDashboard(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *alerting.ValidateDashboardAlertsCommand) error {
return nil
})
bus.AddHandler("test", func(cmd *m.SaveDashboardCommand) error {
cmd.Result = &m.Dashboard{Id: 2, Slug: "Dash", Version: 2}
return nil
})
bus.AddHandler("test", func(cmd *alerting.UpdateDashboardAlertsCommand) error {
return nil
})
sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec()
}
func postDashboardScenario(desc string, url string, routePattern string, role m.RoleType, cmd m.SaveDashboardCommand, fn scenarioFunc) {
Convey(desc+" "+url, func() {
defer bus.ClearBusHandlers()
sc := &scenarioContext{
url: url,
}
viewsPath, _ := filepath.Abs("../../public/views")
sc.m = macaron.New()
sc.m.Use(macaron.Renderer(macaron.RenderOptions{
Directory: viewsPath,
Delims: macaron.Delims{Left: "[[", Right: "]]"},
}))
sc.m.Use(middleware.GetContextHandler())
sc.m.Use(middleware.Sessioner(&session.Options{}))
sc.defaultHandler = wrap(func(c *middleware.Context) Response {
sc.context = c
sc.context.UserId = TestUserID
sc.context.OrgId = TestOrgID
sc.context.OrgRole = role
return PostDashboard(c, cmd)
})
fakeRepo = &fakeDashboardRepo{}
dashboards.SetRepository(fakeRepo)
sc.m.Post(routePattern, sc.defaultHandler)
fn(sc)
})
}
func (sc *scenarioContext) ToJson() *simplejson.Json {
var result *simplejson.Json
err := json.NewDecoder(sc.resp.Body).Decode(&result)
So(err, ShouldBeNil)
return result
}
| pkg/api/dashboard_test.go | 1 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.9991008043289185,
0.2215137481689453,
0.00016490167763549834,
0.02684176340699196,
0.35144251585006714
]
|
{
"id": 13,
"code_window": [
"\n",
"type GetDashboardSlugByIdQuery struct {\n",
"\tId int64\n",
"\tResult string\n",
"}\n",
"\n",
"type GetDashboardUidBySlugQuery struct {\n",
"\tOrgId int64\n",
"\tSlug string\n",
"\tResult string\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "pkg/models/dashboards.go",
"type": "replace",
"edit_start_line_idx": 233
} | import { PanelCtrl } from 'app/plugins/sdk';
import { contextSrv } from 'app/core/core';
class GettingStartedPanelCtrl extends PanelCtrl {
static templateUrl = 'public/app/plugins/panel/gettingstarted/module.html';
checksDone: boolean;
stepIndex: number;
steps: any;
/** @ngInject **/
constructor($scope, $injector, private backendSrv, datasourceSrv, private $q) {
super($scope, $injector);
this.stepIndex = 0;
this.steps = [];
this.steps.push({
title: 'Install Grafana',
icon: 'icon-gf icon-gf-check',
href: 'http://docs.grafana.org/',
target: '_blank',
note: 'Review the installation docs',
check: () => $q.when(true),
});
this.steps.push({
title: 'Create your first data source',
cta: 'Add data source',
icon: 'icon-gf icon-gf-datasources',
href: 'datasources/new?gettingstarted',
check: () => {
return $q.when(
datasourceSrv.getMetricSources().filter(item => {
return item.meta.builtIn !== true;
}).length > 0
);
},
});
this.steps.push({
title: 'Create your first dashboard',
cta: 'New dashboard',
icon: 'icon-gf icon-gf-dashboard',
href: 'dashboard/new?gettingstarted',
check: () => {
return this.backendSrv.search({ limit: 1 }).then(result => {
return result.length > 0;
});
},
});
this.steps.push({
title: 'Invite your team',
cta: 'Add Users',
icon: 'icon-gf icon-gf-users',
href: 'org/users?gettingstarted',
check: () => {
return this.backendSrv.get('/api/org/users').then(res => {
return res.length > 1;
});
},
});
this.steps.push({
title: 'Install apps & plugins',
cta: 'Explore plugin repository',
icon: 'icon-gf icon-gf-apps',
href: 'https://grafana.com/plugins?utm_source=grafana_getting_started',
check: () => {
return this.backendSrv.get('/api/plugins', { embedded: 0, core: 0 }).then(plugins => {
return plugins.length > 0;
});
},
});
}
$onInit() {
this.stepIndex = -1;
return this.nextStep().then(res => {
this.checksDone = true;
});
}
nextStep() {
if (this.stepIndex === this.steps.length - 1) {
return this.$q.when();
}
this.stepIndex += 1;
var currentStep = this.steps[this.stepIndex];
return currentStep.check().then(passed => {
if (passed) {
currentStep.cssClass = 'completed';
return this.nextStep();
}
currentStep.cssClass = 'active';
return this.$q.when();
});
}
dismiss() {
this.dashboard.removePanel(this.panel, false);
this.backendSrv
.request({
method: 'PUT',
url: '/api/user/helpflags/1',
showSuccessAlert: false,
})
.then(res => {
contextSrv.user.helpFlags1 = res.helpFlags1;
});
}
}
export { GettingStartedPanelCtrl, GettingStartedPanelCtrl as PanelCtrl };
| public/app/plugins/panel/gettingstarted/module.ts | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.00022148415155243129,
0.0001748164213495329,
0.00016731226060073823,
0.00017092909547500312,
0.000014196653864928521
]
|
{
"id": 13,
"code_window": [
"\n",
"type GetDashboardSlugByIdQuery struct {\n",
"\tId int64\n",
"\tResult string\n",
"}\n",
"\n",
"type GetDashboardUidBySlugQuery struct {\n",
"\tOrgId int64\n",
"\tSlug string\n",
"\tResult string\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "pkg/models/dashboards.go",
"type": "replace",
"edit_start_line_idx": 233
} | // cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go
// Code generated by the command above; see README.md. DO NOT EDIT.
// +build mips64le,linux
package unix
const (
sizeofPtr = 0x8
sizeofShort = 0x2
sizeofInt = 0x4
sizeofLong = 0x8
sizeofLongLong = 0x8
PathMax = 0x1000
)
type (
_C_short int16
_C_int int32
_C_long int64
_C_long_long int64
)
type Timespec struct {
Sec int64
Nsec int64
}
type Timeval struct {
Sec int64
Usec int64
}
type Timex struct {
Modes uint32
Pad_cgo_0 [4]byte
Offset int64
Freq int64
Maxerror int64
Esterror int64
Status int32
Pad_cgo_1 [4]byte
Constant int64
Precision int64
Tolerance int64
Time Timeval
Tick int64
Ppsfreq int64
Jitter int64
Shift int32
Pad_cgo_2 [4]byte
Stabil int64
Jitcnt int64
Calcnt int64
Errcnt int64
Stbcnt int64
Tai int32
Pad_cgo_3 [44]byte
}
type Time_t int64
type Tms struct {
Utime int64
Stime int64
Cutime int64
Cstime int64
}
type Utimbuf struct {
Actime int64
Modtime int64
}
type Rusage struct {
Utime Timeval
Stime Timeval
Maxrss int64
Ixrss int64
Idrss int64
Isrss int64
Minflt int64
Majflt int64
Nswap int64
Inblock int64
Oublock int64
Msgsnd int64
Msgrcv int64
Nsignals int64
Nvcsw int64
Nivcsw int64
}
type Rlimit struct {
Cur uint64
Max uint64
}
type _Gid_t uint32
type Stat_t struct {
Dev uint32
Pad1 [3]uint32
Ino uint64
Mode uint32
Nlink uint32
Uid uint32
Gid uint32
Rdev uint32
Pad2 [3]uint32
Size int64
Atim Timespec
Mtim Timespec
Ctim Timespec
Blksize uint32
Pad4 uint32
Blocks int64
}
type Statfs_t struct {
Type int64
Bsize int64
Frsize int64
Blocks uint64
Bfree uint64
Files uint64
Ffree uint64
Bavail uint64
Fsid Fsid
Namelen int64
Flags int64
Spare [5]int64
}
type StatxTimestamp struct {
Sec int64
Nsec uint32
X__reserved int32
}
type Statx_t struct {
Mask uint32
Blksize uint32
Attributes uint64
Nlink uint32
Uid uint32
Gid uint32
Mode uint16
_ [1]uint16
Ino uint64
Size uint64
Blocks uint64
Attributes_mask uint64
Atime StatxTimestamp
Btime StatxTimestamp
Ctime StatxTimestamp
Mtime StatxTimestamp
Rdev_major uint32
Rdev_minor uint32
Dev_major uint32
Dev_minor uint32
_ [14]uint64
}
type Dirent struct {
Ino uint64
Off int64
Reclen uint16
Type uint8
Name [256]int8
Pad_cgo_0 [5]byte
}
type Fsid struct {
X__val [2]int32
}
type Flock_t struct {
Type int16
Whence int16
Pad_cgo_0 [4]byte
Start int64
Len int64
Pid int32
Pad_cgo_1 [4]byte
}
type FscryptPolicy struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
Master_key_descriptor [8]uint8
}
type FscryptKey struct {
Mode uint32
Raw [64]uint8
Size uint32
}
type KeyctlDHParams struct {
Private int32
Prime int32
Base int32
}
const (
FADV_NORMAL = 0x0
FADV_RANDOM = 0x1
FADV_SEQUENTIAL = 0x2
FADV_WILLNEED = 0x3
FADV_DONTNEED = 0x4
FADV_NOREUSE = 0x5
)
type RawSockaddrInet4 struct {
Family uint16
Port uint16
Addr [4]byte /* in_addr */
Zero [8]uint8
}
type RawSockaddrInet6 struct {
Family uint16
Port uint16
Flowinfo uint32
Addr [16]byte /* in6_addr */
Scope_id uint32
}
type RawSockaddrUnix struct {
Family uint16
Path [108]int8
}
type RawSockaddrLinklayer struct {
Family uint16
Protocol uint16
Ifindex int32
Hatype uint16
Pkttype uint8
Halen uint8
Addr [8]uint8
}
type RawSockaddrNetlink struct {
Family uint16
Pad uint16
Pid uint32
Groups uint32
}
type RawSockaddrHCI struct {
Family uint16
Dev uint16
Channel uint16
}
type RawSockaddrCAN struct {
Family uint16
Pad_cgo_0 [2]byte
Ifindex int32
Addr [8]byte
}
type RawSockaddrALG struct {
Family uint16
Type [14]uint8
Feat uint32
Mask uint32
Name [64]uint8
}
type RawSockaddrVM struct {
Family uint16
Reserved1 uint16
Port uint32
Cid uint32
Zero [4]uint8
}
type RawSockaddr struct {
Family uint16
Data [14]int8
}
type RawSockaddrAny struct {
Addr RawSockaddr
Pad [96]int8
}
type _Socklen uint32
type Linger struct {
Onoff int32
Linger int32
}
type Iovec struct {
Base *byte
Len uint64
}
type IPMreq struct {
Multiaddr [4]byte /* in_addr */
Interface [4]byte /* in_addr */
}
type IPMreqn struct {
Multiaddr [4]byte /* in_addr */
Address [4]byte /* in_addr */
Ifindex int32
}
type IPv6Mreq struct {
Multiaddr [16]byte /* in6_addr */
Interface uint32
}
type PacketMreq struct {
Ifindex int32
Type uint16
Alen uint16
Address [8]uint8
}
type Msghdr struct {
Name *byte
Namelen uint32
Pad_cgo_0 [4]byte
Iov *Iovec
Iovlen uint64
Control *byte
Controllen uint64
Flags int32
Pad_cgo_1 [4]byte
}
type Cmsghdr struct {
Len uint64
Level int32
Type int32
}
type Inet4Pktinfo struct {
Ifindex int32
Spec_dst [4]byte /* in_addr */
Addr [4]byte /* in_addr */
}
type Inet6Pktinfo struct {
Addr [16]byte /* in6_addr */
Ifindex uint32
}
type IPv6MTUInfo struct {
Addr RawSockaddrInet6
Mtu uint32
}
type ICMPv6Filter struct {
Data [8]uint32
}
type Ucred struct {
Pid int32
Uid uint32
Gid uint32
}
type TCPInfo struct {
State uint8
Ca_state uint8
Retransmits uint8
Probes uint8
Backoff uint8
Options uint8
Pad_cgo_0 [2]byte
Rto uint32
Ato uint32
Snd_mss uint32
Rcv_mss uint32
Unacked uint32
Sacked uint32
Lost uint32
Retrans uint32
Fackets uint32
Last_data_sent uint32
Last_ack_sent uint32
Last_data_recv uint32
Last_ack_recv uint32
Pmtu uint32
Rcv_ssthresh uint32
Rtt uint32
Rttvar uint32
Snd_ssthresh uint32
Snd_cwnd uint32
Advmss uint32
Reordering uint32
Rcv_rtt uint32
Rcv_space uint32
Total_retrans uint32
}
const (
SizeofSockaddrInet4 = 0x10
SizeofSockaddrInet6 = 0x1c
SizeofSockaddrAny = 0x70
SizeofSockaddrUnix = 0x6e
SizeofSockaddrLinklayer = 0x14
SizeofSockaddrNetlink = 0xc
SizeofSockaddrHCI = 0x6
SizeofSockaddrCAN = 0x10
SizeofSockaddrALG = 0x58
SizeofSockaddrVM = 0x10
SizeofLinger = 0x8
SizeofIovec = 0x10
SizeofIPMreq = 0x8
SizeofIPMreqn = 0xc
SizeofIPv6Mreq = 0x14
SizeofPacketMreq = 0x10
SizeofMsghdr = 0x38
SizeofCmsghdr = 0x10
SizeofInet4Pktinfo = 0xc
SizeofInet6Pktinfo = 0x14
SizeofIPv6MTUInfo = 0x20
SizeofICMPv6Filter = 0x20
SizeofUcred = 0xc
SizeofTCPInfo = 0x68
)
const (
IFA_UNSPEC = 0x0
IFA_ADDRESS = 0x1
IFA_LOCAL = 0x2
IFA_LABEL = 0x3
IFA_BROADCAST = 0x4
IFA_ANYCAST = 0x5
IFA_CACHEINFO = 0x6
IFA_MULTICAST = 0x7
IFLA_UNSPEC = 0x0
IFLA_ADDRESS = 0x1
IFLA_BROADCAST = 0x2
IFLA_IFNAME = 0x3
IFLA_MTU = 0x4
IFLA_LINK = 0x5
IFLA_QDISC = 0x6
IFLA_STATS = 0x7
IFLA_COST = 0x8
IFLA_PRIORITY = 0x9
IFLA_MASTER = 0xa
IFLA_WIRELESS = 0xb
IFLA_PROTINFO = 0xc
IFLA_TXQLEN = 0xd
IFLA_MAP = 0xe
IFLA_WEIGHT = 0xf
IFLA_OPERSTATE = 0x10
IFLA_LINKMODE = 0x11
IFLA_LINKINFO = 0x12
IFLA_NET_NS_PID = 0x13
IFLA_IFALIAS = 0x14
IFLA_MAX = 0x2c
RT_SCOPE_UNIVERSE = 0x0
RT_SCOPE_SITE = 0xc8
RT_SCOPE_LINK = 0xfd
RT_SCOPE_HOST = 0xfe
RT_SCOPE_NOWHERE = 0xff
RT_TABLE_UNSPEC = 0x0
RT_TABLE_COMPAT = 0xfc
RT_TABLE_DEFAULT = 0xfd
RT_TABLE_MAIN = 0xfe
RT_TABLE_LOCAL = 0xff
RT_TABLE_MAX = 0xffffffff
RTA_UNSPEC = 0x0
RTA_DST = 0x1
RTA_SRC = 0x2
RTA_IIF = 0x3
RTA_OIF = 0x4
RTA_GATEWAY = 0x5
RTA_PRIORITY = 0x6
RTA_PREFSRC = 0x7
RTA_METRICS = 0x8
RTA_MULTIPATH = 0x9
RTA_FLOW = 0xb
RTA_CACHEINFO = 0xc
RTA_TABLE = 0xf
RTN_UNSPEC = 0x0
RTN_UNICAST = 0x1
RTN_LOCAL = 0x2
RTN_BROADCAST = 0x3
RTN_ANYCAST = 0x4
RTN_MULTICAST = 0x5
RTN_BLACKHOLE = 0x6
RTN_UNREACHABLE = 0x7
RTN_PROHIBIT = 0x8
RTN_THROW = 0x9
RTN_NAT = 0xa
RTN_XRESOLVE = 0xb
RTNLGRP_NONE = 0x0
RTNLGRP_LINK = 0x1
RTNLGRP_NOTIFY = 0x2
RTNLGRP_NEIGH = 0x3
RTNLGRP_TC = 0x4
RTNLGRP_IPV4_IFADDR = 0x5
RTNLGRP_IPV4_MROUTE = 0x6
RTNLGRP_IPV4_ROUTE = 0x7
RTNLGRP_IPV4_RULE = 0x8
RTNLGRP_IPV6_IFADDR = 0x9
RTNLGRP_IPV6_MROUTE = 0xa
RTNLGRP_IPV6_ROUTE = 0xb
RTNLGRP_IPV6_IFINFO = 0xc
RTNLGRP_IPV6_PREFIX = 0x12
RTNLGRP_IPV6_RULE = 0x13
RTNLGRP_ND_USEROPT = 0x14
SizeofNlMsghdr = 0x10
SizeofNlMsgerr = 0x14
SizeofRtGenmsg = 0x1
SizeofNlAttr = 0x4
SizeofRtAttr = 0x4
SizeofIfInfomsg = 0x10
SizeofIfAddrmsg = 0x8
SizeofRtMsg = 0xc
SizeofRtNexthop = 0x8
)
type NlMsghdr struct {
Len uint32
Type uint16
Flags uint16
Seq uint32
Pid uint32
}
type NlMsgerr struct {
Error int32
Msg NlMsghdr
}
type RtGenmsg struct {
Family uint8
}
type NlAttr struct {
Len uint16
Type uint16
}
type RtAttr struct {
Len uint16
Type uint16
}
type IfInfomsg struct {
Family uint8
X__ifi_pad uint8
Type uint16
Index int32
Flags uint32
Change uint32
}
type IfAddrmsg struct {
Family uint8
Prefixlen uint8
Flags uint8
Scope uint8
Index uint32
}
type RtMsg struct {
Family uint8
Dst_len uint8
Src_len uint8
Tos uint8
Table uint8
Protocol uint8
Scope uint8
Type uint8
Flags uint32
}
type RtNexthop struct {
Len uint16
Flags uint8
Hops uint8
Ifindex int32
}
const (
SizeofSockFilter = 0x8
SizeofSockFprog = 0x10
)
type SockFilter struct {
Code uint16
Jt uint8
Jf uint8
K uint32
}
type SockFprog struct {
Len uint16
Pad_cgo_0 [6]byte
Filter *SockFilter
}
type InotifyEvent struct {
Wd int32
Mask uint32
Cookie uint32
Len uint32
}
const SizeofInotifyEvent = 0x10
type PtraceRegs struct {
Regs [32]uint64
Lo uint64
Hi uint64
Epc uint64
Badvaddr uint64
Status uint64
Cause uint64
}
type FdSet struct {
Bits [16]int64
}
type Sysinfo_t struct {
Uptime int64
Loads [3]uint64
Totalram uint64
Freeram uint64
Sharedram uint64
Bufferram uint64
Totalswap uint64
Freeswap uint64
Procs uint16
Pad uint16
Pad_cgo_0 [4]byte
Totalhigh uint64
Freehigh uint64
Unit uint32
X_f [0]int8
Pad_cgo_1 [4]byte
}
type Utsname struct {
Sysname [65]byte
Nodename [65]byte
Release [65]byte
Version [65]byte
Machine [65]byte
Domainname [65]byte
}
type Ustat_t struct {
Tfree int32
Pad_cgo_0 [4]byte
Tinode uint64
Fname [6]int8
Fpack [6]int8
Pad_cgo_1 [4]byte
}
type EpollEvent struct {
Events uint32
Fd int32
Pad int32
}
const (
AT_EMPTY_PATH = 0x1000
AT_FDCWD = -0x64
AT_NO_AUTOMOUNT = 0x800
AT_REMOVEDIR = 0x200
AT_STATX_SYNC_AS_STAT = 0x0
AT_STATX_FORCE_SYNC = 0x2000
AT_STATX_DONT_SYNC = 0x4000
AT_SYMLINK_FOLLOW = 0x400
AT_SYMLINK_NOFOLLOW = 0x100
)
type PollFd struct {
Fd int32
Events int16
Revents int16
}
const (
POLLIN = 0x1
POLLPRI = 0x2
POLLOUT = 0x4
POLLRDHUP = 0x2000
POLLERR = 0x8
POLLHUP = 0x10
POLLNVAL = 0x20
)
type Sigset_t struct {
X__val [16]uint64
}
const RNDGETENTCNT = 0x40045200
const PERF_IOC_FLAG_GROUP = 0x1
type Termios struct {
Iflag uint32
Oflag uint32
Cflag uint32
Lflag uint32
Line uint8
Cc [23]uint8
Ispeed uint32
Ospeed uint32
}
type Winsize struct {
Row uint16
Col uint16
Xpixel uint16
Ypixel uint16
}
type Taskstats struct {
Version uint16
Pad_cgo_0 [2]byte
Ac_exitcode uint32
Ac_flag uint8
Ac_nice uint8
Pad_cgo_1 [6]byte
Cpu_count uint64
Cpu_delay_total uint64
Blkio_count uint64
Blkio_delay_total uint64
Swapin_count uint64
Swapin_delay_total uint64
Cpu_run_real_total uint64
Cpu_run_virtual_total uint64
Ac_comm [32]int8
Ac_sched uint8
Ac_pad [3]uint8
Pad_cgo_2 [4]byte
Ac_uid uint32
Ac_gid uint32
Ac_pid uint32
Ac_ppid uint32
Ac_btime uint32
Pad_cgo_3 [4]byte
Ac_etime uint64
Ac_utime uint64
Ac_stime uint64
Ac_minflt uint64
Ac_majflt uint64
Coremem uint64
Virtmem uint64
Hiwater_rss uint64
Hiwater_vm uint64
Read_char uint64
Write_char uint64
Read_syscalls uint64
Write_syscalls uint64
Read_bytes uint64
Write_bytes uint64
Cancelled_write_bytes uint64
Nvcsw uint64
Nivcsw uint64
Ac_utimescaled uint64
Ac_stimescaled uint64
Cpu_scaled_run_real_total uint64
Freepages_count uint64
Freepages_delay_total uint64
}
const (
TASKSTATS_CMD_UNSPEC = 0x0
TASKSTATS_CMD_GET = 0x1
TASKSTATS_CMD_NEW = 0x2
TASKSTATS_TYPE_UNSPEC = 0x0
TASKSTATS_TYPE_PID = 0x1
TASKSTATS_TYPE_TGID = 0x2
TASKSTATS_TYPE_STATS = 0x3
TASKSTATS_TYPE_AGGR_PID = 0x4
TASKSTATS_TYPE_AGGR_TGID = 0x5
TASKSTATS_TYPE_NULL = 0x6
TASKSTATS_CMD_ATTR_UNSPEC = 0x0
TASKSTATS_CMD_ATTR_PID = 0x1
TASKSTATS_CMD_ATTR_TGID = 0x2
TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3
TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4
)
type CGroupStats struct {
Sleeping uint64
Running uint64
Stopped uint64
Uninterruptible uint64
Io_wait uint64
}
const (
CGROUPSTATS_CMD_UNSPEC = 0x3
CGROUPSTATS_CMD_GET = 0x4
CGROUPSTATS_CMD_NEW = 0x5
CGROUPSTATS_TYPE_UNSPEC = 0x0
CGROUPSTATS_TYPE_CGROUP_STATS = 0x1
CGROUPSTATS_CMD_ATTR_UNSPEC = 0x0
CGROUPSTATS_CMD_ATTR_FD = 0x1
)
type Genlmsghdr struct {
Cmd uint8
Version uint8
Reserved uint16
}
const (
CTRL_CMD_UNSPEC = 0x0
CTRL_CMD_NEWFAMILY = 0x1
CTRL_CMD_DELFAMILY = 0x2
CTRL_CMD_GETFAMILY = 0x3
CTRL_CMD_NEWOPS = 0x4
CTRL_CMD_DELOPS = 0x5
CTRL_CMD_GETOPS = 0x6
CTRL_CMD_NEWMCAST_GRP = 0x7
CTRL_CMD_DELMCAST_GRP = 0x8
CTRL_CMD_GETMCAST_GRP = 0x9
CTRL_ATTR_UNSPEC = 0x0
CTRL_ATTR_FAMILY_ID = 0x1
CTRL_ATTR_FAMILY_NAME = 0x2
CTRL_ATTR_VERSION = 0x3
CTRL_ATTR_HDRSIZE = 0x4
CTRL_ATTR_MAXATTR = 0x5
CTRL_ATTR_OPS = 0x6
CTRL_ATTR_MCAST_GROUPS = 0x7
CTRL_ATTR_OP_UNSPEC = 0x0
CTRL_ATTR_OP_ID = 0x1
CTRL_ATTR_OP_FLAGS = 0x2
CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0
CTRL_ATTR_MCAST_GRP_NAME = 0x1
CTRL_ATTR_MCAST_GRP_ID = 0x2
)
type cpuMask uint64
const (
_CPU_SETSIZE = 0x400
_NCPUBITS = 0x40
)
| vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.0008044871501624584,
0.00019816226267721504,
0.00016381203022319824,
0.00017170669161714613,
0.0000840359425637871
]
|
{
"id": 13,
"code_window": [
"\n",
"type GetDashboardSlugByIdQuery struct {\n",
"\tId int64\n",
"\tResult string\n",
"}\n",
"\n",
"type GetDashboardUidBySlugQuery struct {\n",
"\tOrgId int64\n",
"\tSlug string\n",
"\tResult string\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "pkg/models/dashboards.go",
"type": "replace",
"edit_start_line_idx": 233
} | // +build go1.4
package ldap
import (
"sync/atomic"
)
// For compilers that support it, we just use the underlying sync/atomic.Value
// type.
type atomicValue struct {
atomic.Value
}
| vendor/github.com/go-ldap/ldap/atomic_value.go | 0 | https://github.com/grafana/grafana/commit/fd59241e35bc6584bfcef2a1c9dfc41f19337b38 | [
0.000202081078896299,
0.0001854241854744032,
0.0001687672920525074,
0.0001854241854744032,
0.000016656893421895802
]
|
{
"id": 0,
"code_window": [
"\n",
" async runQueries(resultType: ResultType, queryOptions: any, resultGetter?: any) {\n",
" const queries = [...this.modifiedQueries];\n",
" if (!hasNonEmptyQuery(queries)) {\n",
" return;\n",
" }\n",
" const { datasource } = this.state;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.setState({\n",
" queryTransactions: [],\n",
" });\n"
],
"file_path": "public/app/features/explore/Explore.tsx",
"type": "add",
"edit_start_line_idx": 773
} | import _ from 'lodash';
import React, { PureComponent } from 'react';
import Highlighter from 'react-highlight-words';
import * as rangeUtil from 'app/core/utils/rangeutil';
import { RawTimeRange } from 'app/types/series';
import {
LogsDedupStrategy,
LogsModel,
dedupLogRows,
filterLogLevels,
LogLevel,
LogsStreamLabels,
LogsMetaKind,
LogRow,
} from 'app/core/logs_model';
import { findHighlightChunksInText } from 'app/core/utils/text';
import { Switch } from 'app/core/components/Switch/Switch';
import Graph from './Graph';
const PREVIEW_LIMIT = 100;
const graphOptions = {
series: {
bars: {
show: true,
lineWidth: 5,
// barWidth: 10,
},
// stack: true,
},
yaxis: {
tickDecimals: 0,
},
};
function renderMetaItem(value: any, kind: LogsMetaKind) {
if (kind === LogsMetaKind.LabelsMap) {
return (
<span className="logs-meta-item__value-labels">
<Labels labels={value} />
</span>
);
}
return value;
}
class Label extends PureComponent<{
label: string;
value: string;
onClickLabel?: (label: string, value: string) => void;
}> {
onClickLabel = () => {
const { onClickLabel, label, value } = this.props;
if (onClickLabel) {
onClickLabel(label, value);
}
};
render() {
const { label, value } = this.props;
const tooltip = `${label}: ${value}`;
return (
<span className="logs-label" title={tooltip} onClick={this.onClickLabel}>
{value}
</span>
);
}
}
class Labels extends PureComponent<{
labels: LogsStreamLabels;
onClickLabel?: (label: string, value: string) => void;
}> {
render() {
const { labels, onClickLabel } = this.props;
return Object.keys(labels).map(key => (
<Label key={key} label={key} value={labels[key]} onClickLabel={onClickLabel} />
));
}
}
interface RowProps {
row: LogRow;
showLabels: boolean | null; // Tristate: null means auto
showLocalTime: boolean;
showUtc: boolean;
onClickLabel?: (label: string, value: string) => void;
}
function Row({ onClickLabel, row, showLabels, showLocalTime, showUtc }: RowProps) {
const needsHighlighter = row.searchWords && row.searchWords.length > 0;
return (
<div className="logs-row">
<div className={row.logLevel ? `logs-row-level logs-row-level-${row.logLevel}` : ''}>
{row.duplicates > 0 && (
<div className="logs-row-level__duplicates" title={`${row.duplicates} duplicates`}>
{Array.apply(null, { length: row.duplicates }).map((bogus, index) => (
<div className="logs-row-level__duplicate" key={`${index}`} />
))}
</div>
)}
</div>
{showUtc && (
<div className="logs-row-time" title={`Local: ${row.timeLocal} (${row.timeFromNow})`}>
{row.timestamp}
</div>
)}
{showLocalTime && (
<div className="logs-row-time" title={`${row.timestamp} (${row.timeFromNow})`}>
{row.timeLocal}
</div>
)}
{showLabels && (
<div className="logs-row-labels">
<Labels labels={row.uniqueLabels} onClickLabel={onClickLabel} />
</div>
)}
<div className="logs-row-message">
{needsHighlighter ? (
<Highlighter
textToHighlight={row.entry}
searchWords={row.searchWords}
findChunks={findHighlightChunksInText}
highlightClassName="logs-row-match-highlight"
/>
) : (
row.entry
)}
</div>
</div>
);
}
interface LogsProps {
className?: string;
data: LogsModel;
loading: boolean;
position: string;
range?: RawTimeRange;
scanning?: boolean;
scanRange?: RawTimeRange;
onChangeTime?: (range: RawTimeRange) => void;
onClickLabel?: (label: string, value: string) => void;
onStartScanning?: () => void;
onStopScanning?: () => void;
}
interface LogsState {
dedup: LogsDedupStrategy;
deferLogs: boolean;
hiddenLogLevels: Set<LogLevel>;
renderAll: boolean;
showLabels: boolean | null; // Tristate: null means auto
showLocalTime: boolean;
showUtc: boolean;
}
export default class Logs extends PureComponent<LogsProps, LogsState> {
deferLogsTimer: NodeJS.Timer;
renderAllTimer: NodeJS.Timer;
state = {
dedup: LogsDedupStrategy.none,
deferLogs: true,
hiddenLogLevels: new Set(),
renderAll: false,
showLabels: null,
showLocalTime: true,
showUtc: false,
};
componentDidMount() {
// Staged rendering
if (this.state.deferLogs) {
const { data } = this.props;
const rowCount = data && data.rows ? data.rows.length : 0;
// Render all right away if not too far over the limit
const renderAll = rowCount <= PREVIEW_LIMIT * 2;
this.deferLogsTimer = setTimeout(() => this.setState({ deferLogs: false, renderAll }), rowCount);
}
}
componentDidUpdate(prevProps, prevState) {
// Staged rendering
if (prevState.deferLogs && !this.state.deferLogs && !this.state.renderAll) {
this.renderAllTimer = setTimeout(() => this.setState({ renderAll: true }), 2000);
}
}
componentWillUnmount() {
clearTimeout(this.deferLogsTimer);
clearTimeout(this.renderAllTimer);
}
onChangeDedup = (dedup: LogsDedupStrategy) => {
this.setState(prevState => {
if (prevState.dedup === dedup) {
return { dedup: LogsDedupStrategy.none };
}
return { dedup };
});
};
onChangeLabels = (event: React.SyntheticEvent) => {
const target = event.target as HTMLInputElement;
this.setState({
showLabels: target.checked,
});
};
onChangeLocalTime = (event: React.SyntheticEvent) => {
const target = event.target as HTMLInputElement;
this.setState({
showLocalTime: target.checked,
});
};
onChangeUtc = (event: React.SyntheticEvent) => {
const target = event.target as HTMLInputElement;
this.setState({
showUtc: target.checked,
});
};
onToggleLogLevel = (rawLevel: string, hiddenRawLevels: Set<string>) => {
const hiddenLogLevels: Set<LogLevel> = new Set(Array.from(hiddenRawLevels).map(level => LogLevel[level]));
this.setState({ hiddenLogLevels });
};
onClickScan = (event: React.SyntheticEvent) => {
event.preventDefault();
this.props.onStartScanning();
};
onClickStopScan = (event: React.SyntheticEvent) => {
event.preventDefault();
this.props.onStopScanning();
};
render() {
const { className = '', data, loading = false, onClickLabel, position, range, scanning, scanRange } = this.props;
const { dedup, deferLogs, hiddenLogLevels, renderAll, showLocalTime, showUtc } = this.state;
let { showLabels } = this.state;
const hasData = data && data.rows && data.rows.length > 0;
// Filtering
const filteredData = filterLogLevels(data, hiddenLogLevels);
const dedupedData = dedupLogRows(filteredData, dedup);
const dedupCount = dedupedData.rows.reduce((sum, row) => sum + row.duplicates, 0);
const meta = [...data.meta];
if (dedup !== LogsDedupStrategy.none) {
meta.push({
label: 'Dedup count',
value: dedupCount,
kind: LogsMetaKind.Number,
});
}
// Staged rendering
const firstRows = dedupedData.rows.slice(0, PREVIEW_LIMIT);
const lastRows = dedupedData.rows.slice(PREVIEW_LIMIT);
// Check for labels
if (showLabels === null) {
if (hasData) {
showLabels = data.rows.some(row => _.size(row.uniqueLabels) > 0);
} else {
showLabels = true;
}
}
const scanText = scanRange ? `Scanning ${rangeUtil.describeTimeRange(scanRange)}` : 'Scanning...';
return (
<div className={`${className} logs`}>
<div className="logs-graph">
<Graph
data={data.series}
height="100px"
range={range}
id={`explore-logs-graph-${position}`}
onChangeTime={this.props.onChangeTime}
onToggleSeries={this.onToggleLogLevel}
userOptions={graphOptions}
/>
</div>
<div className="logs-options">
<div className="logs-controls">
<Switch label="Timestamp" checked={showUtc} onChange={this.onChangeUtc} small />
<Switch label="Local time" checked={showLocalTime} onChange={this.onChangeLocalTime} small />
<Switch label="Labels" checked={showLabels} onChange={this.onChangeLabels} small />
<Switch
label="Dedup: off"
checked={dedup === LogsDedupStrategy.none}
onChange={() => this.onChangeDedup(LogsDedupStrategy.none)}
small
/>
<Switch
label="Dedup: exact"
checked={dedup === LogsDedupStrategy.exact}
onChange={() => this.onChangeDedup(LogsDedupStrategy.exact)}
small
/>
<Switch
label="Dedup: numbers"
checked={dedup === LogsDedupStrategy.numbers}
onChange={() => this.onChangeDedup(LogsDedupStrategy.numbers)}
small
/>
<Switch
label="Dedup: signature"
checked={dedup === LogsDedupStrategy.signature}
onChange={() => this.onChangeDedup(LogsDedupStrategy.signature)}
small
/>
{hasData &&
meta && (
<div className="logs-meta">
{meta.map(item => (
<div className="logs-meta-item" key={item.label}>
<span className="logs-meta-item__label">{item.label}:</span>
<span className="logs-meta-item__value">{renderMetaItem(item.value, item.kind)}</span>
</div>
))}
</div>
)}
</div>
</div>
<div className="logs-entries">
{hasData &&
!deferLogs &&
firstRows.map(row => (
<Row
key={row.key + row.duplicates}
row={row}
showLabels={showLabels}
showLocalTime={showLocalTime}
showUtc={showUtc}
onClickLabel={onClickLabel}
/>
))}
{hasData &&
!deferLogs &&
renderAll &&
lastRows.map(row => (
<Row
key={row.key + row.duplicates}
row={row}
showLabels={showLabels}
showLocalTime={showLocalTime}
showUtc={showUtc}
onClickLabel={onClickLabel}
/>
))}
{hasData && deferLogs && <span>Rendering {dedupedData.rows.length} rows...</span>}
</div>
{!loading &&
data.queryEmpty &&
!scanning && (
<div className="logs-nodata">
No logs found.
<a className="link" onClick={this.onClickScan}>
Scan for older logs
</a>
</div>
)}
{scanning && (
<div className="logs-nodata">
<span>{scanText}</span>
<a className="link" onClick={this.onClickStopScan}>
Stop scan
</a>
</div>
)}
</div>
);
}
}
| public/app/features/explore/Logs.tsx | 1 | https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967 | [
0.0007682970026507974,
0.00020364896045066416,
0.00016516211326234043,
0.00017233510152436793,
0.00010892726277234033
]
|
{
"id": 0,
"code_window": [
"\n",
" async runQueries(resultType: ResultType, queryOptions: any, resultGetter?: any) {\n",
" const queries = [...this.modifiedQueries];\n",
" if (!hasNonEmptyQuery(queries)) {\n",
" return;\n",
" }\n",
" const { datasource } = this.state;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.setState({\n",
" queryTransactions: [],\n",
" });\n"
],
"file_path": "public/app/features/explore/Explore.tsx",
"type": "add",
"edit_start_line_idx": 773
} | <div class="edit-tab-with-sidemenu" ng-if="ctrl.alert">
<aside class="edit-sidemenu-aside">
<ul class="edit-sidemenu">
<li ng-class="{active: ctrl.subTabIndex === 0}">
<a ng-click="ctrl.changeTabIndex(0)">Alert Config</a>
</li>
<li ng-class="{active: ctrl.subTabIndex === 1}">
<a ng-click="ctrl.changeTabIndex(1)">
Notifications <span class="muted">({{ctrl.alertNotifications.length}})</span>
</a>
</li>
<li ng-class="{active: ctrl.subTabIndex === 2}">
<a ng-click="ctrl.changeTabIndex(2)">State history</a>
</li>
<li>
<a ng-click="ctrl.delete()">Delete</a>
</li>
</ul>
</aside>
<div class="edit-tab-content">
<div ng-if="ctrl.subTabIndex === 0">
<div class="alert alert-error m-b-2" ng-show="ctrl.error">
<i class="fa fa-warning"></i> {{ctrl.error}}
</div>
<div class="gf-form-group">
<h5 class="section-heading">Alert Config</h5>
<div class="gf-form">
<span class="gf-form-label width-6">Name</span>
<input type="text" class="gf-form-input width-20" ng-model="ctrl.alert.name">
</div>
<div class="gf-form-inline">
<div class="gf-form">
<span class="gf-form-label width-9">Evaluate every</span>
<input class="gf-form-input max-width-6" type="text" ng-model="ctrl.alert.frequency">
</div>
<div class="gf-form max-width-11">
<label class="gf-form-label width-5">For</label>
<input type="text" class="gf-form-input max-width-6" ng-model="ctrl.alert.for" spellcheck='false' placeholder="5m">
<info-popover mode="right-absolute">
If an alert rule has a configured For and the query violates the configured threshold it will first go from OK to Pending.
Going from OK to Pending Grafana will not send any notifications. Once the alert rule has been firing for more than For duration, it will change to Alerting and send alert notifications.
</info-popover>
</div>
</div>
</div>
<div class="gf-form-group">
<h5 class="section-heading">Conditions</h5>
<div class="gf-form-inline" ng-repeat="conditionModel in ctrl.conditionModels">
<div class="gf-form">
<metric-segment-model css-class="query-keyword width-5" ng-if="$index" property="conditionModel.operator.type" options="ctrl.evalOperators" custom="false"></metric-segment-model>
<span class="gf-form-label query-keyword width-5" ng-if="$index===0">WHEN</span>
</div>
<div class="gf-form">
<query-part-editor class="gf-form-label query-part width-9" part="conditionModel.reducerPart" handle-event="ctrl.handleReducerPartEvent(conditionModel, $event)">
</query-part-editor>
<span class="gf-form-label query-keyword">OF</span>
</div>
<div class="gf-form">
<query-part-editor class="gf-form-label query-part" part="conditionModel.queryPart" handle-event="ctrl.handleQueryPartEvent(conditionModel, $event)">
</query-part-editor>
</div>
<div class="gf-form">
<metric-segment-model property="conditionModel.evaluator.type" options="ctrl.evalFunctions" custom="false" css-class="query-keyword" on-change="ctrl.evaluatorTypeChanged(conditionModel.evaluator)"></metric-segment-model>
<input class="gf-form-input max-width-9" type="number" step="any" ng-hide="conditionModel.evaluator.params.length === 0" ng-model="conditionModel.evaluator.params[0]" ng-change="ctrl.evaluatorParamsChanged()">
<label class="gf-form-label query-keyword" ng-show="conditionModel.evaluator.params.length === 2">TO</label>
<input class="gf-form-input max-width-9" type="number" step="any" ng-if="conditionModel.evaluator.params.length === 2" ng-model="conditionModel.evaluator.params[1]" ng-change="ctrl.evaluatorParamsChanged()">
</div>
<div class="gf-form">
<label class="gf-form-label">
<a class="pointer" tabindex="1" ng-click="ctrl.removeCondition($index)">
<i class="fa fa-trash"></i>
</a>
</label>
</div>
</div>
<div class="gf-form">
<label class="gf-form-label dropdown">
<a class="pointer dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-plus"></i>
</a>
<ul class="dropdown-menu" role="menu">
<li ng-repeat="ct in ctrl.conditionTypes" role="menuitem">
<a ng-click="ctrl.addCondition(ct.value);">{{ct.text}}</a>
</li>
</ul>
</label>
</div>
</div>
<div class="gf-form-group">
<div class="gf-form">
<span class="gf-form-label width-18">If no data or all values are null</span>
<span class="gf-form-label query-keyword">SET STATE TO</span>
<div class="gf-form-select-wrapper">
<select class="gf-form-input" ng-model="ctrl.alert.noDataState" ng-options="f.value as f.text for f in ctrl.noDataModes">
</select>
</div>
</div>
<div class="gf-form">
<span class="gf-form-label width-18">If execution error or timeout</span>
<span class="gf-form-label query-keyword">SET STATE TO</span>
<div class="gf-form-select-wrapper">
<select class="gf-form-input" ng-model="ctrl.alert.executionErrorState" ng-options="f.value as f.text for f in ctrl.executionErrorModes">
</select>
</div>
</div>
<div class="gf-form-button-row">
<button class="btn btn-inverse" ng-click="ctrl.test()">
Test Rule
</button>
</div>
</div>
<div class="gf-form-group" ng-if="ctrl.testing">
Evaluating rule <i class="fa fa-spinner fa-spin"></i>
</div>
<div class="gf-form-group" ng-if="ctrl.testResult">
<json-tree root-name="result" object="ctrl.testResult" start-expanded="true"></json-tree>
</div>
</div>
<div class="gf-form-group" ng-if="ctrl.subTabIndex === 1">
<h5 class="section-heading">Notifications</h5>
<div class="gf-form-inline">
<div class="gf-form max-width-30">
<span class="gf-form-label width-8">Send to</span>
<span class="gf-form-label" ng-repeat="nc in ctrl.alertNotifications" ng-style="{'background-color': nc.bgColor }">
<i class="{{nc.iconClass}}"></i> {{nc.name}}
<i class="fa fa-remove pointer muted" ng-click="ctrl.removeNotification($index)" ng-if="nc.isDefault === false"></i>
</span>
<metric-segment segment="ctrl.addNotificationSegment" get-options="ctrl.getNotifications()" on-change="ctrl.notificationAdded()"></metric-segment>
</div>
</div>
<div class="gf-form gf-form--v-stretch">
<span class="gf-form-label width-8">Message</span>
<textarea class="gf-form-input" rows="10" ng-model="ctrl.alert.message" placeholder="Notification message details..."></textarea>
</div>
</div>
<div class="gf-form-group" style="max-width: 720px;" ng-if="ctrl.subTabIndex === 2">
<button class="btn btn-mini btn-danger pull-right" ng-click="ctrl.clearHistory()"><i class="fa fa-trash"></i> Clear history</button>
<h5 class="section-heading" style="whitespace: nowrap">
State history <span class="muted small">(last 50 state changes)</span>
</h5>
<div ng-show="ctrl.alertHistory.length === 0">
<br>
<i>No state changes recorded</i>
</div>
<ol class="alert-rule-list" >
<li class="alert-rule-item" ng-repeat="al in ctrl.alertHistory">
<div class="alert-rule-item__icon {{al.stateModel.stateClass}}">
<i class="{{al.stateModel.iconClass}}"></i>
</div>
<div class="alert-rule-item__body">
<div class="alert-rule-item__header">
<div class="alert-rule-item__text">
<span class="{{al.stateModel.stateClass}}">{{al.stateModel.text}}</span>
</div>
</div>
<span class="alert-list-info">{{al.info}}</span>
</div>
<div class="alert-rule-item__time">
<span>{{al.time}}</span>
</div>
</li>
</ol>
</div>
</div>
</div>
<div class="gf-form-group" ng-if="!ctrl.alert">
<div class="gf-form-button-row">
<button class="btn btn-inverse" ng-click="ctrl.enable()">
<i class="icon-gf icon-gf-alert"></i>
Create Alert
</button>
</div>
</div>
| public/app/features/alerting/partials/alert_tab.html | 0 | https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967 | [
0.00017554109217599034,
0.0001706518669379875,
0.00016480658086948097,
0.00017152017971966416,
0.0000031568424674333073
]
|
{
"id": 0,
"code_window": [
"\n",
" async runQueries(resultType: ResultType, queryOptions: any, resultGetter?: any) {\n",
" const queries = [...this.modifiedQueries];\n",
" if (!hasNonEmptyQuery(queries)) {\n",
" return;\n",
" }\n",
" const { datasource } = this.state;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.setState({\n",
" queryTransactions: [],\n",
" });\n"
],
"file_path": "public/app/features/explore/Explore.tsx",
"type": "add",
"edit_start_line_idx": 773
} | // Autogenerated by Thrift Compiler (0.9.3)
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
package baggage
import (
"bytes"
"fmt"
"github.com/uber/jaeger-client-go/thrift"
)
// (needed to ensure safety because of naive import list construction.)
var _ = thrift.ZERO
var _ = fmt.Printf
var _ = bytes.Equal
func init() {
}
| vendor/github.com/uber/jaeger-client-go/thrift-gen/baggage/constants.go | 0 | https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967 | [
0.00017412261513527483,
0.00017148132610600442,
0.000168840037076734,
0.00017148132610600442,
0.0000026412890292704105
]
|
{
"id": 0,
"code_window": [
"\n",
" async runQueries(resultType: ResultType, queryOptions: any, resultGetter?: any) {\n",
" const queries = [...this.modifiedQueries];\n",
" if (!hasNonEmptyQuery(queries)) {\n",
" return;\n",
" }\n",
" const { datasource } = this.state;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.setState({\n",
" queryTransactions: [],\n",
" });\n"
],
"file_path": "public/app/features/explore/Explore.tsx",
"type": "add",
"edit_start_line_idx": 773
} | The following files were ported to Go from C files of libyaml, and thus
are still covered by their original copyright and license:
apic.go
emitterc.go
parserc.go
readerc.go
scannerc.go
writerc.go
yamlh.go
yamlprivateh.go
Copyright (c) 2006 Kirill Simonov
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
| vendor/gopkg.in/yaml.v2/LICENSE.libyaml | 0 | https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967 | [
0.00017814589955378324,
0.00017564975132700056,
0.00017217858112417161,
0.00017613728414289653,
0.000002548262045820593
]
|
{
"id": 1,
"code_window": [
" const selectedDatasource = datasource ? exploreDatasources.find(d => d.label === datasource.name) : undefined;\n",
" const graphLoading = queryTransactions.some(qt => qt.resultType === 'Graph' && !qt.done);\n",
" const tableLoading = queryTransactions.some(qt => qt.resultType === 'Table' && !qt.done);\n",
" const logsLoading = queryTransactions.some(qt => qt.resultType === 'Logs' && !qt.done);\n",
" const loading = queryTransactions.some(qt => !qt.done);\n",
"\n",
" return (\n",
" <div className={exploreClass} ref={this.getRef}>\n",
" <div className=\"navbar\">\n",
" {position === 'left' ? (\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const queryEmpty = queryTransactions.some(qt => qt.resultType === 'Logs' && qt.done && qt.result.length === 0);\n"
],
"file_path": "public/app/features/explore/Explore.tsx",
"type": "add",
"edit_start_line_idx": 839
} | import React from 'react';
import { hot } from 'react-hot-loader';
import Select from 'react-select';
import _ from 'lodash';
import { DataSource } from 'app/types/datasources';
import {
ExploreState,
ExploreUrlState,
QueryTransaction,
ResultType,
QueryHintGetter,
QueryHint,
} from 'app/types/explore';
import { RawTimeRange, DataQuery } from 'app/types/series';
import store from 'app/core/store';
import {
DEFAULT_RANGE,
calculateResultsFromQueryTransactions,
ensureQueries,
getIntervals,
generateKey,
generateQueryKeys,
hasNonEmptyQuery,
makeTimeSeriesList,
updateHistory,
} from 'app/core/utils/explore';
import ResetStyles from 'app/core/components/Picker/ResetStyles';
import PickerOption from 'app/core/components/Picker/PickerOption';
import IndicatorsContainer from 'app/core/components/Picker/IndicatorsContainer';
import NoOptionsMessage from 'app/core/components/Picker/NoOptionsMessage';
import TableModel from 'app/core/table_model';
import { DatasourceSrv } from 'app/features/plugins/datasource_srv';
import Panel from './Panel';
import QueryRows from './QueryRows';
import Graph from './Graph';
import Logs from './Logs';
import Table from './Table';
import ErrorBoundary from './ErrorBoundary';
import TimePicker from './TimePicker';
interface ExploreProps {
datasourceSrv: DatasourceSrv;
onChangeSplit: (split: boolean, state?: ExploreState) => void;
onSaveState: (key: string, state: ExploreState) => void;
position: string;
split: boolean;
splitState?: ExploreState;
stateKey: string;
urlState: ExploreUrlState;
}
/**
* Explore provides an area for quick query iteration for a given datasource.
* Once a datasource is selected it populates the query section at the top.
* When queries are run, their results are being displayed in the main section.
* The datasource determines what kind of query editor it brings, and what kind
* of results viewers it supports.
*
* QUERY HANDLING
*
* TLDR: to not re-render Explore during edits, query editing is not "controlled"
* in a React sense: values need to be pushed down via `initialQueries`, while
* edits travel up via `this.modifiedQueries`.
*
* By default the query rows start without prior state: `initialQueries` will
* contain one empty DataQuery. While the user modifies the DataQuery, the
* modifications are being tracked in `this.modifiedQueries`, which need to be
* used whenever a query is sent to the datasource to reflect what the user sees
* on the screen. Query rows can be initialized or reset using `initialQueries`,
* by giving the respective row a new key. This wipes the old row and its state.
* This property is also used to govern how many query rows there are (minimum 1).
*
* This flow makes sure that a query row can be arbitrarily complex without the
* fear of being wiped or re-initialized via props. The query row is free to keep
* its own state while the user edits or builds a query. Valid queries can be sent
* up to Explore via the `onChangeQuery` prop.
*
* DATASOURCE REQUESTS
*
* A click on Run Query creates transactions for all DataQueries for all expanded
* result viewers. New runs are discarding previous runs. Upon completion a transaction
* saves the result. The result viewers construct their data from the currently existing
* transactions.
*
* The result viewers determine some of the query options sent to the datasource, e.g.,
* `format`, to indicate eventual transformations by the datasources' result transformers.
*/
export class Explore extends React.PureComponent<ExploreProps, ExploreState> {
el: any;
/**
* Current query expressions of the rows including their modifications, used for running queries.
* Not kept in component state to prevent edit-render roundtrips.
*/
modifiedQueries: DataQuery[];
/**
* Local ID cache to compare requested vs selected datasource
*/
requestedDatasourceId: string;
scanTimer: NodeJS.Timer;
/**
* Timepicker to control scanning
*/
timepickerRef: React.RefObject<TimePicker>;
constructor(props) {
super(props);
const splitState: ExploreState = props.splitState;
let initialQueries: DataQuery[];
if (splitState) {
// Split state overrides everything
this.state = splitState;
initialQueries = splitState.initialQueries;
} else {
const { datasource, queries, range } = props.urlState as ExploreUrlState;
initialQueries = ensureQueries(queries);
const initialRange = range || { ...DEFAULT_RANGE };
// Millies step for helper bar charts
const initialGraphInterval = 15 * 1000;
this.state = {
datasource: null,
datasourceError: null,
datasourceLoading: null,
datasourceMissing: false,
datasourceName: datasource,
exploreDatasources: [],
graphInterval: initialGraphInterval,
graphResult: [],
initialQueries,
history: [],
logsResult: null,
queryTransactions: [],
range: initialRange,
scanning: false,
showingGraph: true,
showingLogs: true,
showingStartPage: false,
showingTable: true,
supportsGraph: null,
supportsLogs: null,
supportsTable: null,
tableResult: new TableModel(),
};
}
this.modifiedQueries = initialQueries.slice();
this.timepickerRef = React.createRef();
}
async componentDidMount() {
const { datasourceSrv } = this.props;
const { datasourceName } = this.state;
if (!datasourceSrv) {
throw new Error('No datasource service passed as props.');
}
const datasources = datasourceSrv.getExploreSources();
const exploreDatasources = datasources.map(ds => ({
value: ds.name,
label: ds.name,
}));
if (datasources.length > 0) {
this.setState({ datasourceLoading: true, exploreDatasources });
// Priority: datasource in url, default datasource, first explore datasource
let datasource;
if (datasourceName) {
datasource = await datasourceSrv.get(datasourceName);
} else {
datasource = await datasourceSrv.get();
}
if (!datasource.meta.explore) {
datasource = await datasourceSrv.get(datasources[0].name);
}
await this.setDatasource(datasource);
} else {
this.setState({ datasourceMissing: true });
}
}
componentWillUnmount() {
clearTimeout(this.scanTimer);
}
async setDatasource(datasource: any, origin?: DataSource) {
const { initialQueries, range } = this.state;
const supportsGraph = datasource.meta.metrics;
const supportsLogs = datasource.meta.logs;
const supportsTable = datasource.meta.metrics;
const datasourceId = datasource.meta.id;
let datasourceError = null;
// Keep ID to track selection
this.requestedDatasourceId = datasourceId;
try {
const testResult = await datasource.testDatasource();
datasourceError = testResult.status === 'success' ? null : testResult.message;
} catch (error) {
datasourceError = (error && error.statusText) || 'Network error';
}
if (datasourceId !== this.requestedDatasourceId) {
// User already changed datasource again, discard results
return;
}
const historyKey = `grafana.explore.history.${datasourceId}`;
const history = store.getObject(historyKey, []);
if (datasource.init) {
datasource.init();
}
// Check if queries can be imported from previously selected datasource
let modifiedQueries = this.modifiedQueries;
if (origin) {
if (origin.meta.id === datasource.meta.id) {
// Keep same queries if same type of datasource
modifiedQueries = [...this.modifiedQueries];
} else if (datasource.importQueries) {
// Datasource-specific importers
modifiedQueries = await datasource.importQueries(this.modifiedQueries, origin.meta);
} else {
// Default is blank queries
modifiedQueries = ensureQueries();
}
}
// Reset edit state with new queries
const nextQueries = initialQueries.map((q, i) => ({
...modifiedQueries[i],
...generateQueryKeys(i),
}));
this.modifiedQueries = modifiedQueries;
// Custom components
const StartPage = datasource.pluginExports.ExploreStartPage;
// Calculate graph bucketing interval
const graphInterval = getIntervals(range, datasource, this.el ? this.el.offsetWidth : 0).intervalMs;
this.setState(
{
StartPage,
datasource,
datasourceError,
graphInterval,
history,
supportsGraph,
supportsLogs,
supportsTable,
datasourceLoading: false,
datasourceName: datasource.name,
initialQueries: nextQueries,
showingStartPage: Boolean(StartPage),
},
() => {
if (datasourceError === null) {
this.onSubmit();
}
}
);
}
getRef = el => {
this.el = el;
};
onAddQueryRow = index => {
// Local cache
this.modifiedQueries[index + 1] = { ...generateQueryKeys(index + 1) };
this.setState(state => {
const { initialQueries, queryTransactions } = state;
const nextQueries = [
...initialQueries.slice(0, index + 1),
{ ...this.modifiedQueries[index + 1] },
...initialQueries.slice(index + 1),
];
// Ongoing transactions need to update their row indices
const nextQueryTransactions = queryTransactions.map(qt => {
if (qt.rowIndex > index) {
return {
...qt,
rowIndex: qt.rowIndex + 1,
};
}
return qt;
});
return { initialQueries: nextQueries, queryTransactions: nextQueryTransactions };
});
};
onChangeDatasource = async option => {
const origin = this.state.datasource;
this.setState({
datasource: null,
datasourceError: null,
datasourceLoading: true,
queryTransactions: [],
});
const datasourceName = option.value;
const datasource = await this.props.datasourceSrv.get(datasourceName);
this.setDatasource(datasource as any, origin);
};
onChangeQuery = (value: DataQuery, index: number, override?: boolean) => {
// Null value means reset
if (value === null) {
value = { ...generateQueryKeys(index) };
}
// Keep current value in local cache
this.modifiedQueries[index] = value;
if (override) {
this.setState(state => {
// Replace query row by injecting new key
const { initialQueries, queryTransactions } = state;
const query: DataQuery = {
...value,
...generateQueryKeys(index),
};
const nextQueries = [...initialQueries];
nextQueries[index] = query;
this.modifiedQueries = [...nextQueries];
// Discard ongoing transaction related to row query
const nextQueryTransactions = queryTransactions.filter(qt => qt.rowIndex !== index);
return {
initialQueries: nextQueries,
queryTransactions: nextQueryTransactions,
};
}, this.onSubmit);
}
};
onChangeTime = (nextRange: RawTimeRange, scanning?: boolean) => {
const range: RawTimeRange = {
...nextRange,
};
if (this.state.scanning && !scanning) {
this.onStopScanning();
}
this.setState({ range, scanning }, () => this.onSubmit());
};
onClickClear = () => {
this.modifiedQueries = ensureQueries();
this.setState(
prevState => ({
initialQueries: [...this.modifiedQueries],
queryTransactions: [],
showingStartPage: Boolean(prevState.StartPage),
}),
this.saveState
);
};
onClickCloseSplit = () => {
const { onChangeSplit } = this.props;
if (onChangeSplit) {
onChangeSplit(false);
}
};
onClickGraphButton = () => {
this.setState(
state => {
const showingGraph = !state.showingGraph;
let nextQueryTransactions = state.queryTransactions;
if (!showingGraph) {
// Discard transactions related to Graph query
nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Graph');
}
return { queryTransactions: nextQueryTransactions, showingGraph };
},
() => {
if (this.state.showingGraph) {
this.onSubmit();
}
}
);
};
onClickLogsButton = () => {
this.setState(
state => {
const showingLogs = !state.showingLogs;
let nextQueryTransactions = state.queryTransactions;
if (!showingLogs) {
// Discard transactions related to Logs query
nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Logs');
}
return { queryTransactions: nextQueryTransactions, showingLogs };
},
() => {
if (this.state.showingLogs) {
this.onSubmit();
}
}
);
};
// Use this in help pages to set page to a single query
onClickExample = (query: DataQuery) => {
const nextQueries = [{ ...query, ...generateQueryKeys() }];
this.modifiedQueries = [...nextQueries];
this.setState({ initialQueries: nextQueries }, this.onSubmit);
};
onClickSplit = () => {
const { onChangeSplit } = this.props;
if (onChangeSplit) {
const state = this.cloneState();
onChangeSplit(true, state);
}
};
onClickTableButton = () => {
this.setState(
state => {
const showingTable = !state.showingTable;
if (showingTable) {
return { showingTable, queryTransactions: state.queryTransactions };
}
// Toggle off needs discarding of table queries
const nextQueryTransactions = state.queryTransactions.filter(qt => qt.resultType !== 'Table');
const results = calculateResultsFromQueryTransactions(
nextQueryTransactions,
state.datasource,
state.graphInterval
);
return { ...results, queryTransactions: nextQueryTransactions, showingTable };
},
() => {
if (this.state.showingTable) {
this.onSubmit();
}
}
);
};
onClickLabel = (key: string, value: string) => {
this.onModifyQueries({ type: 'ADD_FILTER', key, value });
};
onModifyQueries = (action, index?: number) => {
const { datasource } = this.state;
if (datasource && datasource.modifyQuery) {
const preventSubmit = action.preventSubmit;
this.setState(
state => {
const { initialQueries, queryTransactions } = state;
let nextQueries: DataQuery[];
let nextQueryTransactions;
if (index === undefined) {
// Modify all queries
nextQueries = initialQueries.map((query, i) => ({
...datasource.modifyQuery(this.modifiedQueries[i], action),
...generateQueryKeys(i),
}));
// Discard all ongoing transactions
nextQueryTransactions = [];
} else {
// Modify query only at index
nextQueries = initialQueries.map((query, i) => {
// Synchronise all queries with local query cache to ensure consistency
// TODO still needed?
return i === index
? {
...datasource.modifyQuery(this.modifiedQueries[i], action),
...generateQueryKeys(i),
}
: query;
});
nextQueryTransactions = queryTransactions
// Consume the hint corresponding to the action
.map(qt => {
if (qt.hints != null && qt.rowIndex === index) {
qt.hints = qt.hints.filter(hint => hint.fix.action !== action);
}
return qt;
})
// Preserve previous row query transaction to keep results visible if next query is incomplete
.filter(qt => preventSubmit || qt.rowIndex !== index);
}
this.modifiedQueries = [...nextQueries];
return {
initialQueries: nextQueries,
queryTransactions: nextQueryTransactions,
};
},
// Accepting certain fixes do not result in a well-formed query which should not be submitted
!preventSubmit ? () => this.onSubmit() : null
);
}
};
onRemoveQueryRow = index => {
// Remove from local cache
this.modifiedQueries = [...this.modifiedQueries.slice(0, index), ...this.modifiedQueries.slice(index + 1)];
this.setState(
state => {
const { initialQueries, queryTransactions } = state;
if (initialQueries.length <= 1) {
return null;
}
// Remove row from react state
const nextQueries = [...initialQueries.slice(0, index), ...initialQueries.slice(index + 1)];
// Discard transactions related to row query
const nextQueryTransactions = queryTransactions.filter(qt => qt.rowIndex !== index);
const results = calculateResultsFromQueryTransactions(
nextQueryTransactions,
state.datasource,
state.graphInterval
);
return {
...results,
initialQueries: nextQueries,
queryTransactions: nextQueryTransactions,
};
},
() => this.onSubmit()
);
};
onStartScanning = () => {
this.setState({ scanning: true }, this.scanPreviousRange);
};
scanPreviousRange = () => {
const scanRange = this.timepickerRef.current.move(-1, true);
this.setState({ scanRange });
};
onStopScanning = () => {
clearTimeout(this.scanTimer);
this.setState(state => {
const { queryTransactions } = state;
const nextQueryTransactions = queryTransactions.filter(qt => qt.scanning && !qt.done);
return { queryTransactions: nextQueryTransactions, scanning: false, scanRange: undefined };
});
};
onSubmit = () => {
const { showingLogs, showingGraph, showingTable, supportsGraph, supportsLogs, supportsTable } = this.state;
// Keep table queries first since they need to return quickly
if (showingTable && supportsTable) {
this.runQueries(
'Table',
{
format: 'table',
instant: true,
valueWithRefId: true,
},
data => data[0]
);
}
if (showingGraph && supportsGraph) {
this.runQueries(
'Graph',
{
format: 'time_series',
instant: false,
},
makeTimeSeriesList
);
}
if (showingLogs && supportsLogs) {
this.runQueries('Logs', { format: 'logs' });
}
this.saveState();
};
buildQueryOptions(query: DataQuery, queryOptions: { format: string; hinting?: boolean; instant?: boolean }) {
const { datasource, range } = this.state;
const { interval, intervalMs } = getIntervals(range, datasource, this.el.offsetWidth);
const configuredQueries = [
{
...query,
...queryOptions,
},
];
// Clone range for query request
const queryRange: RawTimeRange = { ...range };
// Datasource is using `panelId + query.refId` for cancellation logic.
// Using `format` here because it relates to the view panel that the request is for.
const panelId = queryOptions.format;
return {
interval,
intervalMs,
panelId,
targets: configuredQueries, // Datasources rely on DataQueries being passed under the targets key.
range: queryRange,
};
}
startQueryTransaction(query: DataQuery, rowIndex: number, resultType: ResultType, options: any): QueryTransaction {
const queryOptions = this.buildQueryOptions(query, options);
const transaction: QueryTransaction = {
query,
resultType,
rowIndex,
id: generateKey(), // reusing for unique ID
done: false,
latency: 0,
options: queryOptions,
scanning: this.state.scanning,
};
// Using updater style because we might be modifying queryTransactions in quick succession
this.setState(state => {
const { queryTransactions } = state;
// Discarding existing transactions of same type
const remainingTransactions = queryTransactions.filter(
qt => !(qt.resultType === resultType && qt.rowIndex === rowIndex)
);
// Append new transaction
const nextQueryTransactions = [...remainingTransactions, transaction];
const results = calculateResultsFromQueryTransactions(
nextQueryTransactions,
state.datasource,
state.graphInterval
);
return {
...results,
queryTransactions: nextQueryTransactions,
showingStartPage: false,
};
});
return transaction;
}
completeQueryTransaction(
transactionId: string,
result: any,
latency: number,
queries: DataQuery[],
datasourceId: string
) {
const { datasource } = this.state;
if (datasource.meta.id !== datasourceId) {
// Navigated away, queries did not matter
return;
}
this.setState(state => {
const { history, queryTransactions, scanning } = state;
// Transaction might have been discarded
const transaction = queryTransactions.find(qt => qt.id === transactionId);
if (!transaction) {
return null;
}
// Get query hints
let hints: QueryHint[];
if (datasource.getQueryHints as QueryHintGetter) {
hints = datasource.getQueryHints(transaction.query, result);
}
// Mark transactions as complete
const nextQueryTransactions = queryTransactions.map(qt => {
if (qt.id === transactionId) {
return {
...qt,
hints,
latency,
result,
done: true,
};
}
return qt;
});
const results = calculateResultsFromQueryTransactions(
nextQueryTransactions,
state.datasource,
state.graphInterval
);
const nextHistory = updateHistory(history, datasourceId, queries);
// Keep scanning for results if this was the last scanning transaction
if (_.size(result) === 0 && scanning) {
const other = nextQueryTransactions.find(qt => qt.scanning && !qt.done);
if (!other) {
this.scanTimer = setTimeout(this.scanPreviousRange, 1000);
}
}
return {
...results,
history: nextHistory,
queryTransactions: nextQueryTransactions,
};
});
}
failQueryTransaction(transactionId: string, response: any, datasourceId: string) {
const { datasource } = this.state;
if (datasource.meta.id !== datasourceId || response.cancelled) {
// Navigated away, queries did not matter
return;
}
console.error(response);
let error: string | JSX.Element = response;
if (response.data) {
if (typeof response.data === 'string') {
error = response.data;
} else if (response.data.error) {
error = response.data.error;
if (response.data.response) {
error = (
<>
<span>{response.data.error}</span>
<details>{response.data.response}</details>
</>
);
}
} else {
throw new Error('Could not handle error response');
}
}
this.setState(state => {
// Transaction might have been discarded
if (!state.queryTransactions.find(qt => qt.id === transactionId)) {
return null;
}
// Mark transactions as complete
const nextQueryTransactions = state.queryTransactions.map(qt => {
if (qt.id === transactionId) {
return {
...qt,
error,
done: true,
};
}
return qt;
});
return {
queryTransactions: nextQueryTransactions,
};
});
}
async runQueries(resultType: ResultType, queryOptions: any, resultGetter?: any) {
const queries = [...this.modifiedQueries];
if (!hasNonEmptyQuery(queries)) {
return;
}
const { datasource } = this.state;
const datasourceId = datasource.meta.id;
// Run all queries concurrently
queries.forEach(async (query, rowIndex) => {
const transaction = this.startQueryTransaction(query, rowIndex, resultType, queryOptions);
try {
const now = Date.now();
const res = await datasource.query(transaction.options);
const latency = Date.now() - now;
const results = resultGetter ? resultGetter(res.data) : res.data;
this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId);
} catch (response) {
this.failQueryTransaction(transaction.id, response, datasourceId);
}
});
}
cloneState(): ExploreState {
// Copy state, but copy queries including modifications
return {
...this.state,
queryTransactions: [],
initialQueries: [...this.modifiedQueries],
};
}
saveState = () => {
const { stateKey, onSaveState } = this.props;
onSaveState(stateKey, this.cloneState());
};
render() {
const { position, split } = this.props;
const {
StartPage,
datasource,
datasourceError,
datasourceLoading,
datasourceMissing,
exploreDatasources,
graphResult,
history,
initialQueries,
logsResult,
queryTransactions,
range,
scanning,
scanRange,
showingGraph,
showingLogs,
showingStartPage,
showingTable,
supportsGraph,
supportsLogs,
supportsTable,
tableResult,
} = this.state;
const graphHeight = showingGraph && showingTable ? '200px' : '400px';
const exploreClass = split ? 'explore explore-split' : 'explore';
const selectedDatasource = datasource ? exploreDatasources.find(d => d.label === datasource.name) : undefined;
const graphLoading = queryTransactions.some(qt => qt.resultType === 'Graph' && !qt.done);
const tableLoading = queryTransactions.some(qt => qt.resultType === 'Table' && !qt.done);
const logsLoading = queryTransactions.some(qt => qt.resultType === 'Logs' && !qt.done);
const loading = queryTransactions.some(qt => !qt.done);
return (
<div className={exploreClass} ref={this.getRef}>
<div className="navbar">
{position === 'left' ? (
<div>
<a className="navbar-page-btn">
<i className="fa fa-rocket" />
Explore
</a>
</div>
) : (
<div className="navbar-buttons explore-first-button">
<button className="btn navbar-button" onClick={this.onClickCloseSplit}>
Close Split
</button>
</div>
)}
{!datasourceMissing ? (
<div className="navbar-buttons">
<Select
classNamePrefix={`gf-form-select-box`}
isMulti={false}
isLoading={datasourceLoading}
isClearable={false}
className="gf-form-input gf-form-input--form-dropdown datasource-picker"
onChange={this.onChangeDatasource}
options={exploreDatasources}
styles={ResetStyles}
placeholder="Select datasource"
loadingMessage={() => 'Loading datasources...'}
noOptionsMessage={() => 'No datasources found'}
value={selectedDatasource}
components={{
Option: PickerOption,
IndicatorsContainer,
NoOptionsMessage,
}}
/>
</div>
) : null}
<div className="navbar__spacer" />
{position === 'left' && !split ? (
<div className="navbar-buttons">
<button className="btn navbar-button" onClick={this.onClickSplit}>
Split
</button>
</div>
) : null}
<TimePicker ref={this.timepickerRef} range={range} onChangeTime={this.onChangeTime} />
<div className="navbar-buttons">
<button className="btn navbar-button navbar-button--no-icon" onClick={this.onClickClear}>
Clear All
</button>
</div>
<div className="navbar-buttons relative">
<button className="btn navbar-button--primary" onClick={this.onSubmit}>
Run Query{' '}
{loading ? <i className="fa fa-spinner fa-spin run-icon" /> : <i className="fa fa-level-down run-icon" />}
</button>
</div>
</div>
{datasourceLoading ? <div className="explore-container">Loading datasource...</div> : null}
{datasourceMissing ? (
<div className="explore-container">Please add a datasource that supports Explore (e.g., Prometheus).</div>
) : null}
{datasourceError ? (
<div className="explore-container">Error connecting to datasource. [{datasourceError}]</div>
) : null}
{datasource && !datasourceError ? (
<div className="explore-container">
<QueryRows
datasource={datasource}
history={history}
initialQueries={initialQueries}
onAddQueryRow={this.onAddQueryRow}
onChangeQuery={this.onChangeQuery}
onClickHintFix={this.onModifyQueries}
onExecuteQuery={this.onSubmit}
onRemoveQueryRow={this.onRemoveQueryRow}
transactions={queryTransactions}
/>
<main className="m-t-2">
<ErrorBoundary>
{showingStartPage && <StartPage onClickExample={this.onClickExample} />}
{!showingStartPage && (
<>
{supportsGraph && (
<Panel
label="Graph"
isOpen={showingGraph}
loading={graphLoading}
onToggle={this.onClickGraphButton}
>
<Graph
data={graphResult}
height={graphHeight}
id={`explore-graph-${position}`}
onChangeTime={this.onChangeTime}
range={range}
split={split}
/>
</Panel>
)}
{supportsTable && (
<Panel
label="Table"
loading={tableLoading}
isOpen={showingTable}
onToggle={this.onClickTableButton}
>
<Table data={tableResult} loading={tableLoading} onClickCell={this.onClickLabel} />
</Panel>
)}
{supportsLogs && (
<Panel label="Logs" loading={logsLoading} isOpen={showingLogs} onToggle={this.onClickLogsButton}>
<Logs
data={logsResult}
key={logsResult.id}
loading={logsLoading}
position={position}
onChangeTime={this.onChangeTime}
onClickLabel={this.onClickLabel}
onStartScanning={this.onStartScanning}
onStopScanning={this.onStopScanning}
range={range}
scanning={scanning}
scanRange={scanRange}
/>
</Panel>
)}
</>
)}
</ErrorBoundary>
</main>
</div>
) : null}
</div>
);
}
}
export default hot(module)(Explore);
| public/app/features/explore/Explore.tsx | 1 | https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967 | [
0.998749852180481,
0.07258962094783783,
0.00016253063222393394,
0.0014759183395653963,
0.25074896216392517
]
|
{
"id": 1,
"code_window": [
" const selectedDatasource = datasource ? exploreDatasources.find(d => d.label === datasource.name) : undefined;\n",
" const graphLoading = queryTransactions.some(qt => qt.resultType === 'Graph' && !qt.done);\n",
" const tableLoading = queryTransactions.some(qt => qt.resultType === 'Table' && !qt.done);\n",
" const logsLoading = queryTransactions.some(qt => qt.resultType === 'Logs' && !qt.done);\n",
" const loading = queryTransactions.some(qt => !qt.done);\n",
"\n",
" return (\n",
" <div className={exploreClass} ref={this.getRef}>\n",
" <div className=\"navbar\">\n",
" {position === 'left' ? (\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const queryEmpty = queryTransactions.some(qt => qt.resultType === 'Logs' && qt.done && qt.result.length === 0);\n"
],
"file_path": "public/app/features/explore/Explore.tsx",
"type": "add",
"edit_start_line_idx": 839
} | import { parseQuery } from './query_utils';
describe('parseQuery', () => {
it('returns empty for empty string', () => {
expect(parseQuery('')).toEqual({
query: '',
regexp: '',
});
});
it('returns regexp for strings without query', () => {
expect(parseQuery('test')).toEqual({
query: '',
regexp: 'test',
});
});
it('returns query for strings without regexp', () => {
expect(parseQuery('{foo="bar"}')).toEqual({
query: '{foo="bar"}',
regexp: '',
});
});
it('returns query for strings with query and search string', () => {
expect(parseQuery('x {foo="bar"}')).toEqual({
query: '{foo="bar"}',
regexp: 'x',
});
});
it('returns query for strings with query and regexp', () => {
expect(parseQuery('{foo="bar"} x|y')).toEqual({
query: '{foo="bar"}',
regexp: 'x|y',
});
});
it('returns query for selector with two labels', () => {
expect(parseQuery('{foo="bar", baz="42"}')).toEqual({
query: '{foo="bar", baz="42"}',
regexp: '',
});
});
it('returns query and regexp with quantifiers', () => {
expect(parseQuery('{foo="bar"} \\.java:[0-9]{1,5}')).toEqual({
query: '{foo="bar"}',
regexp: '\\.java:[0-9]{1,5}',
});
expect(parseQuery('\\.java:[0-9]{1,5} {foo="bar"}')).toEqual({
query: '{foo="bar"}',
regexp: '\\.java:[0-9]{1,5}',
});
});
});
| public/app/plugins/datasource/logging/query_utils.test.ts | 0 | https://github.com/grafana/grafana/commit/4e591653bd261f45dac1a04eba7928e7a601a967 | [
0.000173022344824858,
0.00017161096911877394,
0.00017034423945005983,
0.00017146390746347606,
0.000001005093622552522
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.