agent.js 6.52 KB
Newer Older
1
// ===========================================
2
// Wiki.js - Background Agent
3 4 5 6
// 1.0.0
// Licensed under AGPLv3
// ===========================================

7 8 9 10 11 12
const path = require('path')
const ROOTPATH = process.cwd()
const SERVERPATH = path.join(ROOTPATH, 'server')

global.ROOTPATH = ROOTPATH
global.SERVERPATH = SERVERPATH
NGPixel's avatar
NGPixel committed
13
const IS_DEBUG = process.env.NODE_ENV === 'development'
14 15 16 17

let appconf = require('./libs/config')()
global.appconfig = appconf.config
global.appdata = appconf.data
18 19

// ----------------------------------------
20
// Load Winston
21 22
// ----------------------------------------

NGPixel's avatar
NGPixel committed
23
global.winston = require('./libs/logger')(IS_DEBUG, 'AGENT')
24 25

// ----------------------------------------
26
// Load global modules
27 28
// ----------------------------------------

29
global.winston.info('Background Agent is initializing...')
30

31
global.db = require('./libs/db').init()
32 33 34
global.upl = require('./libs/uploads-agent').init()
global.git = require('./libs/git').init()
global.entries = require('./libs/entries').init()
NGPixel's avatar
NGPixel committed
35
global.lang = require('i18next')
36
global.mark = require('./libs/markdown')
37 38 39 40

// ----------------------------------------
// Load modules
// ----------------------------------------
41

42 43 44 45 46
const moment = require('moment')
const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs-extra'))
const klaw = require('klaw')
const Cron = require('cron').CronJob
47
const i18nBackend = require('i18next-node-fs-backend')
48

NGPixel's avatar
NGPixel committed
49 50
const entryHelper = require('./helpers/entry')

NGPixel's avatar
NGPixel committed
51 52 53 54
// ----------------------------------------
// Localization Engine
// ----------------------------------------

55
global.lang
56
  .use(i18nBackend)
NGPixel's avatar
NGPixel committed
57 58
  .init({
    load: 'languageOnly',
59
    ns: ['common', 'admin', 'auth', 'errors', 'git'],
NGPixel's avatar
NGPixel committed
60 61
    defaultNS: 'common',
    saveMissing: false,
62 63
    preload: [appconfig.lang],
    lng: appconfig.lang,
NGPixel's avatar
NGPixel committed
64 65 66 67 68 69
    fallbackLng: 'en',
    backend: {
      loadPath: path.join(SERVERPATH, 'locales/{{lng}}/{{ns}}.json')
    }
  })

70 71 72 73
// ----------------------------------------
// Start Cron
// ----------------------------------------

74 75 76
let job
let jobIsBusy = false
let jobUplWatchStarted = false
77

