portainer/app/docker/views/containers/create/createContainerController.js

687 lines
23 KiB
JavaScript
Raw Normal View History

refactor(app): introduce webpack and babel (#2407) * feat(agent): add new host page * feat(agent): convert volume-browser to files-datatable * fix(agent): browse folders in file-datatable * feat(engine-details): replace engine view with host view * feat(engine-details): remove old panels * feat(engine-details): add basic engine-details-panel component * feat(engine-details): pass details to the different components * feat(engine-details): replace host-view with host-overview * feat(engine-details): add commaseperated filter * feat(engine-details): add host-view container component * feat(engine-details): add host-details component * feat(engine-details): build host details object * feat(engine-details): format engine version * feat(engine-details): get details for one node * feat(engine-details): pass is-agent from view * feat(engine-details): replace old node view with a new component * feat(engine-details): add swarm-node-details component * feat(engine-details): remove isSwarm binding * feat(engine-details): remove node-details and include in parent * feat(engine-details): add labels-table component * feat(engine-details): add update node service * feat(engine-details): add update label functionality * style(engine-details): remove whitespaces * feat(engine-details): remove old node page * feat(engine-details): pass is agent to host details * feat(host-details): hide missing info * feat(host-details): update node availability * style(host-details): remove obsolete event object * feat(host-details): fix labels not sending * feat(host-details): remove flags for hiding data * feat(host-details): create mock call to server for agent host info * style(host-details): fix spelling mistake in filter's name * feat(host-details): get info from agent * feat(host-details): hide engine labels when empty * feat(node-details): move labels table and save button * feat(host-info): add different urls for refresh * feat(host-details): show disk/devices info for agent * feat(host-view): add loading indicator to devices-panel * feat(host-details): add loading indicator to disks panel * feat(agent): fix browse volume * feat(agent): browse files * feat(agent): enable rename * feat(agent): download file * fix(agent): download file from root * feat(agent): delete file * style(agent): remove whitespaces * fix(agent): fix link on node browser * feat(agent): basic file uploader * feat(agent): add basic file upload * fix(volume-browser): move volume id to query params * feat(node-browser): moved uploader into browser * feat(node-browser): add upload spinner * feat(agent): browse files relative to root * feat(build): add webpack build config * feat(build): add missing imports * feat(webpack): add missing imports * feat(build): enable eslint on build * feat(build): add webpack notifier * feat(build): clean terminal on build * feat(build): import all globals * feat(build): add angular import * feat(build): fix styles * feat(build): load favicons * feat(build): load css before script * feat(webpack): split vendors css and js to a different bundle * feat(webpack): import angular in all files * feat(webpack): remove eslint global config * feat(webpack): add webpack clean dist * feat(webpack): fix styling issues * refactor(webpack): remove empty controllers * refactor(webpack): optimize moment * refactor(webpack): add bundle analyzer * feat(webpack): add babel * refactor(webpack): optimize lodash * refactor(toastr): update toastr * feat(webpack): create basic production and dev config * fix(webpack): fix production config * fix(webpack): fix html templates url * refactor(webpack): remove angular imports * refactor(webpack): remove more angular imports * refactor(webpack): return angular to entry file * style(webpack): remove comments from config * fix(hosts): remove browse button * fix(webpack): import lodash * fix(webpack): import missing htmls * feat(webpack): reduce lodash size * feat(webpack): config grunt to use webpack * feat(webpack): add postcss * chore(codeclimate): use eslint-5 channel * feat(deps): upgrade from lodash to lodash-es * fix(webpack): fix bug with lodash * chore(build): add build client script * fix(webpack): fix missing jsyaml reference * refactor(webpack): seperate builds of img files * chore(build): add a way to check times of webpack build * feat(webpack): add dev server * fix(webpack): fix css output name * chore(webpack): optimize images * chore(webpack): add node env * fix(build): copy templates on release * chore(webpack): set env NODE_ENV * feat(webpack): set NODE_ENV on production builds * fix(extensions): set image path * refactor(css): move vendor css to js import * style(app): remove whitespaces * fix(build-system): allow DevOps pipeline to leverage webpack (#2670) * Update devopsbuild task to use webpack & remove AppVeyor environment var * Added -Force to replace the existing dist folder * Removed Test-Path * dep(build-system): add angularjs-annotate to webpack + fix on imports * Merge branch 'develop' into webpack * refactor(app): webpack aliases for imports + async / await dep + start refactor * style(extensions): use develop version of the view * fix(app): fix several issues introduced by webpack migration * fix(webpack): fix ng-include not loading templates with webpack * Fix Windows CI with Webpack (#2782) * fix(configs): refactor broke configs creation and list views * fix(build-system): update build_binary_devops for Windows
2019-03-21 05:46:49 +00:00
import _ from 'lodash-es';
feat(UX): introduce new env variables UI (#4175) * feat(app): introduce new env vars ui feat(app): introduce new env vars ui feat(UX): WIP new env variables UI feat(UX): update button and placeholder feat(UX): mention .env file in message feat(UX): allow add/remove value & load correctly feat(UX): restrict filesize to 1MB feat(UX): vertical align error message feat(UX): fill UI from file & when switching modes feat(UX): strip un-needed newline character feat(UX): introduce component to other views feat(UX): fix title alignment feat(UX): only populate editor on mode switch when key exists feat(UX): prevent trimming of whitespace on values feat(UX): change editor to async feat(UX): add message describing use feat(UX): Refactor variable text to editorText refactor(app): rename env vars controller refactor(app): move env var explanation to parent refactor(app): order env var panels refactor(app): move simple env vars mode to component refactor(app): parse env vars refactor(app): move styles to css refactor(app): rename functions refactor(container): parse env vars refactor(env-vars): move utils to helper module refactor(env-vars): use util function for parse dot env file fix(env-vars): ignore comments refactor(services): use env vars utils refactor(env-vars): rename files refactor(env-panel): use utils style(stack): revert EnvContent to Env style(service): revert EnvContent to Env style(container): revert EnvContent to Env refactor(env-vars): support default value refactor(service): use new env var component refactor(env-var): use one way data flow refactor(containers): remove unused function * fix(env-vars): prevent using non .env files * refactor(env-vars): move env vars items to a component * feat(app): fixed env vars form validation in Stack * feat(services): disable env form submit if invalid * fix(app): show key pairs correctly * fix(env-var): use the same validation as with kubernetes * fix(env-vars): parse env var Co-authored-by: Chaim Lev-Ari <chiptus@gmail.com> Co-authored-by: Felix Han <felix.han@portainer.io>
2021-06-14 06:59:07 +00:00
import { PorImageRegistryModel } from 'Docker/models/porImageRegistry';
feat(UX): introduce new env variables UI (#4175) * feat(app): introduce new env vars ui feat(app): introduce new env vars ui feat(UX): WIP new env variables UI feat(UX): update button and placeholder feat(UX): mention .env file in message feat(UX): allow add/remove value & load correctly feat(UX): restrict filesize to 1MB feat(UX): vertical align error message feat(UX): fill UI from file & when switching modes feat(UX): strip un-needed newline character feat(UX): introduce component to other views feat(UX): fix title alignment feat(UX): only populate editor on mode switch when key exists feat(UX): prevent trimming of whitespace on values feat(UX): change editor to async feat(UX): add message describing use feat(UX): Refactor variable text to editorText refactor(app): rename env vars controller refactor(app): move env var explanation to parent refactor(app): order env var panels refactor(app): move simple env vars mode to component refactor(app): parse env vars refactor(app): move styles to css refactor(app): rename functions refactor(container): parse env vars refactor(env-vars): move utils to helper module refactor(env-vars): use util function for parse dot env file fix(env-vars): ignore comments refactor(services): use env vars utils refactor(env-vars): rename files refactor(env-panel): use utils style(stack): revert EnvContent to Env style(service): revert EnvContent to Env style(container): revert EnvContent to Env refactor(env-vars): support default value refactor(service): use new env var component refactor(env-var): use one way data flow refactor(containers): remove unused function * fix(env-vars): prevent using non .env files * refactor(env-vars): move env vars items to a component * feat(app): fixed env vars form validation in Stack * feat(services): disable env form submit if invalid * fix(app): show key pairs correctly * fix(env-var): use the same validation as with kubernetes * fix(env-vars): parse env var Co-authored-by: Chaim Lev-Ari <chiptus@gmail.com> Co-authored-by: Felix Han <felix.han@portainer.io>
2021-06-14 06:59:07 +00:00
import { confirmDestructive } from '@@/modals/confirm';
import { FeatureId } from '@/react/portainer/feature-flags/enums';
import { buildConfirmButton } from '@@/modals/utils';
import { commandsTabUtils } from '@/react/docker/containers/CreateView/CommandsTab';
import { volumesTabUtils } from '@/react/docker/containers/CreateView/VolumesTab';
import { networkTabUtils } from '@/react/docker/containers/CreateView/NetworkTab';
import { capabilitiesTabUtils } from '@/react/docker/containers/CreateView/CapabilitiesTab';
import { AccessControlFormData } from '@/portainer/components/accessControlForm/porAccessControlFormModel';
import { ContainerDetailsViewModel } from '@/docker/models/container';
import { labelsTabUtils } from '@/react/docker/containers/CreateView/LabelsTab';
refactor(app): introduce webpack and babel (#2407) * feat(agent): add new host page * feat(agent): convert volume-browser to files-datatable * fix(agent): browse folders in file-datatable * feat(engine-details): replace engine view with host view * feat(engine-details): remove old panels * feat(engine-details): add basic engine-details-panel component * feat(engine-details): pass details to the different components * feat(engine-details): replace host-view with host-overview * feat(engine-details): add commaseperated filter * feat(engine-details): add host-view container component * feat(engine-details): add host-details component * feat(engine-details): build host details object * feat(engine-details): format engine version * feat(engine-details): get details for one node * feat(engine-details): pass is-agent from view * feat(engine-details): replace old node view with a new component * feat(engine-details): add swarm-node-details component * feat(engine-details): remove isSwarm binding * feat(engine-details): remove node-details and include in parent * feat(engine-details): add labels-table component * feat(engine-details): add update node service * feat(engine-details): add update label functionality * style(engine-details): remove whitespaces * feat(engine-details): remove old node page * feat(engine-details): pass is agent to host details * feat(host-details): hide missing info * feat(host-details): update node availability * style(host-details): remove obsolete event object * feat(host-details): fix labels not sending * feat(host-details): remove flags for hiding data * feat(host-details): create mock call to server for agent host info * style(host-details): fix spelling mistake in filter's name * feat(host-details): get info from agent * feat(host-details): hide engine labels when empty * feat(node-details): move labels table and save button * feat(host-info): add different urls for refresh * feat(host-details): show disk/devices info for agent * feat(host-view): add loading indicator to devices-panel * feat(host-details): add loading indicator to disks panel * feat(agent): fix browse volume * feat(agent): browse files * feat(agent): enable rename * feat(agent): download file * fix(agent): download file from root * feat(agent): delete file * style(agent): remove whitespaces * fix(agent): fix link on node browser * feat(agent): basic file uploader * feat(agent): add basic file upload * fix(volume-browser): move volume id to query params * feat(node-browser): moved uploader into browser * feat(node-browser): add upload spinner * feat(agent): browse files relative to root * feat(build): add webpack build config * feat(build): add missing imports * feat(webpack): add missing imports * feat(build): enable eslint on build * feat(build): add webpack notifier * feat(build): clean terminal on build * feat(build): import all globals * feat(build): add angular import * feat(build): fix styles * feat(build): load favicons * feat(build): load css before script * feat(webpack): split vendors css and js to a different bundle * feat(webpack): import angular in all files * feat(webpack): remove eslint global config * feat(webpack): add webpack clean dist * feat(webpack): fix styling issues * refactor(webpack): remove empty controllers * refactor(webpack): optimize moment * refactor(webpack): add bundle analyzer * feat(webpack): add babel * refactor(webpack): optimize lodash * refactor(toastr): update toastr * feat(webpack): create basic production and dev config * fix(webpack): fix production config * fix(webpack): fix html templates url * refactor(webpack): remove angular imports * refactor(webpack): remove more angular imports * refactor(webpack): return angular to entry file * style(webpack): remove comments from config * fix(hosts): remove browse button * fix(webpack): import lodash * fix(webpack): import missing htmls * feat(webpack): reduce lodash size * feat(webpack): config grunt to use webpack * feat(webpack): add postcss * chore(codeclimate): use eslint-5 channel * feat(deps): upgrade from lodash to lodash-es * fix(webpack): fix bug with lodash * chore(build): add build client script * fix(webpack): fix missing jsyaml reference * refactor(webpack): seperate builds of img files * chore(build): add a way to check times of webpack build * feat(webpack): add dev server * fix(webpack): fix css output name * chore(webpack): optimize images * chore(webpack): add node env * fix(build): copy templates on release * chore(webpack): set env NODE_ENV * feat(webpack): set NODE_ENV on production builds * fix(extensions): set image path * refactor(css): move vendor css to js import * style(app): remove whitespaces * fix(build-system): allow DevOps pipeline to leverage webpack (#2670) * Update devopsbuild task to use webpack & remove AppVeyor environment var * Added -Force to replace the existing dist folder * Removed Test-Path * dep(build-system): add angularjs-annotate to webpack + fix on imports * Merge branch 'develop' into webpack * refactor(app): webpack aliases for imports + async / await dep + start refactor * style(extensions): use develop version of the view * fix(app): fix several issues introduced by webpack migration * fix(webpack): fix ng-include not loading templates with webpack * Fix Windows CI with Webpack (#2782) * fix(configs): refactor broke configs creation and list views * fix(build-system): update build_binary_devops for Windows
2019-03-21 05:46:49 +00:00
import './createcontainer.css';
import { envVarsTabUtils } from '@/react/docker/containers/CreateView/EnvVarsTab';
import { getContainers } from '@/react/docker/containers/queries/containers';
import { resourcesTabUtils } from '@/react/docker/containers/CreateView/ResourcesTab';
import { restartPolicyTabUtils } from '@/react/docker/containers/CreateView/RestartPolicyTab';
angular.module('portainer.docker').controller('CreateContainerController', [
'$q',
'$scope',
'$async',
'$state',
'$timeout',
'$transition$',
'$analytics',
'Container',
'ContainerHelper',
'ImageHelper',
'NetworkService',
'ResourceControlService',
'Authentication',
'Notifications',
'ContainerService',
'ImageService',
'FormValidator',
'RegistryService',
'SystemService',
'SettingsService',
'HttpRequestHelper',
'endpoint',
function (
$q,
$scope,
$async,
$state,
$timeout,
$transition$,
$analytics,
Container,
ContainerHelper,
ImageHelper,
NetworkService,
ResourceControlService,
Authentication,
Notifications,
ContainerService,
ImageService,
FormValidator,
RegistryService,
SystemService,
SettingsService,
HttpRequestHelper,
endpoint
) {
$scope.create = create;
$scope.endpoint = endpoint;
$scope.containerWebhookFeature = FeatureId.CONTAINER_WEBHOOK;
$scope.formValues = {
alwaysPull: true,
GPU: {
enabled: false,
useSpecific: false,
2022-08-10 21:05:27 +00:00
selectedGPUs: ['all'],
capabilities: ['compute', 'utility'],
},
ExtraHosts: [],
MacAddress: '',
IPv4: '',
IPv6: '',
DnsPrimary: '',
DnsSecondary: '',
AccessControlData: new AccessControlFormData(),
NodeName: null,
RegistryModel: new PorImageRegistryModel(),
commands: commandsTabUtils.getDefaultViewModel(),
envVars: envVarsTabUtils.getDefaultViewModel(),
volumes: volumesTabUtils.getDefaultViewModel(),
network: networkTabUtils.getDefaultViewModel(),
resources: resourcesTabUtils.getDefaultViewModel(),
capabilities: capabilitiesTabUtils.getDefaultViewModel(),
restartPolicy: restartPolicyTabUtils.getDefaultViewModel(),
labels: labelsTabUtils.getDefaultViewModel(),
};
$scope.state = {
formValidationError: '',
actionInProgress: false,
mode: '',
pullImageValidity: true,
settingUnlimitedResources: false,
containerIsLoaded: false,
};
$scope.onAlwaysPullChange = onAlwaysPullChange;
$scope.handlePublishAllPortsChange = handlePublishAllPortsChange;
$scope.handleAutoRemoveChange = handleAutoRemoveChange;
$scope.handlePrivilegedChange = handlePrivilegedChange;
$scope.handleInitChange = handleInitChange;
$scope.handleCommandsChange = handleCommandsChange;
$scope.handleEnvVarsChange = handleEnvVarsChange;
function handleCommandsChange(commands) {
return $scope.$evalAsync(() => {
$scope.formValues.commands = commands;
});
}
function handleEnvVarsChange(value) {
return $scope.$evalAsync(() => {
$scope.formValues.envVars = value;
});
}
$scope.onVolumesChange = function (volumes) {
return $scope.$evalAsync(() => {
$scope.formValues.volumes = volumes;
});
};
$scope.onNetworkChange = function (network) {
return $scope.$evalAsync(() => {
$scope.formValues.network = network;
});
};
$scope.onLabelsChange = function (labels) {
return $scope.$evalAsync(() => {
$scope.formValues.labels = labels;
});
};
$scope.onResourcesChange = function (resources) {
return $scope.$evalAsync(() => {
$scope.formValues.resources = resources;
});
};
$scope.onCapabilitiesChange = function (capabilities) {
return $scope.$evalAsync(() => {
$scope.formValues.capabilities = capabilities;
});
};
$scope.onRestartPolicyChange = function (restartPolicy) {
return $scope.$evalAsync(() => {
$scope.formValues.restartPolicy = restartPolicy;
});
};
function onAlwaysPullChange(checked) {
return $scope.$evalAsync(() => {
$scope.formValues.alwaysPull = checked;
});
}
function handlePublishAllPortsChange(checked) {
return $scope.$evalAsync(() => {
$scope.config.HostConfig.PublishAllPorts = checked;
});
}
function handleAutoRemoveChange(checked) {
return $scope.$evalAsync(() => {
$scope.config.HostConfig.AutoRemove = checked;
});
}
function handlePrivilegedChange(checked) {
return $scope.$evalAsync(() => {
$scope.config.HostConfig.Privileged = checked;
});
}
function handleInitChange(checked) {
return $scope.$evalAsync(() => {
$scope.config.HostConfig.Init = checked;
});
}
$scope.refreshSlider = function () {
$timeout(function () {
$scope.$broadcast('rzSliderForceRender');
});
};
refactor(app): introduce webpack and babel (#2407) * feat(agent): add new host page * feat(agent): convert volume-browser to files-datatable * fix(agent): browse folders in file-datatable * feat(engine-details): replace engine view with host view * feat(engine-details): remove old panels * feat(engine-details): add basic engine-details-panel component * feat(engine-details): pass details to the different components * feat(engine-details): replace host-view with host-overview * feat(engine-details): add commaseperated filter * feat(engine-details): add host-view container component * feat(engine-details): add host-details component * feat(engine-details): build host details object * feat(engine-details): format engine version * feat(engine-details): get details for one node * feat(engine-details): pass is-agent from view * feat(engine-details): replace old node view with a new component * feat(engine-details): add swarm-node-details component * feat(engine-details): remove isSwarm binding * feat(engine-details): remove node-details and include in parent * feat(engine-details): add labels-table component * feat(engine-details): add update node service * feat(engine-details): add update label functionality * style(engine-details): remove whitespaces * feat(engine-details): remove old node page * feat(engine-details): pass is agent to host details * feat(host-details): hide missing info * feat(host-details): update node availability * style(host-details): remove obsolete event object * feat(host-details): fix labels not sending * feat(host-details): remove flags for hiding data * feat(host-details): create mock call to server for agent host info * style(host-details): fix spelling mistake in filter's name * feat(host-details): get info from agent * feat(host-details): hide engine labels when empty * feat(node-details): move labels table and save button * feat(host-info): add different urls for refresh * feat(host-details): show disk/devices info for agent * feat(host-view): add loading indicator to devices-panel * feat(host-details): add loading indicator to disks panel * feat(agent): fix browse volume * feat(agent): browse files * feat(agent): enable rename * feat(agent): download file * fix(agent): download file from root * feat(agent): delete file * style(agent): remove whitespaces * fix(agent): fix link on node browser * feat(agent): basic file uploader * feat(agent): add basic file upload * fix(volume-browser): move volume id to query params * feat(node-browser): moved uploader into browser * feat(node-browser): add upload spinner * feat(agent): browse files relative to root * feat(build): add webpack build config * feat(build): add missing imports * feat(webpack): add missing imports * feat(build): enable eslint on build * feat(build): add webpack notifier * feat(build): clean terminal on build * feat(build): import all globals * feat(build): add angular import * feat(build): fix styles * feat(build): load favicons * feat(build): load css before script * feat(webpack): split vendors css and js to a different bundle * feat(webpack): import angular in all files * feat(webpack): remove eslint global config * feat(webpack): add webpack clean dist * feat(webpack): fix styling issues * refactor(webpack): remove empty controllers * refactor(webpack): optimize moment * refactor(webpack): add bundle analyzer * feat(webpack): add babel * refactor(webpack): optimize lodash * refactor(toastr): update toastr * feat(webpack): create basic production and dev config * fix(webpack): fix production config * fix(webpack): fix html templates url * refactor(webpack): remove angular imports * refactor(webpack): remove more angular imports * refactor(webpack): return angular to entry file * style(webpack): remove comments from config * fix(hosts): remove browse button * fix(webpack): import lodash * fix(webpack): import missing htmls * feat(webpack): reduce lodash size * feat(webpack): config grunt to use webpack * feat(webpack): add postcss * chore(codeclimate): use eslint-5 channel * feat(deps): upgrade from lodash to lodash-es * fix(webpack): fix bug with lodash * chore(build): add build client script * fix(webpack): fix missing jsyaml reference * refactor(webpack): seperate builds of img files * chore(build): add a way to check times of webpack build * feat(webpack): add dev server * fix(webpack): fix css output name * chore(webpack): optimize images * chore(webpack): add node env * fix(build): copy templates on release * chore(webpack): set env NODE_ENV * feat(webpack): set NODE_ENV on production builds * fix(extensions): set image path * refactor(css): move vendor css to js import * style(app): remove whitespaces * fix(build-system): allow DevOps pipeline to leverage webpack (#2670) * Update devopsbuild task to use webpack & remove AppVeyor environment var * Added -Force to replace the existing dist folder * Removed Test-Path * dep(build-system): add angularjs-annotate to webpack + fix on imports * Merge branch 'develop' into webpack * refactor(app): webpack aliases for imports + async / await dep + start refactor * style(extensions): use develop version of the view * fix(app): fix several issues introduced by webpack migration * fix(webpack): fix ng-include not loading templates with webpack * Fix Windows CI with Webpack (#2782) * fix(configs): refactor broke configs creation and list views * fix(build-system): update build_binary_devops for Windows
2019-03-21 05:46:49 +00:00
$scope.onImageNameChange = function () {
$scope.formValues.CmdMode = 'default';
$scope.formValues.EntrypointMode = 'default';
};
$scope.setPullImageValidity = setPullImageValidity;
function setPullImageValidity(validity) {
if (!validity) {
$scope.formValues.alwaysPull = false;
}
$scope.state.pullImageValidity = validity;
}
$scope.config = {
Image: '',
Env: [],
Cmd: null,
MacAddress: '',
ExposedPorts: {},
Entrypoint: null,
WorkingDir: '',
User: '',
HostConfig: {
RestartPolicy: {
Name: 'no',
},
PortBindings: [],
PublishAllPorts: false,
Binds: [],
AutoRemove: false,
NetworkMode: 'bridge',
Privileged: false,
Init: false,
Runtime: null,
ExtraHosts: [],
Devices: [],
DeviceRequests: [],
CapAdd: [],
CapDrop: [],
Sysctls: {},
LogConfig: {
Type: '',
Config: {},
},
},
NetworkingConfig: {
EndpointsConfig: {},
},
Labels: {},
};
$scope.addPortBinding = function () {
$scope.config.HostConfig.PortBindings.push({ hostPort: '', containerPort: '', protocol: 'tcp' });
};
$scope.removePortBinding = function (index) {
$scope.config.HostConfig.PortBindings.splice(index, 1);
};
$scope.addExtraHost = function () {
$scope.formValues.ExtraHosts.push({ value: '' });
};
$scope.removeExtraHost = function (index) {
$scope.formValues.ExtraHosts.splice(index, 1);
};
$scope.addDevice = function () {
$scope.config.HostConfig.Devices.push({ pathOnHost: '', pathInContainer: '' });
};
$scope.removeDevice = function (index) {
$scope.config.HostConfig.Devices.splice(index, 1);
};
$scope.onGpuChange = function (values) {
return $async(async () => {
$scope.formValues.GPU = values;
});
};
$scope.addSysctl = function () {
$scope.formValues.Sysctls.push({ name: '', value: '' });
};
$scope.removeSysctl = function (index) {
$scope.formValues.Sysctls.splice(index, 1);
};
$scope.fromContainerMultipleNetworks = false;
function prepareImageConfig(config) {
const imageConfig = ImageHelper.createImageConfigForContainer($scope.formValues.RegistryModel);
config.Image = imageConfig.fromImage;
}
function preparePortBindings(config) {
const bindings = ContainerHelper.preparePortBindings(config.HostConfig.PortBindings);
config.ExposedPorts = {};
_.forEach(bindings, (_, key) => (config.ExposedPorts[key] = {}));
config.HostConfig.PortBindings = bindings;
}
function prepareConfiguration() {
var config = angular.copy($scope.config);
config = commandsTabUtils.toRequest(config, $scope.formValues.commands);
config = envVarsTabUtils.toRequest(config, $scope.formValues.envVars);
config = volumesTabUtils.toRequest(config, $scope.formValues.volumes);
config = networkTabUtils.toRequest(config, $scope.formValues.network, $scope.fromContainer.Id);
config = resourcesTabUtils.toRequest(config, $scope.formValues.resources);
config = capabilitiesTabUtils.toRequest(config, $scope.formValues.capabilities);
config = restartPolicyTabUtils.toRequest(config, $scope.formValues.restartPolicy);
config = labelsTabUtils.toRequest(config, $scope.formValues.labels);
prepareImageConfig(config);
preparePortBindings(config);
return config;
}
function loadFromContainerPortBindings() {
const bindings = ContainerHelper.sortAndCombinePorts($scope.config.HostConfig.PortBindings);
$scope.config.HostConfig.PortBindings = bindings;
}
function loadFromContainerImageConfig() {
feat(app): rework private registries and support private registries in kubernetes EE-30 (#5131) * feat(app): rework private registries and support private registries in kubernetes [EE-30] feat(api): backport private registries backend changes (#5072) * feat(api/bolt): backport bolt changes * feat(api/exec): backport exec changes * feat(api/http): backport http/handler/dockerhub changes * feat(api/http): backport http/handler/endpoints changes * feat(api/http): backport http/handler/registries changes * feat(api/http): backport http/handler/stacks changes * feat(api/http): backport http/handler changes * feat(api/http): backport http/proxy/factory/azure changes * feat(api/http): backport http/proxy/factory/docker changes * feat(api/http): backport http/proxy/factory/utils changes * feat(api/http): backport http/proxy/factory/kubernetes changes * feat(api/http): backport http/proxy/factory changes * feat(api/http): backport http/security changes * feat(api/http): backport http changes * feat(api/internal): backport internal changes * feat(api): backport api changes * feat(api/kubernetes): backport kubernetes changes * fix(api/http): changes on backend following backport feat(app): backport private registries frontend changes (#5056) * feat(app/docker): backport docker/components changes * feat(app/docker): backport docker/helpers changes * feat(app/docker): backport docker/views/container changes * feat(app/docker): backport docker/views/images changes * feat(app/docker): backport docker/views/registries changes * feat(app/docker): backport docker/views/services changes * feat(app/docker): backport docker changes * feat(app/kubernetes): backport kubernetes/components changes * feat(app/kubernetes): backport kubernetes/converters changes * feat(app/kubernetes): backport kubernetes/models changes * feat(app/kubernetes): backport kubernetes/registries changes * feat(app/kubernetes): backport kubernetes/services changes * feat(app/kubernetes): backport kubernetes/views/applications changes * feat(app/kubernetes): backport kubernetes/views/configurations changes * feat(app/kubernetes): backport kubernetes/views/configure changes * feat(app/kubernetes): backport kubernetes/views/resource-pools changes * feat(app/kubernetes): backport kubernetes/views changes * feat(app/portainer): backport portainer/components/accessManagement changes * feat(app/portainer): backport portainer/components/datatables changes * feat(app/portainer): backport portainer/components/forms changes * feat(app/portainer): backport portainer/components/registry-details changes * feat(app/portainer): backport portainer/models changes * feat(app/portainer): backport portainer/rest changes * feat(app/portainer): backport portainer/services changes * feat(app/portainer): backport portainer/views changes * feat(app/portainer): backport portainer changes * feat(app): backport app changes * config(project): gitignore + jsconfig changes gitignore all files under api/cmd/portainer but main.go and enable Code Editor autocomplete on import ... from '@/...' fix(app): fix pull rate limit checker fix(app/registries): sidebar menus and registry accesses users filtering fix(api): add missing kube client factory fix(kube): fetch dockerhub pull limits (#5133) fix(app): pre review fixes (#5142) * fix(app/registries): remove checkbox for endpointRegistries view * fix(endpoints): allow access to default namespace * fix(docker): fetch pull limits * fix(kube/ns): show selected registries for non admin Co-authored-by: Chaim Lev-Ari <chiptus@gmail.com> chore(webpack): ignore missing sourcemaps fix(registries): fetch registry config from url feat(kube/registries): ignore not found when deleting secret feat(db): move migration to db 31 fix(registries): fix bugs in PR EE-869 (#5169) * fix(registries): hide role * fix(endpoints): set empty access policy to edge endpoint * fix(registry): remove double arguments * fix(admin): ignore warning * feat(kube/configurations): tag registry secrets (#5157) * feat(kube/configurations): tag registry secrets * feat(kube/secrets): show registry secrets for admins * fix(registries): move dockerhub to beginning * refactor(registries): use endpoint scoped registries feat(registries): filter by namespace if supplied feat(access-managment): filter users for registry (#5191) * refactor(access-manage): move users selector to component * feat(access-managment): filter users for registry refactor(registries): sync code with CE (#5200) * refactor(registry): add inspect handler under endpoints * refactor(endpoint): sync endpoint_registries_list * refactor(endpoints): sync registry_access * fix(db): rename migration functions * fix(registries): show accesses for admin * fix(kube): set token on transport * refactor(kube): move secret help to bottom * fix(kuberentes): remove shouldLog parameter * style(auth): add description of security.IsAdmin * feat(security): allow admin access to registry * feat(edge): connect to edge endpoint when creating client * style(portainer): change deprecation version * refactor(sidebar): hide manage * refactor(containers): revert changes * style(container): remove whitespace * fix(endpoint): add handler to registy on endpointService * refactor(image): use endpointService.registries * fix(kueb/namespaces): rename resource pool to namespace * fix(kube/namespace): move selected registries * fix(api/registries): hide accesses on registry creation Co-authored-by: LP B <xAt0mZ@users.noreply.github.com> refactor(api): remove code duplication after rebase fix(app/registries): replace last registry api usage by endpoint registry api fix(api/endpoints): update registry access policies on endpoint deletion (#5226) [EE-1027] fix(db): update db version * fix(dockerhub): fetch rate limits * fix(registry/tests): supply restricred context * fix(registries): show proget registry only when selected * fix(registry): create dockerhub registry * feat(db): move migrations to db 32 Co-authored-by: Chaim Lev-Ari <chiptus@gmail.com>
2021-07-14 09:15:21 +00:00
RegistryService.retrievePorRegistryModelFromRepository($scope.config.Image, endpoint.Id)
.then((model) => {
$scope.formValues.RegistryModel = model;
})
.catch(function error(err) {
Notifications.error('Failure', err, 'Unable to retrieve registry');
});
}
function loadFromContainerSpec() {
// Get container
Container.get({ id: $transition$.params().from })
.$promise.then(function success(d) {
var fromContainer = new ContainerDetailsViewModel(d);
if (fromContainer.ResourceControl) {
if (fromContainer.ResourceControl.Public) {
$scope.formValues.AccessControlData.AccessControlEnabled = false;
}
// When the container is create by duplicate/edit, the access permission
// shouldn't be copied
fromContainer.ResourceControl.UserAccesses = [];
fromContainer.ResourceControl.TeamAccesses = [];
}
$scope.fromContainer = fromContainer;
$scope.state.mode = 'duplicate';
$scope.config = ContainerHelper.configFromContainer(angular.copy(d));
$scope.formValues.commands = commandsTabUtils.toViewModel(d);
$scope.formValues.envVars = envVarsTabUtils.toViewModel(d);
$scope.formValues.volumes = volumesTabUtils.toViewModel(d);
$scope.formValues.network = networkTabUtils.toViewModel(d, $scope.availableNetworks, $scope.runningContainers);
$scope.formValues.resources = resourcesTabUtils.toViewModel(d);
$scope.formValues.capabilities = capabilitiesTabUtils.toViewModel(d);
$scope.formValues.labels = labelsTabUtils.toViewModel(d);
$scope.formValues.restartPolicy = restartPolicyTabUtils.toViewModel(d);
loadFromContainerPortBindings(d);
loadFromContainerImageConfig(d);
})
.then(() => {
$scope.state.containerIsLoaded = true;
})
.catch(function error(err) {
Notifications.error('Failure', err, 'Unable to retrieve container');
});
}
async function initView() {
var nodeName = $transition$.params().nodeName;
$scope.formValues.NodeName = nodeName;
HttpRequestHelper.setPortainerAgentTargetHeader(nodeName);
$scope.isAdmin = Authentication.isAdmin();
$scope.showDeviceMapping = await shouldShowDevices();
$scope.allowSysctl = await shouldShowSysctls();
$scope.areContainerCapabilitiesEnabled = await checkIfContainerCapabilitiesEnabled();
$scope.isAdminOrEndpointAdmin = Authentication.isAdmin();
var provider = $scope.applicationState.endpoint.mode.provider;
var apiVersion = $scope.applicationState.endpoint.apiVersion;
NetworkService.networks(provider === 'DOCKER_STANDALONE' || provider === 'DOCKER_SWARM_MODE', false, provider === 'DOCKER_SWARM_MODE' && apiVersion >= 1.25)
.then(function success(networks) {
networks.push({ Name: 'container' });
$scope.availableNetworks = networks.sort((a, b) => a.Name.localeCompare(b.Name));
$scope.formValues.network = networkTabUtils.getDefaultViewModel(networks.some((network) => network.Name === 'bridge'));
})
.catch(function error(err) {
Notifications.error('Failure', err, 'Unable to retrieve networks');
});
getContainers(endpoint.Id)
.then((containers) => {
$scope.runningContainers = containers;
$scope.gpuUseAll = _.get($scope, 'endpoint.Snapshots[0].GpuUseAll', false);
$scope.gpuUseList = _.get($scope, 'endpoint.Snapshots[0].GpuUseList', []);
if ($transition$.params().from) {
loadFromContainerSpec();
} else {
$scope.state.containerIsLoaded = true;
$scope.fromContainer = {};
if ($scope.areContainerCapabilitiesEnabled) {
$scope.formValues.capabilities = capabilitiesTabUtils.getDefaultViewModel();
}
}
})
.catch((e) => {
Notifications.error('Failure', e, 'Unable to retrieve running containers');
});
SystemService.info()
.then(function success(data) {
$scope.availableRuntimes = data.Runtimes ? Object.keys(data.Runtimes) : [];
$scope.state.sliderMaxCpu = 32;
if (data.NCPU) {
$scope.state.sliderMaxCpu = data.NCPU;
}
$scope.state.sliderMaxMemory = 32768;
if (data.MemTotal) {
$scope.state.sliderMaxMemory = Math.floor(data.MemTotal / 1000 / 1000);
}
})
.catch(function error(err) {
Notifications.error('Failure', err, 'Unable to retrieve engine details');
});
$scope.allowBindMounts = $scope.isAdminOrEndpointAdmin || endpoint.SecuritySettings.allowBindMountsForRegularUsers;
$scope.allowPrivilegedMode = endpoint.SecuritySettings.allowPrivilegedModeForRegularUsers;
}
function validateForm(accessControlData, isAdmin) {
$scope.state.formValidationError = '';
var error = '';
error = FormValidator.validateAccessControl(accessControlData, isAdmin);
if (error) {
$scope.state.formValidationError = error;
return false;
}
return true;
}
$scope.handleResourceChange = handleResourceChange;
function handleResourceChange() {
$scope.state.settingUnlimitedResources = false;
if (
($scope.config.HostConfig.Memory > 0 && $scope.formValues.MemoryLimit === 0) ||
($scope.config.HostConfig.MemoryReservation > 0 && $scope.formValues.MemoryReservation === 0) ||
($scope.config.HostConfig.NanoCpus > 0 && $scope.formValues.CpuLimit === 0)
) {
$scope.state.settingUnlimitedResources = true;
}
}
$scope.redeployUnlimitedResources = function (resources) {
return $async(async () => {
$scope.formValues.resources = resources;
return create();
});
};
function create() {
var oldContainer = null;
HttpRequestHelper.setPortainerAgentTargetHeader($scope.formValues.NodeName);
return findCurrentContainer().then(setOldContainer).then(confirmCreateContainer).then(startCreationProcess).catch(notifyOnError).finally(final);
function final() {
$scope.state.actionInProgress = false;
}
function setOldContainer(container) {
oldContainer = container;
return container;
}
function findCurrentContainer() {
return Container.query({ all: 1, filters: { name: ['^/' + $scope.config.name + '$'] } })
.$promise.then(function onQuerySuccess(containers) {
if (!containers.length) {
return;
}
return containers[0];
})
.catch(notifyOnError);
function notifyOnError(err) {
Notifications.error('Failure', err, 'Unable to retrieve containers');
}
}
function startCreationProcess(confirmed) {
if (!confirmed) {
return $q.when();
}
if (!validateAccessControl()) {
return $q.when();
}
$scope.state.actionInProgress = true;
return pullImageIfNeeded()
.then(stopAndRenameContainer)
.then(createNewContainer)
.then(applyResourceControl)
.then(connectToExtraNetworks)
.then(removeOldContainer)
.then(onSuccess)
.catch(onCreationProcessFail);
}
function onCreationProcessFail(error) {
var deferred = $q.defer();
removeNewContainer()
.then(restoreOldContainerName)
.then(function () {
deferred.reject(error);
})
.catch(function (restoreError) {
deferred.reject(restoreError);
});
return deferred.promise;
}
function removeNewContainer() {
return findCurrentContainer().then(function onContainerLoaded(container) {
if (container && (!oldContainer || container.Id !== oldContainer.Id)) {
return ContainerService.remove(container, true);
}
});
}
function restoreOldContainerName() {
if (!oldContainer) {
return;
}
return ContainerService.renameContainer(oldContainer.Id, oldContainer.Names[0]);
}
function confirmCreateContainer(container) {
if (!container) {
return $q.when(true);
}
return showConfirmationModal();
function showConfirmationModal() {
var deferred = $q.defer();
confirmDestructive({
title: 'Are you sure?',
message: 'A container with the same name already exists. Portainer can automatically remove it and re-create one. Do you want to replace it?',
confirmButton: buildConfirmButton('Replace', 'danger'),
}).then(function onConfirm(confirmed) {
deferred.resolve(confirmed);
});
return deferred.promise;
}
}
function stopAndRenameContainer() {
if (!oldContainer) {
return $q.when();
}
return stopContainerIfNeeded(oldContainer).then(renameContainer);
}
function stopContainerIfNeeded(oldContainer) {
if (oldContainer.State !== 'running') {
return $q.when();
}
return ContainerService.stopContainer(oldContainer.Id);
}
function renameContainer() {
return ContainerService.renameContainer(oldContainer.Id, oldContainer.Names[0] + '-old');
}
function pullImageIfNeeded() {
return $q.when($scope.formValues.alwaysPull && ImageService.pullImage($scope.formValues.RegistryModel, true));
}
function createNewContainer() {
return $async(async () => {
const config = prepareConfiguration();
return await ContainerService.createAndStartContainer(config);
});
}
feat(api): rewrite access control management in Docker (#3337) * feat(api): decorate Docker resource creation response with resource control * fix(api): fix a potential resource control conflict between stacks/volumes * feat(api): generate a default private resource control instead of admin only * fix(api): fix default RC value * fix(api): update RC authorizations check to support admin only flag * refactor(api): relocate access control related methods * fix(api): fix a potential conflict when fetching RC from database * refactor(api): refactor access control logic * refactor(api): remove the concept of DecoratedStack * feat(api): automatically remove RC when removing a Docker resource * refactor(api): update filter resource methods documentation * refactor(api): update proxy package structure * refactor(api): renamed proxy/misc package * feat(api): re-introduce ResourceControlDelete operation as admin restricted * refactor(api): relocate default endpoint authorizations * feat(api): migrate RBAC data * feat(app): ResourceControl management refactor * fix(api): fix access control issue on stack deletion and automatically delete RC * fix(api): fix stack filtering * fix(api): fix UpdateResourceControl operation checks * refactor(api): introduce a NewTransport builder method * refactor(api): inject endpoint in Docker transport * refactor(api): introduce Docker client into Docker transport * refactor(api): refactor http/proxy package * feat(api): inspect a Docker resource labels during access control validation * fix(api): only apply automatic resource control creation on success response * fix(api): fix stack access control check * fix(api): use StatusCreated instead of StatusOK for automatic resource control creation * fix(app): resource control fixes * fix(api): fix an issue preventing administrator to inspect a resource with a RC * refactor(api): remove useless error return * refactor(api): document DecorateStacks function * fix(api): fix invalid resource control type for container deletion * feat(api): support Docker system networks * feat(api): update Swagger docs * refactor(api): rename transport variable * refactor(api): rename transport variable * feat(networks): add system tag for system networks * feat(api): add support for resource control labels * feat(api): upgrade to DBVersion 22 * refactor(api): refactor access control management in Docker proxy * refactor(api): re-implement docker proxy taskListOperation * refactor(api): review parameters declaration * refactor(api): remove extra blank line * refactor(api): review method comments * fix(api): fix invalid ServerAddress property and review method visibility * feat(api): update error message * feat(api): update restrictedVolumeBrowserOperation method * refactor(api): refactor method parameters * refactor(api): minor refactor * refactor(api): change Azure transport visibility * refactor(api): update struct documentation * refactor(api): update struct documentation * feat(api): review restrictedResourceOperation method * refactor(api): remove unused authorization methods * feat(api): apply RBAC when enabled on stack operations * fix(api): fix invalid data migration procedure for DBVersion = 22 * fix(app): RC duplicate on private resource * feat(api): change Docker API version logic for libcompose/client factory * fix(api): update access denied error message to be Docker API compliant * fix(api): update volume browsing authorizations data migration * fix(api): fix an issue with access control in multi-node agent Swarm cluster
2019-11-12 23:41:42 +00:00
async function sendAnalytics() {
const publicSettings = await SettingsService.publicSettings();
const analyticsAllowed = publicSettings.EnableTelemetry;
const image = `${$scope.formValues.RegistryModel.Registry.URL}/${$scope.formValues.RegistryModel.Image}`;
if (analyticsAllowed && $scope.formValues.GPU.enabled) {
$analytics.eventTrack('gpuContainerCreated', {
category: 'docker',
metadata: { gpu: $scope.formValues.GPU, containerImage: image },
});
}
}
function applyResourceControl(newContainer) {
const userId = Authentication.getUserDetails().ID;
const resourceControl = newContainer.Portainer.ResourceControl;
const containerId = newContainer.Id;
const accessControlData = $scope.formValues.AccessControlData;
return ResourceControlService.applyResourceControl(userId, accessControlData, resourceControl).then(function onApplyResourceControlSuccess() {
return containerId;
});
}
function connectToExtraNetworks(newContainerId) {
if (!$scope.formValues.network.extraNetworks) {
return $q.when();
}
var connectionPromises = _.forOwn($scope.formValues.network.extraNetworks, function (network, networkName) {
if (_.has(network, 'Aliases')) {
var aliases = _.filter(network.Aliases, (o) => {
return !_.startsWith($scope.fromContainer.Id, o);
});
}
return NetworkService.connectContainer(networkName, newContainerId, aliases);
});
return $q.all(connectionPromises);
}
function removeOldContainer() {
var deferred = $q.defer();
if (!oldContainer) {
deferred.resolve();
return;
}
ContainerService.remove(oldContainer, true).then(notifyOnRemoval).catch(notifyOnRemoveError);
return deferred.promise;
function notifyOnRemoval() {
Notifications.success('Container Removed', oldContainer.Id);
deferred.resolve();
}
function notifyOnRemoveError(err) {
deferred.reject({ msg: 'Unable to remove container', err: err });
}
}
function notifyOnError(err) {
Notifications.error('Failure', err, 'Unable to create container');
}
function validateAccessControl() {
var accessControlData = $scope.formValues.AccessControlData;
return validateForm(accessControlData, $scope.isAdmin);
}
async function onSuccess() {
await sendAnalytics();
Notifications.success('Success', 'Container successfully created');
$state.go('docker.containers', {}, { reload: true });
}
}
async function shouldShowDevices() {
return endpoint.SecuritySettings.allowDeviceMappingForRegularUsers || Authentication.isAdmin();
}
async function shouldShowSysctls() {
return endpoint.SecuritySettings.allowSysctlSettingForRegularUsers || Authentication.isAdmin();
}
async function checkIfContainerCapabilitiesEnabled() {
return endpoint.SecuritySettings.allowContainerCapabilitiesForRegularUsers || Authentication.isAdmin();
}
initView();
},
]);