1
0
Fork 0
mirror of https://github.com/portainer/portainer.git synced 2025-08-05 05:45:22 +02:00

feat(intel): Enable OpenAMT and FDO capabilities (#6212)

* feat(openamt): add AMT Devices information in Environments view [INT-8] (#6169)

* feat(openamt): add AMT Devices Ouf of Band Managamenet actions  [INT-9] (#6171)

* feat(openamt): add AMT Devices KVM Connection [INT-10] (#6179)

* feat(openamt): Enhance the Environments MX to activate OpenAMT on compatible environments [INT-7] (#6196)

* feat(openamt): Enable KVM by default [INT-25] (#6228)

* feat(fdo): implement the FDO configuration settings INT-19 (#6238)

feat(fdo): implement the FDO configuration settings INT-19

* feat(fdo): implement Owner client INT-17 (#6231)

feat(fdo): implement Owner client INT-17

* feat(openamt): hide wireless config in OpenAMT form (#6250)

* feat(openamt): Increase OpenAMT timeouts [INT-30] (#6253)

* feat(openamt): Disable the ability to use KVM and OOB actions on a MPS disconnected device [INT-36] (#6254)

* feat(fdo): add import device UI [INT-20] (#6240)

feat(fdo): add import device UI INT-20

* refactor(fdo): fix develop merge issues

* feat(openamt): Do not fetch OpenAMT details for an unassociated Edge endpoint (#6273)

* fix(intel): Fix switches params (#6282)

* feat(openamt): preload existing AMT settings (#6283)

* feat(openamt): Better UI/UX for AMT activation loading [INT-39] (#6290)

* feat(openamt): Remove wireless config related code [INT-41] (#6291)

* yarn install

* feat(openamt): change kvm redirection for pop up, always enable features [INT-37] (#6292)

* feat(openamt): change kvm redirection for pop up, always enable features [INT-37] (#6293)

* feat(openmt): use .ts services with axios for OpenAMT (#6312)

* Minor code cleanup.

* fix(fdo): move the FDO client code to the hostmanagement folder INT-44 (#6345)

* refactor(intel): Add Edge Compute Settings view (#6351)

* feat(fdo): add FDO profiles INT-22 (#6363)

feat(fdo): add FDO profiles INT-22

* fix(fdo): fix incorrect profile URL INT-45 (#6377)

* fixed husky version

* fix go.mod with go mod tidy

* feat(edge): migrate OpenAMT devices views to Edge Devices [EE-2322] (#6373)

* feat(intel): OpenAMT UI/UX adjustments (#6394)

* only allow edge agent as edge device

* show all edge agent environments on Edge Devices view

* feat(fdo): add the ability to import multiple ownership vouchers at once EE-2324 (#6395)

* fix(edge): settings edge compute alert (#6402)

* remove pagination, add useMemo for devices result array (#6409)

* feat(edge): minor Edge Devices (AMT) UI fixes (#6410)

* chore(eslint): fix versions

* chore(app): reformat codebase

* change add edge agent modal behaviour, fix yarn.lock

* fix use pagination

* remove extractedTranslations folder

* feat(edge): add FDO Profiles Datatable [EE-2406] (#6415)

* feat(edge): add KVM workaround tooltip (#6441)

* feat(edge): Add default FDO profile (#6450)

* feat(edge): add settings to disable trust on first connect and enforce Edge ID INT-1 EE-2410 (#6429)

Co-authored-by: andres-portainer <91705312+andres-portainer@users.noreply.github.com>
Co-authored-by: Anthony Lapenna <anthony.lapenna@portainer.io>
Co-authored-by: andres-portainer <andres-portainer@users.noreply.github.com>
Co-authored-by: Chaim Lev-Ari <chiptus@gmail.com>
This commit is contained in:
Marcelo Rydel 2022-01-23 16:48:04 -03:00 committed by GitHub
parent 3ed92e5fee
commit 2c4c638f46
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
170 changed files with 6834 additions and 819 deletions

View file

@ -1,8 +1,9 @@
import angular from 'angular';
import edgeStackModule from './views/edge-stacks';
import edgeDevicesModule from './devices';
angular.module('portainer.edge', [edgeStackModule]).config(function config($stateRegistryProvider) {
angular.module('portainer.edge', [edgeStackModule, edgeDevicesModule]).config(function config($stateRegistryProvider) {
const edge = {
name: 'edge',
url: '/edge',
@ -106,6 +107,16 @@ angular.module('portainer.edge', [edgeStackModule]).config(function config($stat
},
};
const edgeDevices = {
name: 'edge.devices',
url: '/devices',
views: {
'content@': {
component: 'edgeDevicesView',
},
},
};
$stateRegistryProvider.register(edge);
$stateRegistryProvider.register(groups);
@ -119,4 +130,6 @@ angular.module('portainer.edge', [edgeStackModule]).config(function config($stat
$stateRegistryProvider.register(edgeJobs);
$stateRegistryProvider.register(edgeJob);
$stateRegistryProvider.register(edgeJobCreation);
$stateRegistryProvider.register(edgeDevices);
});

View file

@ -0,0 +1,108 @@
import { usePagination, useTable } from 'react-table';
import {
Table,
TableContainer,
TableHeaderRow,
TableRow,
} from '@/portainer/components/datatables/components';
import { InnerDatatable } from '@/portainer/components/datatables/components/InnerDatatable';
import { Device } from '@/portainer/hostmanagement/open-amt/model';
import { useAMTDevices } from '@/edge/devices/components/AMTDevicesDatatable/useAMTDevices';
import { RowProvider } from '@/edge/devices/components/AMTDevicesDatatable/columns/RowContext';
import { EnvironmentId } from '@/portainer/environments/types';
import PortainerError from '@/portainer/error';
import { useColumns } from './columns';
export interface AMTDevicesTableProps {
environmentId: EnvironmentId;
}
export function AMTDevicesDatatable({ environmentId }: AMTDevicesTableProps) {
const columns = useColumns();
const { isLoading, devices, error } = useAMTDevices(environmentId);
const { getTableProps, getTableBodyProps, headerGroups, page, prepareRow } =
useTable<Device>(
{
columns,
data: devices,
},
usePagination
);
const tableProps = getTableProps();
const tbodyProps = getTableBodyProps();
return (
<InnerDatatable>
<TableContainer>
<Table
className={tableProps.className}
role={tableProps.role}
style={tableProps.style}
>
<thead>
{headerGroups.map((headerGroup) => {
const { key, className, role, style } =
headerGroup.getHeaderGroupProps();
return (
<TableHeaderRow<Device>
key={key}
className={className}
role={role}
style={style}
headers={headerGroup.headers}
/>
);
})}
</thead>
<tbody
className={tbodyProps.className}
role={tbodyProps.role}
style={tbodyProps.style}
>
{!isLoading && devices && devices.length > 0 ? (
page.map((row) => {
prepareRow(row);
const { key, className, role, style } = row.getRowProps();
return (
<RowProvider key={key} environmentId={environmentId}>
<TableRow<Device>
cells={row.cells}
key={key}
className={className}
role={role}
style={style}
/>
</RowProvider>
);
})
) : (
<tr>
<td colSpan={5} className="text-center text-muted">
{userMessage(isLoading, error)}
</td>
</tr>
)}
</tbody>
</Table>
</TableContainer>
</InnerDatatable>
);
}
function userMessage(isLoading: boolean, error?: PortainerError) {
if (isLoading) {
return 'Loading...';
}
if (error) {
return error.message;
}
return 'No devices found';
}

View file

@ -0,0 +1,43 @@
import {
createContext,
useContext,
useMemo,
useReducer,
PropsWithChildren,
} from 'react';
import { EnvironmentId } from 'Portainer/environments/types';
interface RowContextState {
environmentId: EnvironmentId;
isLoading: boolean;
toggleIsLoading(): void;
}
const RowContext = createContext<RowContextState | null>(null);
export interface RowProviderProps {
environmentId: EnvironmentId;
}
export function RowProvider({
environmentId,
children,
}: PropsWithChildren<RowProviderProps>) {
const [isLoading, toggleIsLoading] = useReducer((state) => !state, false);
const state = useMemo(
() => ({ isLoading, toggleIsLoading, environmentId }),
[isLoading, toggleIsLoading, environmentId]
);
return <RowContext.Provider value={state}>{children}</RowContext.Provider>;
}
export function useRowContext() {
const context = useContext(RowContext);
if (!context) {
throw new Error('should be nested under RowProvider');
}
return context;
}

View file

@ -0,0 +1,108 @@
import { CellProps, Column } from 'react-table';
import { useSref } from '@uirouter/react';
import { MenuItem, MenuLink } from '@reach/menu-button';
import { useQueryClient } from 'react-query';
import { Device } from '@/portainer/hostmanagement/open-amt/model';
import { ActionsMenu } from '@/portainer/components/datatables/components/ActionsMenu';
import { confirmAsync } from '@/portainer/services/modal.service/confirm';
import { executeDeviceAction } from '@/portainer/hostmanagement/open-amt/open-amt.service';
import * as notifications from '@/portainer/services/notifications';
import { ActionsMenuTitle } from '@/portainer/components/datatables/components/ActionsMenuTitle';
import { useRowContext } from '@/edge/devices/components/AMTDevicesDatatable/columns/RowContext';
import { DeviceAction } from '@/edge/devices/types';
export const actions: Column<Device> = {
Header: 'Actions',
accessor: () => 'actions',
id: 'actions',
disableFilters: true,
canHide: true,
disableResizing: true,
width: '5px',
sortType: 'string',
Filter: () => null,
Cell: ActionsCell,
};
export function ActionsCell({ row: { original: device } }: CellProps<Device>) {
const queryClient = useQueryClient();
const { isLoading, toggleIsLoading, environmentId } = useRowContext();
const kvmLinkProps = useSref('portainer.endpoints.endpoint.kvm', {
id: environmentId,
deviceId: device.guid,
deviceName: device.hostname,
});
return (
<ActionsMenu>
<ActionsMenuTitle>AMT Functions</ActionsMenuTitle>
<MenuItem
disabled={isLoading}
onSelect={() => handleDeviceActionClick(DeviceAction.PowerOn)}
>
Power ON
</MenuItem>
<MenuItem
disabled={isLoading}
onSelect={() => handleDeviceActionClick(DeviceAction.PowerOff)}
>
Power OFF
</MenuItem>
<MenuItem
disabled={isLoading}
onSelect={() => handleDeviceActionClick(DeviceAction.Restart)}
>
Restart
</MenuItem>
<MenuLink
href={kvmLinkProps.href}
onClick={kvmLinkProps.onClick}
disabled={isLoading}
>
KVM
</MenuLink>
</ActionsMenu>
);
async function handleDeviceActionClick(action: string) {
const confirmed = await confirmAsync({
title: 'Confirm action',
message: `Are you sure you want to ${action} the device?`,
buttons: {
cancel: {
label: 'Cancel',
className: 'btn-default',
},
confirm: {
label: 'Confirm',
className: 'btn-primary',
},
},
});
if (!confirmed) {
return;
}
try {
toggleIsLoading();
await executeDeviceAction(environmentId, device.guid, action);
notifications.success(
`${action} action sent successfully`,
device.hostname
);
await queryClient.invalidateQueries(['amt_devices', environmentId]);
} catch (err) {
notifications.error(
'Failure',
err as Error,
`Failed to ${action} the device`
);
} finally {
toggleIsLoading();
}
}
}

View file

@ -0,0 +1,13 @@
import { Column } from 'react-table';
import { Device } from '@/portainer/hostmanagement/open-amt/model';
export const hostname: Column<Device> = {
Header: 'Hostname',
accessor: (row) => row.hostname || '-',
id: 'hostname',
disableFilters: true,
canHide: true,
sortType: 'string',
Filter: () => null,
};

View file

@ -0,0 +1,10 @@
import { useMemo } from 'react';
import { hostname } from './hostname';
import { status } from './status';
import { powerState } from './power-state';
import { actions } from './actions';
export function useColumns() {
return useMemo(() => [hostname, status, powerState, actions], []);
}

View file

@ -0,0 +1,56 @@
import { CellProps, Column } from 'react-table';
import clsx from 'clsx';
import { Device } from '@/portainer/hostmanagement/open-amt/model';
import { useRowContext } from '@/edge/devices/components/AMTDevicesDatatable/columns/RowContext';
import { PowerState, PowerStateCode } from '@/edge/devices/types';
export const powerState: Column<Device> = {
Header: 'Power State',
accessor: (row) => parsePowerState(row.powerState),
id: 'powerState',
disableFilters: true,
canHide: true,
sortType: 'string',
Cell: PowerStateCell,
Filter: () => null,
};
export function PowerStateCell({
row: { original: device },
}: CellProps<Device>) {
const { isLoading } = useRowContext();
return (
<>
<span
className={clsx({
'text-success': device.powerState === PowerStateCode.On,
})}
>
{parsePowerState(device.powerState)}
</span>
<span>{isLoading && <i className="fa fa-cog fa-spin space-left" />}</span>
</>
);
}
function parsePowerState(value: PowerStateCode) {
// https://app.swaggerhub.com/apis-docs/rbheopenamt/mps/1.4.0#/AMT/get_api_v1_amt_power_state__guid_
switch (value) {
case PowerStateCode.On:
return PowerState.Running;
case PowerStateCode.SleepLight:
case PowerStateCode.SleepDeep:
return PowerState.Sleep;
case PowerStateCode.OffHard:
case PowerStateCode.OffSoft:
case PowerStateCode.OffHardGraceful:
return PowerState.Off;
case PowerStateCode.Hibernate:
return PowerState.Hibernate;
case PowerStateCode.PowerCycle:
return PowerState.PowerCycle;
default:
return '-';
}
}

View file

@ -0,0 +1,22 @@
import { CellProps, Column } from 'react-table';
import clsx from 'clsx';
import { Device } from '@/portainer/hostmanagement/open-amt/model';
export const status: Column<Device> = {
Header: 'MPS Status',
id: 'status',
disableFilters: true,
canHide: true,
sortType: 'string',
Cell: StatusCell,
Filter: () => null,
};
export function StatusCell({ row: { original: device } }: CellProps<Device>) {
return (
<span className={clsx({ 'text-success': device.connectionStatus })}>
{device.connectionStatus ? 'Connected' : 'Disconnected'}
</span>
);
}

View file

@ -0,0 +1,32 @@
import { useEffect, useMemo } from 'react';
import { useQuery } from 'react-query';
import { getDevices } from '@/portainer/hostmanagement/open-amt/open-amt.service';
import { EnvironmentId } from '@/portainer/environments/types';
import PortainerError from '@/portainer/error';
import * as notifications from '@/portainer/services/notifications';
export function useAMTDevices(environmentId: EnvironmentId) {
const { isLoading, data, isError, error } = useQuery(
['amt_devices', environmentId],
() => getDevices(environmentId)
);
useEffect(() => {
if (isError) {
notifications.error(
'Failure',
error as Error,
'Failed retrieving AMT devices'
);
}
}, [isError, error]);
const devices = useMemo(() => data || [], [data]);
return {
isLoading,
devices,
error: isError ? (error as PortainerError) : undefined,
};
}

View file

@ -0,0 +1,3 @@
.kvm-tip {
padding: 8px;
}

View file

@ -0,0 +1,265 @@
import { useEffect } from 'react';
import {
useTable,
useExpanded,
useSortBy,
useFilters,
useGlobalFilter,
usePagination,
} from 'react-table';
import { useRowSelectColumn } from '@lineup-lite/hooks';
import { Environment } from '@/portainer/environments/types';
import { PaginationControls } from '@/portainer/components/pagination-controls';
import {
Table,
TableActions,
TableContainer,
TableHeaderRow,
TableRow,
TableSettingsMenu,
TableTitle,
TableTitleActions,
} from '@/portainer/components/datatables/components';
import { multiple } from '@/portainer/components/datatables/components/filter-types';
import { useTableSettings } from '@/portainer/components/datatables/components/useTableSettings';
import { ColumnVisibilityMenu } from '@/portainer/components/datatables/components/ColumnVisibilityMenu';
import { useRepeater } from '@/portainer/components/datatables/components/useRepeater';
import { useDebounce } from '@/portainer/hooks/useDebounce';
import {
useSearchBarContext,
SearchBar,
} from '@/portainer/components/datatables/components/SearchBar';
import { useRowSelect } from '@/portainer/components/datatables/components/useRowSelect';
import { TableFooter } from '@/portainer/components/datatables/components/TableFooter';
import { SelectedRowsCount } from '@/portainer/components/datatables/components/SelectedRowsCount';
import { EdgeDeviceTableSettings } from '@/edge/devices/types';
import { EdgeDevicesDatatableSettings } from '@/edge/devices/components/EdgeDevicesDatatable/EdgeDevicesDatatableSettings';
import { EdgeDevicesDatatableActions } from '@/edge/devices/components/EdgeDevicesDatatable/EdgeDevicesDatatableActions';
import { AMTDevicesDatatable } from '@/edge/devices/components/AMTDevicesDatatable/AMTDevicesDatatable';
import { TextTip } from '@/portainer/components/Tip/TextTip';
import { RowProvider } from './columns/RowContext';
import { useColumns } from './columns';
import styles from './EdgeDevicesDatatable.module.css';
export interface EdgeDevicesTableProps {
isEnabled: boolean;
isFdoEnabled: boolean;
isOpenAmtEnabled: boolean;
disableTrustOnFirstConnect: boolean;
mpsServer: string;
dataset: Environment[];
onRefresh(): Promise<void>;
setLoadingMessage(message: string): void;
}
export function EdgeDevicesDatatable({
isFdoEnabled,
isOpenAmtEnabled,
disableTrustOnFirstConnect,
mpsServer,
dataset,
onRefresh,
setLoadingMessage,
}: EdgeDevicesTableProps) {
const { settings, setTableSettings } =
useTableSettings<EdgeDeviceTableSettings>();
const [searchBarValue, setSearchBarValue] = useSearchBarContext();
const columns = useColumns();
useRepeater(settings.autoRefreshRate, onRefresh);
const {
getTableProps,
getTableBodyProps,
headerGroups,
page,
prepareRow,
selectedFlatRows,
allColumns,
gotoPage,
setPageSize,
setHiddenColumns,
setGlobalFilter,
state: { pageIndex, pageSize },
} = useTable<Environment>(
{
defaultCanFilter: false,
columns,
data: dataset,
filterTypes: { multiple },
initialState: {
pageSize: settings.pageSize || 10,
hiddenColumns: settings.hiddenColumns,
sortBy: [settings.sortBy],
globalFilter: searchBarValue,
},
isRowSelectable() {
return true;
},
autoResetExpanded: false,
autoResetSelectedRows: false,
selectColumnWidth: 5,
},
useFilters,
useGlobalFilter,
useSortBy,
useExpanded,
usePagination,
useRowSelect,
useRowSelectColumn
);
const debouncedSearchValue = useDebounce(searchBarValue);
useEffect(() => {
setGlobalFilter(debouncedSearchValue);
}, [debouncedSearchValue, setGlobalFilter]);
const columnsToHide = allColumns.filter((colInstance) => {
const columnDef = columns.find((c) => c.id === colInstance.id);
return columnDef?.canHide;
});
const tableProps = getTableProps();
const tbodyProps = getTableBodyProps();
const someDeviceHasAMTActivated = dataset.some(
(environment) =>
environment.AMTDeviceGUID && environment.AMTDeviceGUID !== ''
);
return (
<TableContainer>
<TableTitle icon="fa-plug" label="Edge Devices">
<TableTitleActions>
<ColumnVisibilityMenu<Environment>
columns={columnsToHide}
onChange={handleChangeColumnsVisibility}
value={settings.hiddenColumns}
/>
<TableSettingsMenu>
<EdgeDevicesDatatableSettings />
</TableSettingsMenu>
</TableTitleActions>
</TableTitle>
<TableActions>
<EdgeDevicesDatatableActions
selectedItems={selectedFlatRows.map((row) => row.original)}
isFDOEnabled={isFdoEnabled}
isOpenAMTEnabled={isOpenAmtEnabled}
setLoadingMessage={setLoadingMessage}
/>
</TableActions>
{someDeviceHasAMTActivated && (
<div className={styles.kvmTip}>
<TextTip color="blue">
For the KVM function to work you need to have the MPS server added
to your trusted site list, browse to this{' '}
<a href={`https://${mpsServer}`} target="_blank" rel="noreferrer">
site
</a>{' '}
and add to your trusted site list
</TextTip>
</div>
)}
<SearchBar value={searchBarValue} onChange={handleSearchBarChange} />
<Table
className={tableProps.className}
role={tableProps.role}
style={tableProps.style}
>
<thead>
{headerGroups.map((headerGroup) => {
const { key, className, role, style } =
headerGroup.getHeaderGroupProps();
return (
<TableHeaderRow<Environment>
key={key}
className={className}
role={role}
style={style}
headers={headerGroup.headers}
onSortChange={handleSortChange}
/>
);
})}
</thead>
<tbody
className={tbodyProps.className}
role={tbodyProps.role}
style={tbodyProps.style}
>
{page.map((row) => {
prepareRow(row);
const { key, className, role, style } = row.getRowProps();
return (
<RowProvider
key={key}
disableTrustOnFirstConnect={disableTrustOnFirstConnect}
>
<TableRow<Environment>
cells={row.cells}
key={key}
className={className}
role={role}
style={style}
/>
{row.isExpanded && (
<tr>
<td />
<td colSpan={row.cells.length - 1}>
<AMTDevicesDatatable environmentId={row.original.Id} />
</td>
</tr>
)}
</RowProvider>
);
})}
</tbody>
</Table>
<TableFooter>
<SelectedRowsCount value={selectedFlatRows.length} />
<PaginationControls
showAll
pageLimit={pageSize}
page={pageIndex + 1}
onPageChange={(p) => gotoPage(p - 1)}
totalCount={dataset.length}
onPageLimitChange={handlePageSizeChange}
/>
</TableFooter>
</TableContainer>
);
function handlePageSizeChange(pageSize: number) {
setPageSize(pageSize);
setTableSettings((settings) => ({ ...settings, pageSize }));
}
function handleChangeColumnsVisibility(hiddenColumns: string[]) {
setHiddenColumns(hiddenColumns);
setTableSettings((settings) => ({ ...settings, hiddenColumns }));
}
function handleSearchBarChange(value: string) {
setSearchBarValue(value);
}
function handleSortChange(id: string, desc: boolean) {
setTableSettings((settings) => ({
...settings,
sortBy: { id, desc },
}));
}
}

View file

@ -0,0 +1,173 @@
import { useRouter } from '@uirouter/react';
import type { Environment } from '@/portainer/environments/types';
import { Button } from '@/portainer/components/Button';
import { confirmAsync } from '@/portainer/services/modal.service/confirm';
import { promptAsync } from '@/portainer/services/modal.service/prompt';
import * as notifications from '@/portainer/services/notifications';
import { activateDevice } from '@/portainer/hostmanagement/open-amt/open-amt.service';
import { deleteEndpoint } from '@/portainer/environments/environment.service';
interface Props {
selectedItems: Environment[];
isFDOEnabled: boolean;
isOpenAMTEnabled: boolean;
setLoadingMessage(message: string): void;
}
export function EdgeDevicesDatatableActions({
selectedItems,
isOpenAMTEnabled,
isFDOEnabled,
setLoadingMessage,
}: Props) {
const router = useRouter();
return (
<div className="actionBar">
<Button
disabled={selectedItems.length < 1}
color="danger"
onClick={() => onDeleteEdgeDeviceClick()}
>
<i className="fa fa-trash-alt space-right" aria-hidden="true" />
Remove
</Button>
<Button onClick={() => onAddNewDeviceClick()}>
<i className="fa fa-plus-circle space-right" aria-hidden="true" />
Add Device
</Button>
{isOpenAMTEnabled && (
<Button
disabled={selectedItems.length !== 1}
onClick={() => onAssociateOpenAMTClick(selectedItems)}
>
<i className="fa fa-link space-right" aria-hidden="true" />
Associate with OpenAMT
</Button>
)}
</div>
);
async function onDeleteEdgeDeviceClick() {
const confirmed = await confirmAsync({
title: 'Are you sure ?',
message:
'This action will remove all configurations associated to your environment(s). Continue?',
buttons: {
confirm: {
label: 'Remove',
className: 'btn-danger',
},
},
});
if (!confirmed) {
return;
}
await Promise.all(
selectedItems.map(async (environment) => {
try {
await deleteEndpoint(environment.Id);
notifications.success(
'Environment successfully removed',
environment.Name
);
} catch (err) {
notifications.error(
'Failure',
err as Error,
'Unable to remove environment'
);
}
})
);
await router.stateService.reload();
}
async function onAddNewDeviceClick() {
if (!isFDOEnabled) {
router.stateService.go('portainer.endpoints.newEdgeDevice');
return;
}
const result = await promptAsync({
title: 'How would you like to add an Edge Device?',
inputType: 'radio',
inputOptions: [
{
text: 'Provision bare-metal using Intel FDO',
value: 'FDO',
},
{
text: 'Deploy agent manually',
value: 'MANUAL',
},
],
buttons: {
confirm: {
label: 'Confirm',
className: 'btn-primary',
},
},
});
switch (result) {
case 'FDO':
router.stateService.go('portainer.endpoints.importDevice');
break;
case 'MANUAL':
router.stateService.go('portainer.endpoints.newEdgeDevice');
break;
default:
break;
}
}
async function onAssociateOpenAMTClick(selectedItems: Environment[]) {
const selectedEnvironment = selectedItems[0];
const confirmed = await confirmAsync({
title: '',
message: `Associate ${selectedEnvironment.Name} with OpenAMT`,
buttons: {
cancel: {
label: 'Cancel',
className: 'btn-default',
},
confirm: {
label: 'Confirm',
className: 'btn-primary',
},
},
});
if (!confirmed) {
return;
}
try {
setLoadingMessage(
'Activating Active Management Technology on selected device...'
);
await activateDevice(selectedEnvironment.Id);
notifications.success(
'Successfully associated with OpenAMT',
selectedEnvironment.Name
);
} catch (err) {
notifications.error(
'Failure',
err as Error,
'Unable to associate with OpenAMT'
);
} finally {
setLoadingMessage('');
}
}
}

View file

@ -0,0 +1,42 @@
import { react2angular } from '@/react-tools/react2angular';
import { TableSettingsProvider } from '@/portainer/components/datatables/components/useTableSettings';
import { SearchBarProvider } from '@/portainer/components/datatables/components/SearchBar';
import {
EdgeDevicesDatatable,
EdgeDevicesTableProps,
} from './EdgeDevicesDatatable';
export function EdgeDevicesDatatableContainer({
...props
}: EdgeDevicesTableProps) {
const defaultSettings = {
autoRefreshRate: 0,
hiddenQuickActions: [],
hiddenColumns: [],
pageSize: 10,
sortBy: { id: 'state', desc: false },
};
return (
<TableSettingsProvider defaults={defaultSettings} storageKey="edgeDevices">
<SearchBarProvider storageKey="edgeDevices">
{/* eslint-disable-next-line react/jsx-props-no-spreading */}
<EdgeDevicesDatatable {...props} />
</SearchBarProvider>
</TableSettingsProvider>
);
}
export const EdgeDevicesDatatableAngular = react2angular(
EdgeDevicesDatatableContainer,
[
'dataset',
'onRefresh',
'setLoadingMessage',
'isFdoEnabled',
'disableTrustOnFirstConnect',
'isOpenAmtEnabled',
'mpsServer',
]
);

View file

@ -0,0 +1,19 @@
import { TableSettingsMenuAutoRefresh } from '@/portainer/components/datatables/components/TableSettingsMenuAutoRefresh';
import { useTableSettings } from '@/portainer/components/datatables/components/useTableSettings';
import { EdgeDeviceTableSettings } from '@/edge/devices/types';
export function EdgeDevicesDatatableSettings() {
const { settings, setTableSettings } =
useTableSettings<EdgeDeviceTableSettings>();
return (
<TableSettingsMenuAutoRefresh
value={settings.autoRefreshRate}
onChange={handleRefreshRateChange}
/>
);
function handleRefreshRateChange(autoRefreshRate: number) {
setTableSettings({ autoRefreshRate });
}
}

View file

@ -0,0 +1,32 @@
import { createContext, useContext, useMemo, PropsWithChildren } from 'react';
interface RowContextState {
disableTrustOnFirstConnect: boolean;
}
const RowContext = createContext<RowContextState | null>(null);
export interface RowProviderProps {
disableTrustOnFirstConnect: boolean;
}
export function RowProvider({
disableTrustOnFirstConnect,
children,
}: PropsWithChildren<RowProviderProps>) {
const state = useMemo(
() => ({ disableTrustOnFirstConnect }),
[disableTrustOnFirstConnect]
);
return <RowContext.Provider value={state}>{children}</RowContext.Provider>;
}
export function useRowContext() {
const context = useContext(RowContext);
if (!context) {
throw new Error('should be nested under RowProvider');
}
return context;
}

View file

@ -0,0 +1,107 @@
import { CellProps, Column } from 'react-table';
import { MenuItem, MenuLink } from '@reach/menu-button';
import { useRouter, useSref } from '@uirouter/react';
import { Environment } from '@/portainer/environments/types';
import { ActionsMenu } from '@/portainer/components/datatables/components/ActionsMenu';
import {
snapshotEndpoint,
trustEndpoint,
} from '@/portainer/environments/environment.service';
import * as notifications from '@/portainer/services/notifications';
import { getRoute } from '@/portainer/environments/utils';
import { confirmAsync } from '@/portainer/services/modal.service/confirm';
import { useRowContext } from '@/edge/devices/components/EdgeDevicesDatatable/columns/RowContext';
export const actions: Column<Environment> = {
Header: 'Actions',
accessor: () => 'actions',
id: 'actions',
disableFilters: true,
canHide: true,
disableResizing: true,
width: '5px',
sortType: 'string',
Filter: () => null,
Cell: ActionsCell,
};
export function ActionsCell({
row: { original: environment },
}: CellProps<Environment>) {
const router = useRouter();
const environmentRoute = getRoute(environment);
const browseLinkProps = useSref(environmentRoute, {
id: environment.Id,
endpointId: environment.Id,
});
const showRefreshSnapshot = false; // remove and show MenuItem when feature is available
const { disableTrustOnFirstConnect } = useRowContext();
return (
<ActionsMenu>
<MenuLink href={browseLinkProps.href} onClick={browseLinkProps.onClick}>
Browse
</MenuLink>
{showRefreshSnapshot && (
<MenuItem hidden onSelect={() => handleRefreshSnapshotClick()}>
Refresh Snapshot
</MenuItem>
)}
{disableTrustOnFirstConnect && !environment.UserTrusted && (
<MenuLink onClick={trustDevice}>Trust</MenuLink>
)}
</ActionsMenu>
);
async function handleRefreshSnapshotClick() {
try {
await snapshotEndpoint(environment.Id);
notifications.success('Success', 'Environment updated');
} catch (err) {
notifications.error(
'Failure',
err as Error,
'An error occurred during environment snapshot'
);
} finally {
await router.stateService.reload();
}
}
async function trustDevice() {
const confirmed = await confirmAsync({
title: '',
message: `Mark ${environment.Name} as trusted?`,
buttons: {
cancel: {
label: 'Cancel',
className: 'btn-default',
},
confirm: {
label: 'Trust',
className: 'btn-primary',
},
},
});
if (!confirmed) {
return;
}
try {
await trustEndpoint(environment.Id);
} catch (err) {
notifications.error(
'Failure',
err as Error,
'An error occurred while trusting the environment'
);
} finally {
await router.stateService.reload();
}
}
}

View file

@ -0,0 +1,12 @@
import { Column } from 'react-table';
import { Environment } from '@/portainer/environments/types';
import { DefaultFilter } from '@/portainer/components/datatables/components/Filter';
export const group: Column<Environment> = {
Header: 'Group',
accessor: (row) => row.GroupName || '-',
id: 'groupName',
Filter: DefaultFilter,
canHide: true,
};

View file

@ -0,0 +1,50 @@
import { CellProps, Column } from 'react-table';
import clsx from 'clsx';
import { Environment, EnvironmentStatus } from '@/portainer/environments/types';
import { useRowContext } from '@/edge/devices/components/EdgeDevicesDatatable/columns/RowContext';
export const heartbeat: Column<Environment> = {
Header: 'Heartbeat',
accessor: 'Status',
id: 'status',
Cell: StatusCell,
disableFilters: true,
canHide: true,
};
export function StatusCell({
row: { original: environment },
}: CellProps<Environment>) {
const { disableTrustOnFirstConnect } = useRowContext();
if (disableTrustOnFirstConnect && !environment.UserTrusted) {
return <span className="label label-default">untrusted</span>;
}
if (!environment.LastCheckInDate) {
return (
<span className="label label-default">
<s>associated</s>
</span>
);
}
return (
<i
className={clsx(
'fa',
'fa-heartbeat',
environmentStatusLabel(environment.Status)
)}
aria-hidden="true"
/>
);
function environmentStatusLabel(status: EnvironmentStatus) {
if (status === EnvironmentStatus.Up) {
return 'green-icon';
}
return 'orange-icon';
}
}

View file

@ -0,0 +1,10 @@
import { useMemo } from 'react';
import { name } from './name';
import { heartbeat } from './heartbeat';
import { group } from './group';
import { actions } from './actions';
export function useColumns() {
return useMemo(() => [name, heartbeat, group, actions], []);
}

View file

@ -0,0 +1,30 @@
import { CellProps, Column, TableInstance } from 'react-table';
import { Environment } from '@/portainer/environments/types';
import { Link } from '@/portainer/components/Link';
import { ExpandingCell } from '@/portainer/components/datatables/components/ExpandingCell';
export const name: Column<Environment> = {
Header: 'Name',
accessor: (row) => row.Name,
id: 'name',
Cell: NameCell,
disableFilters: true,
Filter: () => null,
canHide: false,
sortType: 'string',
};
export function NameCell({ value: name, row }: CellProps<TableInstance>) {
return (
<ExpandingCell row={row}>
<Link
to="portainer.endpoints.endpoint"
params={{ id: row.original.Id }}
title={name}
>
{name}
</Link>
</ExpandingCell>
);
}

View file

@ -0,0 +1,7 @@
import angular from 'angular';
import { EdgeDevicesDatatableAngular } from '@/edge/devices/components/EdgeDevicesDatatable/EdgeDevicesDatatableContainer';
export default angular
.module('portainer.edge.devices', [])
.component('edgeDevicesDatatable', EdgeDevicesDatatableAngular).name;

36
app/edge/devices/types.ts Normal file
View file

@ -0,0 +1,36 @@
export interface EdgeDeviceTableSettings {
hiddenColumns: string[];
autoRefreshRate: number;
pageSize: number;
sortBy: { id: string; desc: boolean };
}
export interface FDOProfilesTableSettings {
pageSize: number;
sortBy: { id: string; desc: boolean };
}
export enum DeviceAction {
PowerOn = 'power on',
PowerOff = 'power off',
Restart = 'restart',
}
export enum PowerState {
Running = 'Running',
Sleep = 'Sleep',
Off = 'Off',
Hibernate = 'Hibernate',
PowerCycle = 'Power Cycle',
}
export enum PowerStateCode {
On = 2,
SleepLight = 3,
SleepDeep = 4,
OffHard = 6,
Hibernate = 7,
OffSoft = 8,
PowerCycle = 9,
OffHardGraceful = 13,
}

View file

@ -1,6 +1,6 @@
import angular from 'angular';
import { ScheduleCreateRequest, ScheduleUpdateRequest } from 'Portainer/models/schedule';
import { ScheduleCreateRequest, ScheduleUpdateRequest } from '@/portainer/models/schedule';
function EdgeJobService(EdgeJobs, EdgeJobResults, FileUploadService) {
var service = {};

View file

@ -0,0 +1,39 @@
<rd-header>
<rd-header-title title-text="Edge Devices">
<a data-toggle="tooltip" title="Refresh" ui-sref="edge.devices" ui-sref-opts="{reload: true}">
<i class="fa fa-sync" aria-hidden="true"></i>
</a>
</rd-header-title>
<rd-header-content>Edge Devices</rd-header-content>
</rd-header>
<div
class="row"
style="width: 100%; height: 100%; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center"
ng-if="$ctrl.loadingMessage"
>
<div class="sk-fold">
<div class="sk-fold-cube"></div>
<div class="sk-fold-cube"></div>
<div class="sk-fold-cube"></div>
<div class="sk-fold-cube"></div>
</div>
<span style="margin-top: 25px">
{{ $ctrl.loadingMessage }}
<i class="fa fa-cog fa-spin"></i>
</span>
</div>
<div class="row" ng-if="!$ctrl.loadingMessage">
<div class="col-sm-12">
<edge-devices-datatable
dataset="($ctrl.edgeDevices)"
is-fdo-enabled="($ctrl.isFDOEnabled)"
is-open-amt-enabled="($ctrl.isOpenAMTEnabled)"
disable-trust-on-first-connect="($ctrl.disableTrustOnFirstConnect)"
mps-server="($ctrl.mpsServer)"
on-refresh="($ctrl.getEnvironments)"
set-loading-message="($ctrl.setLoadingMessage)"
></edge-devices-datatable>
</div>
</div>

View file

@ -0,0 +1,52 @@
import EndpointHelper from 'Portainer/helpers/endpointHelper';
import { getEndpoints } from 'Portainer/environments/environment.service';
import { EnvironmentType } from 'Portainer/environments/types';
angular.module('portainer.edge').controller('EdgeDevicesViewController', EdgeDevicesViewController);
/* @ngInject */
export function EdgeDevicesViewController($q, $async, EndpointService, GroupService, SettingsService, ModalService, Notifications) {
var ctrl = this;
ctrl.edgeDevices = [];
this.getEnvironments = function () {
return $async(async () => {
try {
const [endpointsResponse, groups] = await Promise.all([getEndpoints(0, 100, { types: [EnvironmentType.EdgeAgentOnDocker] }), GroupService.groups()]);
EndpointHelper.mapGroupNameToEndpoint(endpointsResponse.value, groups);
ctrl.edgeDevices = endpointsResponse.value;
} catch (err) {
Notifications.error('Failure', err, 'Unable to retrieve edge devices');
ctrl.edgeDevices = [];
}
});
};
this.getSettings = function () {
return $async(async () => {
try {
const settings = await SettingsService.settings();
ctrl.isFDOEnabled = settings && settings.EnableEdgeComputeFeatures && settings.fdoConfiguration && settings.fdoConfiguration.enabled;
ctrl.disableTrustOnFirstConnect = settings && settings.EnableEdgeComputeFeatures && settings.DisableTrustOnFirstConnect;
ctrl.isOpenAMTEnabled = settings && settings.EnableEdgeComputeFeatures && settings.openAMTConfiguration && settings.openAMTConfiguration.enabled;
ctrl.mpsServer = ctrl.isOpenAMTEnabled ? settings.openAMTConfiguration.mpsServer : '';
} catch (err) {
Notifications.error('Failure', err, 'Unable to retrieve settings');
}
});
};
this.setLoadingMessage = function (message) {
return $async(async () => {
ctrl.loadingMessage = message;
});
};
function initView() {
ctrl.getEnvironments();
ctrl.getSettings();
}
initView();
}

View file

@ -0,0 +1,8 @@
import angular from 'angular';
import { EdgeDevicesViewController } from './edgeDevicesViewController';
angular.module('portainer.edge').component('edgeDevicesView', {
templateUrl: './edgeDevicesView.html',
controller: EdgeDevicesViewController,
});