78 79
global.db.onReady.then(() => {
  return global.db.Entry.remove({})
NGPixel's avatar
NGPixel committed
80 81 82 83 84 85 86
}).then(() => {
  job = new Cron({
    cronTime: '0 */5 * * * *',
    onTick: () => {
      // Make sure we don't start two concurrent jobs

      if (jobIsBusy) {
87
        global.winston.warn('Previous job has not completed gracefully or is still running! Skipping for now. (This is not normal, you should investigate)')
NGPixel's avatar
NGPixel committed
88 89
        return
      }
90
      global.winston.info('Running all jobs...')
NGPixel's avatar
NGPixel committed
91
      jobIsBusy = true
92

NGPixel's avatar
NGPixel committed
93
      // Prepare async job collector
94

NGPixel's avatar
NGPixel committed
95 96 97 98
      let jobs = []
      let repoPath = path.resolve(ROOTPATH, appconfig.paths.repo)
      let dataPath = path.resolve(ROOTPATH, appconfig.paths.data)
      let uploadsTempPath = path.join(dataPath, 'temp-upload')
99

NGPixel's avatar
NGPixel committed
100 101 102
      // ----------------------------------------
      // REGULAR JOBS
      // ----------------------------------------
103

NGPixel's avatar
NGPixel committed
104 105 106
      //* ****************************************
      // -> Sync with Git remote
      //* ****************************************
107

108
      jobs.push(global.git.resync().then(() => {
109 110 111 112 113 114 115 116 117 118
        // -> Stream all documents

        let cacheJobs = []
        let jobCbStreamDocsResolve = null
        let jobCbStreamDocs = new Promise((resolve, reject) => {
          jobCbStreamDocsResolve = resolve
        })

        klaw(repoPath).on('data', function (item) {
          if (path.extname(item.path) === '.md' && path.basename(item.path) !== 'README.md') {
NGPixel's avatar
NGPixel committed
119 120
            let entryPath = entryHelper.parsePath(entryHelper.getEntryPathFromFullPath(item.path))
            let cachePath = entryHelper.getCachePath(entryPath)
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

            // -> Purge outdated cache

            cacheJobs.push(
              fs.statAsync(cachePath).then((st) => {
                return moment(st.mtime).isBefore(item.stats.mtime) ? 'expired' : 'active'
              }).catch((err) => {
                return (err.code !== 'EEXIST') ? err : 'new'
              }).then((fileStatus) => {
                // -> Delete expired cache file

                if (fileStatus === 'expired') {
                  return fs.unlinkAsync(cachePath).return(fileStatus)
                }

                return fileStatus
              }).then((fileStatus) => {
                // -> Update cache and search index

                if (fileStatus !== 'active') {
141
                  return global.entries.updateCache(entryPath).then(entry => {
142 143 144 145 146 147
                    process.send({
                      action: 'searchAdd',
                      content: entry
                    })
                    return true
                  })
148 149 150 151 152 153 154 155 156 157 158
                }

                return true
              })
            )
          }
        }).on('end', () => {
          jobCbStreamDocsResolve(Promise.all(cacheJobs))
        })

        return jobCbStreamDocs
NGPixel's avatar
NGPixel committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
      }))

      //* ****************************************
      // -> Clear failed temporary upload files
      //* ****************************************

      jobs.push(
        fs.readdirAsync(uploadsTempPath).then((ls) => {
          let fifteenAgo = moment().subtract(15, 'minutes')

          return Promise.map(ls, (f) => {
            return fs.statAsync(path.join(uploadsTempPath, f)).then((s) => { return { filename: f, stat: s } })
          }).filter((s) => { return s.stat.isFile() }).then((arrFiles) => {
            return Promise.map(arrFiles, (f) => {
              if (moment(f.stat.ctime).isBefore(fifteenAgo, 'minute')) {
                return fs.unlinkAsync(path.join(uploadsTempPath, f.filename))
              } else {
                return true
              }
            })
179 180
          })
        })
NGPixel's avatar
NGPixel committed
181
      )
182

NGPixel's avatar
NGPixel committed
183 184 185
      // ----------------------------------------
      // Run
      // ----------------------------------------
186

NGPixel's avatar
NGPixel committed
187
      Promise.all(jobs).then(() => {
188
        global.winston.info('All jobs completed successfully! Going to sleep for now.')
189

NGPixel's avatar
NGPixel committed
190 191
        if (!jobUplWatchStarted) {
          jobUplWatchStarted = true
192
          global.upl.initialScan().then(() => {
NGPixel's avatar
NGPixel committed
193 194 195 196 197 198
            job.start()
          })
        }

        return true
      }).catch((err) => {
199
        global.winston.error('One or more jobs have failed: ', err)
NGPixel's avatar
NGPixel committed
200 201 202 203 204 205 206 207
      }).finally(() => {
        jobIsBusy = false
      })
    },
    start: false,
    timeZone: 'UTC',
    runOnInit: true
  })
208
})
209

210 211 212 213 214
// ----------------------------------------
// Shutdown gracefully
// ----------------------------------------

process.on('disconnect', () => {
215
  global.winston.warn('Lost connection to main server. Exiting...')
216 217 218
  job.stop()
  process.exit()
})
219 220

process.on('exit', () => {
221 222
  job.stop()
})