api/src/lib/docker.ts

98 lines · 2924 bytes

 1// Turns a Portainer template into docker run / compose usage output
 2
 3export interface TemplateEnv {
 4  name: string
 5  label?: string
 6  default?: string
 7  description?: string
 8}
 9
10export interface TemplateVolume {
11  container: string
12  bind?: string
13  readonly?: boolean
14}
15
16export interface Template {
17  title?: string
18  name?: string
19  image?: string
20  logo?: string
21  description?: string
22  categories?: string[]
23  ports?: string[]
24  env?: TemplateEnv[]
25  volumes?: TemplateVolume[]
26  restart_policy?: string
27}
28
29// Strip everything but alphanumerics so loose name matching works
30export const normalize = (str: string) => str.replace(/[^a-z0-9]/gi, '').toLowerCase()
31
32// Minimal YAML serialiser, enough for the compose object we build
33const toYaml = (data: unknown, indent = ''): string[] => {
34  const lines: string[] = []
35  if (Array.isArray(data)) {
36    for (const el of data) lines.push(`${indent}- ${scalar(el)}`)
37  } else if (data && typeof data === 'object') {
38    for (const [key, value] of Object.entries(data)) {
39      if (value === undefined || value === null) continue
40      if (typeof value === 'object') {
41        const child = toYaml(value, `${indent}  `)
42        if (!child.length) continue
43        lines.push(`${indent}${key}:`)
44        lines.push(...child)
45      } else {
46        lines.push(`${indent}${key}: ${scalar(value)}`)
47      }
48    }
49  }
50  return lines
51}
52
53// Quote scalars holding a colon so ports/images aren't misread as YAML maps or sexagesimals
54const scalar = (value: unknown): string => {
55  const str = String(value)
56  return str.includes(':') ? `"${str}"` : str
57}
58
59// Volume mount, host:container when a host bind is given, else an anonymous volume
60const mount = (vol: TemplateVolume) =>
61  vol.bind ? `${vol.bind}:${vol.container}` : vol.container
62
63// A copy-pasteable `docker run` command for the template
64export const runCommand = (t: Template): string => {
65  const parts = ['docker run -d']
66  for (const port of t.ports ?? []) parts.push(`-p ${port}`)
67  for (const env of t.env ?? []) parts.push(`-e ${env.name}=\${${env.name}}`)
68  for (const vol of t.volumes ?? []) {
69    parts.push(`-v ${mount(vol)}${vol.readonly ? ':ro' : ''}`)
70  }
71  if (t.restart_policy) parts.push(`--restart=${t.restart_policy}`)
72  parts.push(t.image ?? '')
73  return parts.join(' \\\n  ')
74}
75
76// Equivalent docker-compose.yml as a YAML string
77export const composeFile = (t: Template): string => {
78  const service =
79    (t.title ?? 'app')
80      .toLowerCase()
81      .replace(/[^a-z0-9]+/g, '-')
82      .replace(/^-+|-+$/g, '') || 'app'
83  const compose = {
84    version: '3.8',
85    services: {
86      [service]: {
87        image: t.image,
88        ports: t.ports ?? [],
89        environment: Object.fromEntries(
90          (t.env ?? []).map((e) => [e.name, e.default ?? '']),
91        ),
92        volumes: (t.volumes ?? []).map(mount),
93        restart: t.restart_policy,
94      },
95    },
96  }
97  return toYaml(compose).join('\n')
98}