1
0
Fork 0
mirror of https://github.com/portainer/portainer.git synced 2025-08-02 20:35:25 +02:00

chore(project): add prettier for code format (#3645)

* chore(project): install prettier and lint-staged

* chore(project): apply prettier to html too

* chore(project): git ignore eslintcache

* chore(project): add a comment about format script

* chore(prettier): update printWidth

* chore(prettier): remove useTabs option

* chore(prettier): add HTML validation

* refactor(prettier): fix closing tags

* feat(prettier): define angular parser for html templates

* style(prettier): run prettier on codebase

Co-authored-by: Anthony Lapenna <lapenna.anthony@gmail.com>
This commit is contained in:
Chaim Lev-Ari 2020-04-11 00:54:53 +03:00 committed by GitHub
parent 6663073be1
commit cf5056d9c0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
714 changed files with 31228 additions and 28305 deletions

View file

@ -1,34 +1,35 @@
angular.module('portainer.docker')
.factory('ConfigHelper', [function ConfigHelperFactory() {
'use strict';
return {
flattenConfig: function(config) {
if (config) {
return {
Id: config.ConfigID,
Name: config.ConfigName,
FileName: config.File.Name,
Uid: config.File.UID,
Gid: config.File.GID,
Mode: config.File.Mode
};
}
return {};
},
configConfig: function(config) {
if (config) {
return {
ConfigID: config.Id,
ConfigName: config.Name,
File: {
Name: config.FileName || config.Name,
UID: config.Uid || '0',
GID: config.Gid || '0',
Mode: config.Mode || 292
}
};
}
return {};
}
};
}]);
angular.module('portainer.docker').factory('ConfigHelper', [
function ConfigHelperFactory() {
'use strict';
return {
flattenConfig: function (config) {
if (config) {
return {
Id: config.ConfigID,
Name: config.ConfigName,
FileName: config.File.Name,
Uid: config.File.UID,
Gid: config.File.GID,
Mode: config.File.Mode,
};
}
return {};
},
configConfig: function (config) {
if (config) {
return {
ConfigID: config.Id,
ConfigName: config.Name,
File: {
Name: config.FileName || config.Name,
UID: config.Uid || '0',
GID: config.Gid || '0',
Mode: config.Mode || 292,
},
};
}
return {};
},
};
},
]);

View file

@ -12,18 +12,16 @@ var patterns = {
nodeHostname: 'node.hostname',
nodeRole: 'node.role',
nodeLabels: 'node.labels.',
engineLabels: 'engine.labels.'
engineLabels: 'engine.labels.',
},
op: {
eq: '==',
neq: '!='
}
neq: '!=',
},
};
function matchesConstraint(value, constraint) {
if (!constraint ||
(constraint.op === patterns.op.eq && value === constraint.value) ||
(constraint.op === patterns.op.neq && value !== constraint.value)) {
if (!constraint || (constraint.op === patterns.op.eq && value === constraint.value) || (constraint.op === patterns.op.neq && value !== constraint.value)) {
return true;
}
return false;
@ -47,8 +45,8 @@ function extractCustomLabelKey(constraint, op, baseLabelKey) {
return constraint.split(op).shift().trim().replace(baseLabelKey, '');
}
angular.module('portainer.docker')
.factory('ConstraintsHelper', [function ConstraintsHelperFactory() {
angular.module('portainer.docker').factory('ConstraintsHelper', [
function ConstraintsHelperFactory() {
'use strict';
return {
transformConstraints: function (constraints) {
@ -94,7 +92,8 @@ angular.module('portainer.docker')
return true;
}
var constraints = this.transformConstraints(angular.copy(service.Constraints));
if (matchesConstraint(node.Id, constraints.nodeId) &&
if (
matchesConstraint(node.Id, constraints.nodeId) &&
matchesConstraint(node.Hostname, constraints.nodeHostname) &&
matchesConstraint(node.Role, constraints.nodeRole) &&
matchesLabel(node.Labels, constraints.nodeLabels) &&
@ -103,6 +102,7 @@ angular.module('portainer.docker')
return true;
}
return false;
}
},
};
}]);
},
]);

View file

@ -1,5 +1,5 @@
import _ from 'lodash-es';
import splitargs from 'splitargs/src/splitargs'
import splitargs from 'splitargs/src/splitargs';
const portPattern = /^([1-9]|[1-5]?[0-9]{2,4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/m;
@ -33,8 +33,7 @@ function isValidPortRange(portRange) {
portRange = parsePortRange();
}
return Array.isArray(portRange) && portRange.length === 2 &&
portRange[0] > 0 && portRange[1] >= portRange[0];
return Array.isArray(portRange) && portRange.length === 2 && portRange[0] > 0 && portRange[1] >= portRange[0];
}
function createPortRange(portRangeText, port) {
@ -49,7 +48,7 @@ function createPortRange(portRangeText, port) {
portRangeText = portRangeText.substr(colonIndex + 1);
}
port = (typeof port === 'number' ? port : parsePort(port));
port = typeof port === 'number' ? port : parsePort(port);
const portRange = parsePortRange(portRangeText);
const startPort = Math.min(portRange[0], port);
const endPort = Math.max(portRange[1], port);
@ -61,178 +60,181 @@ function createPortRange(portRangeText, port) {
}
}
angular.module('portainer.docker')
.factory('ContainerHelper', [function ContainerHelperFactory() {
'use strict';
var helper = {};
angular.module('portainer.docker').factory('ContainerHelper', [
function ContainerHelperFactory() {
'use strict';
var helper = {};
helper.commandStringToArray = function(command) {
return splitargs(command);
};
helper.commandArrayToString = function(array) {
return array.map(function(elem) {
return '\'' + elem + '\'';
}).join(' ');
};
helper.configFromContainer = function(container) {
var config = container.Config;
// HostConfig
config.HostConfig = container.HostConfig;
// Name
config.name = container.Name.replace(/^\//g, '');
// Network
var mode = config.HostConfig.NetworkMode;
config.NetworkingConfig = {
'EndpointsConfig': {}
helper.commandStringToArray = function (command) {
return splitargs(command);
};
config.NetworkingConfig.EndpointsConfig = container.NetworkSettings.Networks;
if (mode.indexOf('container:') !== -1) {
delete config.Hostname;
delete config.ExposedPorts;
}
// Set volumes
var binds = [];
var volumes = {};
for (var v in container.Mounts) {
if ({}.hasOwnProperty.call(container.Mounts, v)) {
var mount = container.Mounts[v];
var name = mount.Name || mount.Source;
var containerPath = mount.Destination;
if (name && containerPath) {
var bind = name + ':' + containerPath;
volumes[containerPath] = {};
if (mount.RW === false) {
bind += ':ro';
helper.commandArrayToString = function (array) {
return array
.map(function (elem) {
return "'" + elem + "'";
})
.join(' ');
};
helper.configFromContainer = function (container) {
var config = container.Config;
// HostConfig
config.HostConfig = container.HostConfig;
// Name
config.name = container.Name.replace(/^\//g, '');
// Network
var mode = config.HostConfig.NetworkMode;
config.NetworkingConfig = {
EndpointsConfig: {},
};
config.NetworkingConfig.EndpointsConfig = container.NetworkSettings.Networks;
if (mode.indexOf('container:') !== -1) {
delete config.Hostname;
delete config.ExposedPorts;
}
// Set volumes
var binds = [];
var volumes = {};
for (var v in container.Mounts) {
if ({}.hasOwnProperty.call(container.Mounts, v)) {
var mount = container.Mounts[v];
var name = mount.Name || mount.Source;
var containerPath = mount.Destination;
if (name && containerPath) {
var bind = name + ':' + containerPath;
volumes[containerPath] = {};
if (mount.RW === false) {
bind += ':ro';
}
binds.push(bind);
}
binds.push(bind);
}
}
}
config.HostConfig.Binds = binds;
config.Volumes = volumes;
return config;
};
config.HostConfig.Binds = binds;
config.Volumes = volumes;
return config;
};
helper.preparePortBindings = function(portBindings) {
const bindings = {};
_.forEach(portBindings, (portBinding) => {
if (!portBinding.containerPort) {
return;
}
let hostPort = portBinding.hostPort;
const containerPortRange = parsePortRange(portBinding.containerPort);
if (!isValidPortRange(containerPortRange)) {
throw new Error('Invalid port specification: ' + portBinding.containerPort);
}
const startPort = containerPortRange[0];
const endPort = containerPortRange[1];
let hostIp = undefined;
let startHostPort = 0;
let endHostPort = 0;
if (hostPort) {
if (hostPort.indexOf(':') > -1) {
const hostAndPort = _.split(hostPort, ':');
hostIp = hostAndPort[0];
hostPort = hostAndPort[1];
helper.preparePortBindings = function (portBindings) {
const bindings = {};
_.forEach(portBindings, (portBinding) => {
if (!portBinding.containerPort) {
return;
}
const hostPortRange = parsePortRange(hostPort);
if (!isValidPortRange(hostPortRange)) {
throw new Error('Invalid port specification: ' + hostPort);
let hostPort = portBinding.hostPort;
const containerPortRange = parsePortRange(portBinding.containerPort);
if (!isValidPortRange(containerPortRange)) {
throw new Error('Invalid port specification: ' + portBinding.containerPort);
}
startHostPort = hostPortRange[0];
endHostPort = hostPortRange[1];
if (endPort !== startPort && (endPort - startPort) !== (endHostPort - startHostPort)) {
throw new Error('Invalid port specification: ' + hostPort);
}
}
const startPort = containerPortRange[0];
const endPort = containerPortRange[1];
let hostIp = undefined;
let startHostPort = 0;
let endHostPort = 0;
if (hostPort) {
if (hostPort.indexOf(':') > -1) {
const hostAndPort = _.split(hostPort, ':');
hostIp = hostAndPort[0];
hostPort = hostAndPort[1];
}
for (let i = 0; i <= (endPort - startPort); i++) {
const containerPort = (startPort + i).toString();
if (startHostPort > 0) {
hostPort = (startHostPort + i).toString();
}
if (startPort === endPort && startHostPort !== endHostPort) {
hostPort += '-' + endHostPort.toString();
const hostPortRange = parsePortRange(hostPort);
if (!isValidPortRange(hostPortRange)) {
throw new Error('Invalid port specification: ' + hostPort);
}
startHostPort = hostPortRange[0];
endHostPort = hostPortRange[1];
if (endPort !== startPort && endPort - startPort !== endHostPort - startHostPort) {
throw new Error('Invalid port specification: ' + hostPort);
}
}
const bindKey = containerPort + '/' + portBinding.protocol;
bindings[bindKey] = [{ HostIp: hostIp, HostPort: hostPort }];
}
});
return bindings;
};
for (let i = 0; i <= endPort - startPort; i++) {
const containerPort = (startPort + i).toString();
if (startHostPort > 0) {
hostPort = (startHostPort + i).toString();
}
if (startPort === endPort && startHostPort !== endHostPort) {
hostPort += '-' + endHostPort.toString();
}
helper.sortAndCombinePorts = function(portBindings) {
const bindings = [];
const portBindingKeys = _.keys(portBindings);
const bindKey = containerPort + '/' + portBinding.protocol;
bindings[bindKey] = [{ HostIp: hostIp, HostPort: hostPort }];
}
});
return bindings;
};
// Group the port bindings by protocol
const portBindingKeysByProtocol = _.groupBy(portBindingKeys, (portKey) => {
return _.split(portKey, '/')[1];
});
helper.sortAndCombinePorts = function (portBindings) {
const bindings = [];
const portBindingKeys = _.keys(portBindings);
_.forEach(portBindingKeysByProtocol, (portBindingKeys, protocol) => {
// Group the port bindings by host IP
const portBindingKeysByHostIp = _.groupBy(portBindingKeys, (portKey) => {
const portBinding = portBindings[portKey][0];
return portBinding.HostIp || '';
// Group the port bindings by protocol
const portBindingKeysByProtocol = _.groupBy(portBindingKeys, (portKey) => {
return _.split(portKey, '/')[1];
});
_.forEach(portBindingKeysByHostIp, (portBindingKeys) => {
// Sort by host port
const sortedPortBindingKeys = _.orderBy(portBindingKeys, (portKey) => {
return parseInt(_.split(portKey, '/')[0]);
_.forEach(portBindingKeysByProtocol, (portBindingKeys, protocol) => {
// Group the port bindings by host IP
const portBindingKeysByHostIp = _.groupBy(portBindingKeys, (portKey) => {
const portBinding = portBindings[portKey][0];
return portBinding.HostIp || '';
});
let previousHostPort = -1;
let previousContainerPort = -1;
_.forEach(sortedPortBindingKeys, (portKey) => {
const portKeySplit = _.split(portKey, '/');
const containerPort = parseInt(portKeySplit[0]);
const portBinding = portBindings[portKey][0];
const hostPort = parsePort(portBinding.HostPort);
_.forEach(portBindingKeysByHostIp, (portBindingKeys) => {
// Sort by host port
const sortedPortBindingKeys = _.orderBy(portBindingKeys, (portKey) => {
return parseInt(_.split(portKey, '/')[0]);
});
let previousHostPort = -1;
let previousContainerPort = -1;
_.forEach(sortedPortBindingKeys, (portKey) => {
const portKeySplit = _.split(portKey, '/');
const containerPort = parseInt(portKeySplit[0]);
const portBinding = portBindings[portKey][0];
const hostPort = parsePort(portBinding.HostPort);
// We only combine single ports, and skip the host port ranges on one container port
if (hostPort > 0) {
// If we detect consecutive ports, we create a range of them
if (bindings.length > 0 && previousHostPort === hostPort - 1 && previousContainerPort === containerPort - 1) {
bindings[bindings.length - 1].hostPort = createPortRange(bindings[bindings.length - 1].hostPort, hostPort);
bindings[bindings.length - 1].containerPort = createPortRange(bindings[bindings.length - 1].containerPort, containerPort);
previousHostPort = hostPort;
previousContainerPort = containerPort;
return;
}
// We only combine single ports, and skip the host port ranges on one container port
if (hostPort > 0) {
// If we detect consecutive ports, we create a range of them
if (bindings.length > 0 && previousHostPort === (hostPort - 1) && previousContainerPort === (containerPort - 1)) {
bindings[bindings.length-1].hostPort = createPortRange(bindings[bindings.length-1].hostPort, hostPort);
bindings[bindings.length-1].containerPort = createPortRange(bindings[bindings.length-1].containerPort, containerPort);
previousHostPort = hostPort;
previousContainerPort = containerPort;
return;
} else {
previousHostPort = -1;
previousContainerPort = -1;
}
previousHostPort = hostPort;
previousContainerPort = containerPort;
} else {
previousHostPort = -1;
previousContainerPort = -1;
}
let bindingHostPort = portBinding.HostPort.toString();
if (portBinding.HostIp) {
bindingHostPort = portBinding.HostIp + ':' + bindingHostPort;
}
let bindingHostPort = portBinding.HostPort.toString();
if (portBinding.HostIp) {
bindingHostPort = portBinding.HostIp + ':' + bindingHostPort;
}
const binding = {
hostPort: bindingHostPort,
containerPort: containerPort,
protocol: protocol
};
bindings.push(binding);
const binding = {
hostPort: bindingHostPort,
containerPort: containerPort,
protocol: protocol,
};
bindings.push(binding);
});
});
});
});
return bindings;
};
return bindings;
};
return helper;
}]);
return helper;
},
]);

View file

@ -1,72 +1,73 @@
import _ from 'lodash-es';
import { RegistryTypes } from 'Extensions/registry-management/models/registryTypes';
angular.module('portainer.docker')
.factory('ImageHelper', [function ImageHelperFactory() {
'use strict';
angular.module('portainer.docker').factory('ImageHelper', [
function ImageHelperFactory() {
'use strict';
var helper = {};
var helper = {};
helper.isValidTag = isValidTag;
helper.createImageConfigForContainer = createImageConfigForContainer;
helper.getImagesNamesForDownload = getImagesNamesForDownload;
helper.removeDigestFromRepository = removeDigestFromRepository;
helper.imageContainsURL = imageContainsURL;
helper.isValidTag = isValidTag;
helper.createImageConfigForContainer = createImageConfigForContainer;
helper.getImagesNamesForDownload = getImagesNamesForDownload;
helper.removeDigestFromRepository = removeDigestFromRepository;
helper.imageContainsURL = imageContainsURL;
function isValidTag(tag) {
return tag.match(/^(?![\.\-])([a-zA-Z0-9\_\.\-])+$/g);
}
function isValidTag(tag) {
return tag.match(/^(?![\.\-])([a-zA-Z0-9\_\.\-])+$/g);
}
function getImagesNamesForDownload(images) {
var names = images.map(function(image) {
return image.RepoTags[0] !== '<none>:<none>' ? image.RepoTags[0] : image.Id;
});
return {
names: names
};
}
function getImagesNamesForDownload(images) {
var names = images.map(function (image) {
return image.RepoTags[0] !== '<none>:<none>' ? image.RepoTags[0] : image.Id;
});
return {
names: names,
};
}
/**
*
* @param {PorImageRegistryModel} registry
*/
function createImageConfigForContainer(registry) {
const data = {
fromImage: ''
};
let fullImageName = '';
/**
*
* @param {PorImageRegistryModel} registry
*/
function createImageConfigForContainer(registry) {
const data = {
fromImage: '',
};
let fullImageName = '';
if (registry.UseRegistry) {
if (registry.Registry.Type === RegistryTypes.GITLAB) {
const slash = _.startsWith(registry.Image, ':') ? '' : '/';
fullImageName = registry.Registry.URL + '/' + registry.Registry.Gitlab.ProjectPath + slash + registry.Image;
if (registry.UseRegistry) {
if (registry.Registry.Type === RegistryTypes.GITLAB) {
const slash = _.startsWith(registry.Image, ':') ? '' : '/';
fullImageName = registry.Registry.URL + '/' + registry.Registry.Gitlab.ProjectPath + slash + registry.Image;
} else {
const url = registry.Registry.URL ? registry.Registry.URL + '/' : '';
fullImageName = url + registry.Image;
}
if (!_.includes(registry.Image, ':')) {
fullImageName += ':latest';
}
} else {
const url = registry.Registry.URL ? registry.Registry.URL + '/' : '';
fullImageName = url + registry.Image;
fullImageName = registry.Image;
}
if (!_.includes(registry.Image, ':')) {
fullImageName += ':latest';
}
} else {
fullImageName = registry.Image;
data.fromImage = fullImageName;
return data;
}
data.fromImage = fullImageName;
return data;
}
function imageContainsURL(image) {
const split = _.split(image, '/');
const url = split[0];
if (split.length > 1) {
return _.includes(url, '.') || _.includes(url, ':');
function imageContainsURL(image) {
const split = _.split(image, '/');
const url = split[0];
if (split.length > 1) {
return _.includes(url, '.') || _.includes(url, ':');
}
return false;
}
return false;
}
function removeDigestFromRepository(repository) {
return repository.split('@sha')[0];
}
function removeDigestFromRepository(repository) {
return repository.split('@sha')[0];
}
return helper;
}]);
return helper;
},
]);

View file

@ -1,38 +1,39 @@
import _ from 'lodash-es';
angular.module('portainer.docker')
.factory('InfoHelper', [function InfoHelperFactory() {
'use strict';
angular.module('portainer.docker').factory('InfoHelper', [
function InfoHelperFactory() {
'use strict';
var helper = {};
var helper = {};
helper.determineEndpointMode = function(info, type) {
var mode = {
provider: '',
role: '',
agentProxy: false
helper.determineEndpointMode = function (info, type) {
var mode = {
provider: '',
role: '',
agentProxy: false,
};
if (type === 2 || type === 4) {
mode.agentProxy = true;
}
if (!info.Swarm || _.isEmpty(info.Swarm.NodeID)) {
if (info.ID === 'vSphere Integrated Containers') {
mode.provider = 'VMWARE_VIC';
} else {
mode.provider = 'DOCKER_STANDALONE';
}
} else {
mode.provider = 'DOCKER_SWARM_MODE';
if (info.Swarm.ControlAvailable) {
mode.role = 'MANAGER';
} else {
mode.role = 'WORKER';
}
}
return mode;
};
if (type === 2 || type === 4) {
mode.agentProxy = true;
}
if (!info.Swarm || _.isEmpty(info.Swarm.NodeID)) {
if (info.ID === 'vSphere Integrated Containers') {
mode.provider = 'VMWARE_VIC';
} else {
mode.provider = 'DOCKER_STANDALONE';
}
} else {
mode.provider = 'DOCKER_SWARM_MODE';
if (info.Swarm.ControlAvailable) {
mode.role = 'MANAGER';
} else {
mode.role = 'WORKER';
}
}
return mode;
};
return helper;
}]);
return helper;
},
]);

View file

@ -1,25 +1,26 @@
angular.module('portainer.docker')
.factory('LabelHelper', [function LabelHelperFactory() {
'use strict';
return {
fromLabelHashToKeyValue: function(labels) {
if (labels) {
return Object.keys(labels).map(function(key) {
return {key: key, value: labels[key], originalKey: key, originalValue: labels[key], added: true};
});
}
return [];
},
fromKeyValueToLabelHash: function(labelKV) {
var labels = {};
if (labelKV) {
labelKV.forEach(function(label) {
if (label.key) {
labels[label.key] = label.value;
}
});
}
return labels;
}
};
}]);
angular.module('portainer.docker').factory('LabelHelper', [
function LabelHelperFactory() {
'use strict';
return {
fromLabelHashToKeyValue: function (labels) {
if (labels) {
return Object.keys(labels).map(function (key) {
return { key: key, value: labels[key], originalKey: key, originalValue: labels[key], added: true };
});
}
return [];
},
fromKeyValueToLabelHash: function (labelKV) {
var labels = {};
if (labelKV) {
labelKV.forEach(function (label) {
if (label.key) {
labels[label.key] = label.value;
}
});
}
return labels;
},
};
},
]);

View file

@ -1,22 +1,22 @@
angular.module('portainer.docker')
.factory('LogHelper', [function LogHelperFactory() {
'use strict';
var helper = {};
angular.module('portainer.docker').factory('LogHelper', [
function LogHelperFactory() {
'use strict';
var helper = {};
// Return an array with each line being an entry.
// It will also remove any ANSI code related character sequences.
// If the skipHeaders param is specified, it will strip the 8 first characters of each line.
helper.formatLogs = function(logs, skipHeaders) {
logs = logs.replace(
/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');
// Return an array with each line being an entry.
// It will also remove any ANSI code related character sequences.
// If the skipHeaders param is specified, it will strip the 8 first characters of each line.
helper.formatLogs = function (logs, skipHeaders) {
logs = logs.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');
if (skipHeaders) {
logs = logs.substring(8);
logs = logs.replace(/\n(.{8})/g, '\n\r');
}
if (skipHeaders) {
logs = logs.substring(8);
logs = logs.replace(/\n(.{8})/g, '\n\r');
}
return logs.split('\n');
};
return logs.split('\n');
};
return helper;
}]);
return helper;
},
]);

View file

@ -1,14 +1,15 @@
angular.module('portainer.docker')
.factory('NodeHelper', [function NodeHelperFactory() {
'use strict';
return {
nodeToConfig: function(node) {
return {
Name: node.Spec.Name,
Role: node.Spec.Role,
Labels: node.Spec.Labels,
Availability: node.Spec.Availability
};
}
};
}]);
angular.module('portainer.docker').factory('NodeHelper', [
function NodeHelperFactory() {
'use strict';
return {
nodeToConfig: function (node) {
return {
Name: node.Spec.Name,
Role: node.Spec.Role,
Labels: node.Spec.Labels,
Availability: node.Spec.Availability,
};
},
};
},
]);

View file

@ -1,34 +1,35 @@
angular.module('portainer.docker')
.factory('SecretHelper', [function SecretHelperFactory() {
'use strict';
return {
flattenSecret: function(secret) {
if (secret) {
return {
Id: secret.SecretID,
Name: secret.SecretName,
FileName: secret.File.Name,
Uid: secret.File.UID,
Gid: secret.File.GID,
Mode: secret.File.Mode
};
}
return {};
},
secretConfig: function(secret) {
if (secret) {
return {
SecretID: secret.Id,
SecretName: secret.Name,
File: {
Name: secret.FileName,
UID: secret.Uid || '0',
GID: secret.Gid || '0',
Mode: secret.Mode || 444
}
};
}
return {};
}
};
}]);
angular.module('portainer.docker').factory('SecretHelper', [
function SecretHelperFactory() {
'use strict';
return {
flattenSecret: function (secret) {
if (secret) {
return {
Id: secret.SecretID,
Name: secret.SecretName,
FileName: secret.File.Name,
Uid: secret.File.UID,
Gid: secret.File.GID,
Mode: secret.File.Mode,
};
}
return {};
},
secretConfig: function (secret) {
if (secret) {
return {
SecretID: secret.Id,
SecretName: secret.Name,
File: {
Name: secret.FileName,
UID: secret.Uid || '0',
GID: secret.Gid || '0',
Mode: secret.Mode || 444,
},
};
}
return {};
},
};
},
]);

View file

@ -1,250 +1,251 @@
import moment from 'moment';
angular.module('portainer.docker')
.factory('ServiceHelper', [function ServiceHelperFactory() {
'use strict';
angular.module('portainer.docker').factory('ServiceHelper', [
function ServiceHelperFactory() {
'use strict';
var helper = {};
var helper = {};
helper.associateTasksToService = function(service, tasks) {
service.Tasks = [];
var otherServicesTasks = [];
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
if (task.ServiceId === service.Id) {
service.Tasks.push(task);
task.ServiceName = service.Name;
} else {
otherServicesTasks.push(task);
helper.associateTasksToService = function (service, tasks) {
service.Tasks = [];
var otherServicesTasks = [];
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
if (task.ServiceId === service.Id) {
service.Tasks.push(task);
task.ServiceName = service.Name;
} else {
otherServicesTasks.push(task);
}
}
}
tasks = otherServicesTasks;
};
helper.serviceToConfig = function(service) {
return {
Name: service.Spec.Name,
Labels: service.Spec.Labels,
TaskTemplate: service.Spec.TaskTemplate,
Mode: service.Spec.Mode,
UpdateConfig: service.Spec.UpdateConfig,
Networks: service.Spec.Networks,
EndpointSpec: service.Spec.EndpointSpec
tasks = otherServicesTasks;
};
};
helper.translateKeyValueToPlacementPreferences = function(keyValuePreferences) {
if (keyValuePreferences) {
var preferences = [];
keyValuePreferences.forEach(function(preference) {
if (preference.strategy && preference.strategy !== '' && preference.value && preference.value !== '') {
switch (preference.strategy.toLowerCase()) {
case 'spread':
preferences.push({
'Spread': {
'SpreadDescriptor': preference.value
}
});
break;
helper.serviceToConfig = function (service) {
return {
Name: service.Spec.Name,
Labels: service.Spec.Labels,
TaskTemplate: service.Spec.TaskTemplate,
Mode: service.Spec.Mode,
UpdateConfig: service.Spec.UpdateConfig,
Networks: service.Spec.Networks,
EndpointSpec: service.Spec.EndpointSpec,
};
};
helper.translateKeyValueToPlacementPreferences = function (keyValuePreferences) {
if (keyValuePreferences) {
var preferences = [];
keyValuePreferences.forEach(function (preference) {
if (preference.strategy && preference.strategy !== '' && preference.value && preference.value !== '') {
switch (preference.strategy.toLowerCase()) {
case 'spread':
preferences.push({
Spread: {
SpreadDescriptor: preference.value,
},
});
break;
}
}
}
});
return preferences;
}
return [];
};
helper.translateKeyValueToPlacementConstraints = function(keyValueConstraints) {
if (keyValueConstraints) {
var constraints = [];
keyValueConstraints.forEach(function(constraint) {
if (constraint.key && constraint.key !== '' && constraint.value && constraint.value !== '') {
constraints.push(constraint.key + constraint.operator + constraint.value);
}
});
return constraints;
}
return [];
};
helper.translateEnvironmentVariables = function(env) {
if (env) {
var variables = [];
env.forEach(function(variable) {
var idx = variable.indexOf('=');
var keyValue = [variable.slice(0, idx), variable.slice(idx + 1)];
var originalValue = (keyValue.length > 1) ? keyValue[1] : '';
variables.push({
key: keyValue[0],
value: originalValue,
originalKey: keyValue[0],
originalValue: originalValue,
added: true
});
});
return variables;
}
return [];
};
return preferences;
}
return [];
};
helper.translateEnvironmentVariablesToEnv = function(env) {
if (env) {
var variables = [];
env.forEach(function(variable) {
if (variable.key && variable.key !== '') {
variables.push(variable.key + '=' + variable.value);
}
});
return variables;
}
return [];
};
helper.translateKeyValueToPlacementConstraints = function (keyValueConstraints) {
if (keyValueConstraints) {
var constraints = [];
keyValueConstraints.forEach(function (constraint) {
if (constraint.key && constraint.key !== '' && constraint.value && constraint.value !== '') {
constraints.push(constraint.key + constraint.operator + constraint.value);
}
});
return constraints;
}
return [];
};
helper.translatePreferencesToKeyValue = function(preferences) {
if (preferences) {
var keyValuePreferences = [];
preferences.forEach(function(preference) {
if (preference.Spread) {
keyValuePreferences.push({
strategy: 'Spread',
value: preference.Spread.SpreadDescriptor
helper.translateEnvironmentVariables = function (env) {
if (env) {
var variables = [];
env.forEach(function (variable) {
var idx = variable.indexOf('=');
var keyValue = [variable.slice(0, idx), variable.slice(idx + 1)];
var originalValue = keyValue.length > 1 ? keyValue[1] : '';
variables.push({
key: keyValue[0],
value: originalValue,
originalKey: keyValue[0],
originalValue: originalValue,
added: true,
});
}
});
return keyValuePreferences;
}
return [];
};
helper.translateConstraintsToKeyValue = function(constraints) {
function getOperator(constraint) {
var indexEquals = constraint.indexOf('==');
if (indexEquals >= 0) {
return [indexEquals, '=='];
}
return [constraint.indexOf('!='), '!='];
}
if (constraints) {
var keyValueConstraints = [];
constraints.forEach(function(constraint) {
var operatorIndices = getOperator(constraint);
var key = constraint.slice(0, operatorIndices[0]);
var operator = operatorIndices[1];
var value = constraint.slice(operatorIndices[0] + 2);
keyValueConstraints.push({
key: key,
value: value,
operator: operator,
originalKey: key,
originalValue: value
});
});
return keyValueConstraints;
}
};
helper.translateHumanDurationToNanos = function(humanDuration) {
var nanos;
var regex = /^([0-9]+)(h|m|s|ms|us|ns)$/i;
var matches = humanDuration.match(regex);
if (matches !== null && matches.length === 3) {
var duration = parseInt(matches[1], 10);
var unit = matches[2];
// Moment.js cannot use micro or nanoseconds
switch (unit) {
case 'ns':
nanos = duration;
break;
case 'us':
nanos = duration * 1000;
break;
default:
nanos = moment.duration(duration, unit).asMilliseconds() * 1000000;
return variables;
}
}
return nanos;
};
return [];
};
// Convert nanoseconds to the higher unit possible
// e.g 1840 nanoseconds = 1804ns
// e.g 300000000000 nanoseconds = 5m
// e.g 3510000000000 nanoseconds = 3510s
// e.g 3540000000000 nanoseconds = 59m
// e.g 3600000000000 nanoseconds = 1h
helper.translateNanosToHumanDuration = function(nanos) {
var humanDuration = '0s';
var conversionFromNano = {};
conversionFromNano['ns'] = 1;
conversionFromNano['us'] = conversionFromNano['ns'] * 1000;
conversionFromNano['ms'] = conversionFromNano['us'] * 1000;
conversionFromNano['s'] = conversionFromNano['ms'] * 1000;
conversionFromNano['m'] = conversionFromNano['s'] * 60;
conversionFromNano['h'] = conversionFromNano['m'] * 60;
Object.keys(conversionFromNano).forEach(function(unit) {
if ( nanos % conversionFromNano[unit] === 0 && (nanos / conversionFromNano[unit]) > 0) {
humanDuration = (nanos / conversionFromNano[unit]) + unit;
}
});
return humanDuration;
};
helper.translateLogDriverOptsToKeyValue = function(logOptions) {
var options = [];
if (logOptions) {
Object.keys(logOptions).forEach(function(key) {
options.push({
key: key,
value: logOptions[key],
originalKey: key,
originalValue: logOptions[key],
added: true
helper.translateEnvironmentVariablesToEnv = function (env) {
if (env) {
var variables = [];
env.forEach(function (variable) {
if (variable.key && variable.key !== '') {
variables.push(variable.key + '=' + variable.value);
}
});
});
}
return options;
};
return variables;
}
return [];
};
helper.translateKeyValueToLogDriverOpts = function(keyValueLogDriverOpts) {
var options = {};
if (keyValueLogDriverOpts) {
keyValueLogDriverOpts.forEach(function(option) {
if (option.key && option.key !== '' && option.value && option.value !== '') {
options[option.key] = option.value;
helper.translatePreferencesToKeyValue = function (preferences) {
if (preferences) {
var keyValuePreferences = [];
preferences.forEach(function (preference) {
if (preference.Spread) {
keyValuePreferences.push({
strategy: 'Spread',
value: preference.Spread.SpreadDescriptor,
});
}
});
return keyValuePreferences;
}
return [];
};
helper.translateConstraintsToKeyValue = function (constraints) {
function getOperator(constraint) {
var indexEquals = constraint.indexOf('==');
if (indexEquals >= 0) {
return [indexEquals, '=='];
}
return [constraint.indexOf('!='), '!='];
}
if (constraints) {
var keyValueConstraints = [];
constraints.forEach(function (constraint) {
var operatorIndices = getOperator(constraint);
var key = constraint.slice(0, operatorIndices[0]);
var operator = operatorIndices[1];
var value = constraint.slice(operatorIndices[0] + 2);
keyValueConstraints.push({
key: key,
value: value,
operator: operator,
originalKey: key,
originalValue: value,
});
});
return keyValueConstraints;
}
};
helper.translateHumanDurationToNanos = function (humanDuration) {
var nanos;
var regex = /^([0-9]+)(h|m|s|ms|us|ns)$/i;
var matches = humanDuration.match(regex);
if (matches !== null && matches.length === 3) {
var duration = parseInt(matches[1], 10);
var unit = matches[2];
// Moment.js cannot use micro or nanoseconds
switch (unit) {
case 'ns':
nanos = duration;
break;
case 'us':
nanos = duration * 1000;
break;
default:
nanos = moment.duration(duration, unit).asMilliseconds() * 1000000;
}
}
return nanos;
};
// Convert nanoseconds to the higher unit possible
// e.g 1840 nanoseconds = 1804ns
// e.g 300000000000 nanoseconds = 5m
// e.g 3510000000000 nanoseconds = 3510s
// e.g 3540000000000 nanoseconds = 59m
// e.g 3600000000000 nanoseconds = 1h
helper.translateNanosToHumanDuration = function (nanos) {
var humanDuration = '0s';
var conversionFromNano = {};
conversionFromNano['ns'] = 1;
conversionFromNano['us'] = conversionFromNano['ns'] * 1000;
conversionFromNano['ms'] = conversionFromNano['us'] * 1000;
conversionFromNano['s'] = conversionFromNano['ms'] * 1000;
conversionFromNano['m'] = conversionFromNano['s'] * 60;
conversionFromNano['h'] = conversionFromNano['m'] * 60;
Object.keys(conversionFromNano).forEach(function (unit) {
if (nanos % conversionFromNano[unit] === 0 && nanos / conversionFromNano[unit] > 0) {
humanDuration = nanos / conversionFromNano[unit] + unit;
}
});
}
return options;
};
return humanDuration;
};
helper.translateHostsEntriesToHostnameIP = function(entries) {
var ipHostEntries = [];
if (entries) {
entries.forEach(function(entry) {
if (entry.indexOf(' ') && entry.split(' ').length === 2) {
var keyValue = entry.split(' ');
ipHostEntries.push({ hostname: keyValue[1], ip: keyValue[0]});
}
});
}
return ipHostEntries;
};
helper.translateLogDriverOptsToKeyValue = function (logOptions) {
var options = [];
if (logOptions) {
Object.keys(logOptions).forEach(function (key) {
options.push({
key: key,
value: logOptions[key],
originalKey: key,
originalValue: logOptions[key],
added: true,
});
});
}
return options;
};
helper.translateHostnameIPToHostsEntries = function(entries) {
var ipHostEntries = [];
if (entries) {
entries.forEach(function(entry) {
if (entry.ip && entry.hostname) {
ipHostEntries.push(entry.ip + ' ' + entry.hostname);
}
});
}
return ipHostEntries;
};
helper.translateKeyValueToLogDriverOpts = function (keyValueLogDriverOpts) {
var options = {};
if (keyValueLogDriverOpts) {
keyValueLogDriverOpts.forEach(function (option) {
if (option.key && option.key !== '' && option.value && option.value !== '') {
options[option.key] = option.value;
}
});
}
return options;
};
return helper;
}]);
helper.translateHostsEntriesToHostnameIP = function (entries) {
var ipHostEntries = [];
if (entries) {
entries.forEach(function (entry) {
if (entry.indexOf(' ') && entry.split(' ').length === 2) {
var keyValue = entry.split(' ');
ipHostEntries.push({ hostname: keyValue[1], ip: keyValue[0] });
}
});
}
return ipHostEntries;
};
helper.translateHostnameIPToHostsEntries = function (entries) {
var ipHostEntries = [];
if (entries) {
entries.forEach(function (entry) {
if (entry.ip && entry.hostname) {
ipHostEntries.push(entry.ip + ' ' + entry.hostname);
}
});
}
return ipHostEntries;
};
return helper;
},
]);

View file

@ -1,18 +1,19 @@
angular.module('portainer.docker')
.factory('TaskHelper', [function TaskHelperFactory() {
'use strict';
angular.module('portainer.docker').factory('TaskHelper', [
function TaskHelperFactory() {
'use strict';
var helper = {};
var helper = {};
helper.associateContainerToTask = function(task, containers) {
for (var i = 0; i < containers.length; i++) {
var container = containers[i];
if (task.ContainerId === container.Id) {
task.Container = container;
break;
helper.associateContainerToTask = function (task, containers) {
for (var i = 0; i < containers.length; i++) {
var container = containers[i];
if (task.ContainerId === container.Id) {
task.Container = container;
break;
}
}
}
};
};
return helper;
}]);
return helper;
},
]);

View file

@ -1,30 +1,31 @@
angular.module('portainer.docker')
.factory('VolumeHelper', [function VolumeHelperFactory() {
'use strict';
var helper = {};
angular.module('portainer.docker').factory('VolumeHelper', [
function VolumeHelperFactory() {
'use strict';
var helper = {};
helper.createDriverOptions = function(optionArray) {
var options = {};
optionArray.forEach(function (option) {
options[option.name] = option.value;
});
return options;
};
helper.createDriverOptions = function (optionArray) {
var options = {};
optionArray.forEach(function (option) {
options[option.name] = option.value;
});
return options;
};
helper.isVolumeUsedByAService = function(volume, services) {
for (var i = 0; i < services.length; i++) {
var service = services[i];
var mounts = service.Mounts;
for (var j = 0; j < mounts.length; j++) {
var mount = mounts[j];
if (mount.Source === volume.Id) {
return true;
helper.isVolumeUsedByAService = function (volume, services) {
for (var i = 0; i < services.length; i++) {
var service = services[i];
var mounts = service.Mounts;
for (var j = 0; j < mounts.length; j++) {
var mount = mounts[j];
if (mount.Source === volume.Id) {
return true;
}
}
}
}
return false;
};
return false;
};
return helper;
}]);
return helper;
},
]);