summaryrefslogtreecommitdiffstats
path: root/server/lib/shell.js
blob: 77c5dcc2b64fce62816cc0c73e4c3d695d95acce (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/* global __appdir */
var path = require('path')
var shell = require('shelljs')
var io = require(path.join(__appdir, 'lib', 'socketio'))
const fs = require('fs')
// Only one building process per version at a time.

module.exports = {
  buildIpxe: async function (buildParameters = [], gitURL = 'http://git.ipxe.org/ipxe.git', gitBranch = '') {
    var makeCmd = ''

    // Only one building process can be running. (lock the ipxe directory)
    // TODO:
    // If file is already locked
    // if (false) return { status: 'ALREADY_BUILDING', error: 'iPXE-building process is already in progress.' }

    makeCmd = 'make ' + buildParameters.join(' ')
    makeCmd += ' EMBED=' + path.join(__appdir, 'ipxe', 'embedded.ipxe')
    makeCmd += ' TRUST=' + path.join(__appdir, 'bin', 'fullchain.pem')

    // Cloning git.
    sendToLog('Cloning git ...\n', 'primary')
    await cloneIpxe(gitURL, gitBranch)

    // Copying configs.
    sendToLog('Copying configs ...\n', 'primary')
    copyConfigs()

    // Make ipxe.
    sendToLog('Make iPXE ...\n', 'primary')
    shell.cd(path.join(__appdir, 'ipxe', 'ipxeGIT', 'src'))

    await new Promise((resolve, reject) => {
      const process = shell.exec(makeCmd, { async: true }, () => {
        resolve()
      })

      // Send the output to the frontend log.
      process.stdout.on('data', data => {
        const multiline = data.split('\n')
        if (multiline.length > 2) {
          multiline.forEach(line => {
            if (line) sendToLog(line, 'normal')
          })
        } else sendToLog(data, 'normal')
      })
      process.stderr.on('data', data => {
        const multiline = data.split('\n')
        if (multiline.length > 2) {
          multiline.forEach(line => {
            if (line) sendToLog(line, 'error')
          })
        } else sendToLog(data, 'error')
      })
    })

    // Copy and rename the ipxe file to the __appdir/ipxe/builds/<date> dir.
    sendToLog('Copying ipxe file(s) ...\n', 'primary')
    const date = new Date()
    const timestamp = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + '_' + date.getHours() + '-' + date.getMinutes() + '-' + date.getSeconds()

    for (let buildtarget of buildParameters) {
      const target = buildtarget.split('/')
      shell.mkdir('-p', path.join(__appdir, 'ipxe', 'builds', timestamp, target[0]))
      shell.cp(path.join(__appdir, 'ipxe', 'ipxeGIT', 'src', buildtarget), path.join(__appdir, 'ipxe', 'builds', timestamp, target[0], target[1]))
      sendToLog('Copyed ' + buildtarget, 'success')
    }
    sendToLog('Finished copying\n', 'success')
    // sendToLog(ipxeVersion, 'done\n', 'success')
    // shell.mv(path.join(__appdir, 'ipxe', 'undionly.kpxe'), path.join(__appdir, 'ipxe', 'ipxe.' + ipxeVersion))
    // updateInProgress(ipxeVersion, false)
  },

  cancelBuilding: async function () {
    /*
    const ipxeVersion = req.params.version
    const process = make[ipxeVersion]
    if (process) {
      const kill = 'pkill -P ' + process.pid
      shell.exec(kill)
      updateInProgress(ipxeVersion, false)
    }
    res.send({ status: 'SUCCESS', data: process })
    */
  },

  clean: async function () {
    // If building return
    // return { status: 'ALREADY_BUILDING', error: 'Can\'t clean, while iPXE-building is in progress.' }

    // TODO more logging of what get's deleted
    shell.cd(path.join(__appdir, 'ipxe'))
    shell.rm('-rf', 'ipxeGIT')
    shell.rm(path.join(__appdir, 'ipxe', 'ipxelog.txt'))
    sendToLog('iPXE files successfully cleaned', 'success', false)
    return { status: 'SUCCESS', msg: 'Cleaning iPXE started' }
  },

  status: function (ipxeVersion) {
    return false
  },

  /* Changes or creates a symbolic link to a builded ipxe */
  forceSymlink: function (source, dest) {
    // Because of the shelljs lib is bugged handle broken links deletetion myself
    var destinationExists
    try {
      fs.lstatSync(dest)
      destinationExists = true
    } catch (err) {
      destinationExists = false
    }

    if (destinationExists) {
      fs.unlinkSync(dest)
    }

    const ln = shell.ln('-sf', source, dest)
    if (ln.stderr) return { status: 'ERROR', error: ln.stderr }
    else return { status: 'SUCCESS' }
  },

  readdirRecursive: function (buildsPath) {
    let structure = []
    try {
      const directory = fs.readdirSync(buildsPath)
      for (let obj of directory) {
        if (!fs.lstatSync(path.join(buildsPath, obj)).isDirectory()) {
          structure.push({ name: obj, type: 'file' })
        } else {
          structure.push({ name: obj, type: 'directory', children: this.readdirRecursive(path.join(buildsPath, obj)) })
        }
      }
    } catch (error) {
      return []
    }
    return structure
  },

  forceDeleteBuild: function (buildsPath) {
    shell.rm('-rf', path.join(buildsPath))
  }
}

async function cloneIpxe (url, branch) {
  // Check if git is installed on the server.
  if (!shell.which('git')) return { status: 'GIT_MISSING', error: 'Please install git on the server.' }

  shell.cd(path.join(__appdir, 'ipxe'))
  return new Promise((resolve, reject) => {
    let command = 'git clone ' + url
    if (branch) command += ' --branch ' + branch + ' --single-branch'
    var clone = shell.exec(command + ' ipxeGIT', { async: true }, () => {
      resolve()
    })
    clone.stdout.on('data', data => {
      sendToLog(data, 'normal')
    })
    clone.stderr.on('data', data => {
      sendToLog(data, 'error')
    })
  })
}

function copyConfigs (ipxeVersion) {
  // Remove the default configs and paste in the customized ones.
  shell.rm(path.join(__appdir, 'ipxe', 'ipxeGIT', 'src', 'config', 'general.h'))
  shell.rm(path.join(__appdir, 'ipxe', 'ipxeGIT', 'src', 'config', 'console.h'))
  shell.cp(path.join(__appdir, 'ipxe', 'general.h'), path.join(__appdir, 'ipxe', 'ipxeGIT', 'src', 'config', 'general.h'))
  shell.cp(path.join(__appdir, 'ipxe', 'console.h'), path.join(__appdir, 'ipxe', 'ipxeGIT', 'src', 'config', 'console.h'))
}

function sendToLog (msg, status, log = true) {
  const date = new Date()
  const pad = x => x < 10 ? '0' + x : x
  var dateString = '[' + date.getFullYear() + '-'
  dateString += pad(date.getMonth() + 1) + '-'
  dateString += pad(date.getDate()) + ' '
  dateString += pad(date.getHours()) + ':'
  dateString += pad(date.getMinutes()) + ':'
  dateString += pad(date.getSeconds()) + ']'

  const logEntry = { date: dateString, status: status, msg: msg }

  const event = 'log'
  io.in('broadcast ipxeBuild').emit(event, logEntry)
  if (log) writeLog(logEntry)
}

function writeLog (logEntry) {
  fs.writeFile(path.join(__appdir, 'ipxe', 'ipxelog.txt'), logEntry.date + '\t' + logEntry.status + '\t' + logEntry.msg, { flag: 'a+' }, (err) => {
    if (err) throw err
  })
}