<commit_before>/*eslint-env node */
/*eslint no-sync: "off", global-require: "off"*/
'use strict';

var path = require('path')
  , basename = path.basename(__filename, '.js')
  , debug = require('debug')('castor:route:' + basename)
  , bodyParser = require('body-parser')
  , fs = require('fs')
  , getSize = require('get-folder-size')
  , filesize = require('filesize')
  , Docker = require('dockerode')
  , docker = new Docker({ socketPath: '/var/run/docker.sock'})
  , exec = require('child_process').exec
  , jsonfile = require('jsonfile')
  , mkdirp = require('mkdirp')
  , rimraf = require('rimraf')
  , fileExists = require('file-exists')
  , instances = require('../helpers/instances')
  , util = require('utile');



jsonfile.spaces = 2;

module.exports = function (router, core) {

  var config = core.config;

  router.route('/').get(function (req, res, next) {

    if(!req.session.messages)
      req.session.messages = new Array();

    return res.render('template.html');
  
  });

  router.route('/-/v1/instances').get(function (req, res, next) {
    
    instances.getInstances(req, res, next);

  /* 
    // RECUP RESULTAT DE DOCKER STAT POUR AFFICHER LOAD AVERAGE, ETC
    var command_docker_stats = 'docker stats';

    exec(command_docker_stats, function (err, stdout, stderr) {
      if (err) { 

        req.session.messages.push(err);
        config.get('socket').emit('message', req.session.messages);

        return next(err); 

      }

      req.session.messages.push(stdout);
      config.get('socket').emit('message', req.session.messages);

    });
  */

//    config.get('socket').emit('message', req.session.messages);



  });

  router.route('/-/v1/instances/:containerId').put(bodyParser(), function (req, res, next) {
    var container = docker.getContainer(req.params.containerId);

    container.inspect(function (err, data) {
      if (err) { 

        req.session.messages.push(err);
        config.get('socket').emit('message', req.session.messages);

        return next(err); 

      }
      if (req.body.action == 'start' && data.State.Running == false) {
        container.start(function (err, datas, container) {
          if (err) { 

            req.session.messages.push(err);
            config.get('socket').emit('message', req.session.messages);

            return next(err); 

          }

          req.session.messages.push("Instance Started");
          config.get('socket').emit('message', req.session.messages);

          res.status(200).send('Starting done');

        });
      }
      else if (req.body.action == 'stop' && data.State.Running == true) {
        container.stop(function (err, datas, container) {
          if (err) { 

            req.session.messages.push(err);
            config.get('socket').emit('message', req.session.messages);

            return next(err);

          }

          req.session.messages.push("Instance Stopped");
          config.get('socket').emit('message', req.session.messages);

          res.status(200).send('Stoping done');

        });
      }
      else if (req.body.action == 'updateConfig') {
        var splittedName = data.Name.split('/');

        jsonfile.writeFile(
          path.join(__dirname, '../instances/', splittedName[1], '/config/config.json'),
          req.body.newConfig, function (err) {
         
          if (err) { 

            req.session.messages.push(err);
            config.get('socket').emit('message', req.session.messages);

            return next(err); 

          }

          if (data.State.Running == true) {
            container.restart(function (err) {
              if (err) { 

                req.session.messages.push(err);
                config.get('socket').emit('message', req.session.messages);

                return next(err); 

              }

              req.session.messages.push('Update done');
              config.get('socket').emit('message', req.session.messages);

              res.status(200).send('Update done');
            });
          }
          else { 
              
            req.session.messages.push('Update done');
            config.get('socket').emit('message', req.session.messages);

            res.status(200).send('Update done'); 

          }
        });
      }
    });
  });

  router.route('/-/v1/instances/verif').get(bodyParser(), function (req, res, next) {
    if (fileExists(path.join(__dirname, '../manifests/'+req.query.technicalName+'.json')) == false) {

      //req.session.messages.push('Technical name does not exists');
      //config.get('socket').emit('message', req.session.messages);

      res.status(200).send('Technical name does not exists');

    }
    else {

      req.session.messages.push('Technical name '+req.query.technicalName+' already exists');
      config.get('socket').emit('message', req.session.messages);

      res.status(409).send('Technical name '+req.query.technicalName+' already exists');

    }
  });

  router.route('/-/v1/instances/:containerId').get(bodyParser(), function (req, res, next) {
    var container = docker.getContainer(req.params.containerId);

    container.inspect(function (err, data) {
      if (err) { 

        req.session.messages.push(err);
        config.get('socket').emit('message', req.session.messages);

        return next(err); 

      }

      var splittedName = data.Name.split('/');

      if (req.query.action == 'info') {
        var directoryDatas = path.join(__dirname, '../instances/', splittedName[1], '/data/')
          , result = {};

        getSize(directoryDatas, function (err, size) {
          if (err) { return next(err); }

          result['technicalName'] = splittedName[1];
          result['size'] = filesize(size);

          //req.session.messages.push(result);
          //config.get('socket').emit('message', req.session.messages);

          return res.status(200).send(result);
        });
      }
      else if (req.query.action == 'config') {
        jsonfile.readFile(
        path.join(__dirname, '../instances/', splittedName[1], '/config/config.json'),
        function (err, obj) {

          if (err) { 

            req.session.messages.push(err);
            config.get('socket').emit('message', req.session.messages);

            return next(err); 

          }

          //req.session.messages.push(obj);
          //config.get('socket').emit('message', req.session.messages);

          return res.status(200).send(obj);
        });
      }
    });
  });

  router.route('/-/v1/instances/:containerId').delete(function (req, res, next) {
    var container = docker.getContainer(req.params.containerId);

    container.inspect(function (err, data) {
      if (err) { 

        req.session.messages.push(err);
        config.get('socket').emit('message', req.session.messages);

        return next(err); 

      }

      if (data.State.Running == true) {
        container.stop(function (err, datas, cont) {
          if (err) { 

            req.session.messages.push(err);
            config.get('socket').emit('message', req.session.messages);

            return next(err); 

          }

          container.remove(function (err, datas, cont) {
            if (err) { 

              req.session.messages.push(err);
              config.get('socket').emit('message', req.session.messages);

              return next(err); 

            }
          });
        });
      }
      else if (data.State.Running == false) {
        container.remove(function (err, datas, cont) {
          if (err) { 

            req.session.messages.push(err);
            config.get('socket').emit('message', req.session.messages);

            return next(err); 

          }
        });
      }

      var splittedName = data.Name.split('/');
      rimraf(path.join(__dirname, '../instances/', splittedName[1]), function (err) {
        if (err) { 

          req.session.messages.push(err);
          config.get('socket').emit('message', req.session.messages);

          return next(err);

        }

        rimraf(path.join(__dirname, '../manifests/', splittedName[1] + '.json'), function (err) {
          if (err) { 

            req.session.messages.push(err);
            config.get('socket').emit('message', req.session.messages);

            return next(err); 

          }

          req.session.messages.push("Instance Deleted");
          config.get('socket').emit('message', req.session.messages);

          res.status(200).send('Removing done');

        });
      });
    });
  });

  router.route('/-/v1/instances').post(bodyParser(), function (req, res, next) {
    var technicalName = req.body.technicalName
      , longName = req.body.longName
      , image = req.body.app
      , project = req.body.project
      , study = req.body.study;

    if (/^[a-z0-9]+$/.test(project) == false && project != '' && project != null) {

      req.session.messages.push('Enter a valid project name');
      config.get('socket').emit('message', req.session.messages);

      return res.status(400).send('Enter a valid project name');

    }
    if (/^[a-z0-9]+$/.test(study) == false && study != '' && study != null) {
      
      req.session.messages.push('Enter a valid study name');
      config.get('socket').emit('message', req.session.messages);

      return res.status(400).send('Enter a valid study name');

    }
    if (fileExists(path.join(__dirname, '../manifests/'+req.query.technicalName+'.json')) == true) {
      
      req.session.messages.push('Technical name already exists');
      config.get('socket').emit('message', req.session.messages);

      res.status(409).send('Technical name already exists');

    }
    else {
    
      docker.pull(image, function (err, stream) {
        if (err) { 

          req.session.messages.push(err);
          config.get('socket').emit('message', req.session.messages);

          return res.status(400).send(err); 

        }

        docker.modem.followProgress(stream, onFinished);

        function onFinished(err, output) {
          if (err) { 

            req.session.messages.push(err);
            config.get('socket').emit('message', req.session.messages);

            return res.status(400).send(err); 

          }

          mkdirp(path.join(__dirname, '../instances/'+technicalName+'/config/'), function (err) {
            if (err) { 

              req.session.messages.push(err);
              config.get('socket').emit('message', req.session.messages);

              return next(err); 

            }

            mkdirp(path.join(__dirname, '../instances/'+technicalName+'/data/'), function (err) {
              if (err) { 

                req.session.messages.push(err);
                config.get('socket').emit('message', req.session.messages);

                return next(err); 

              }

              fs.appendFile(
              path.join(__dirname, '../instances/'+technicalName+'/config/config.json')
              , '{}', function (err) {

                if (err) { 

                  req.session.messages.push(err);
                  config.get('socket').emit('message', req.session.messages);

                  return next(err); 

                }

                var instancesArray = fs.readdirSync(path.join(__dirname, '../instances/'));

                docker.listContainers({all : true}, function (err, containers) {
                  if (err) { 

                    req.session.messages.push(err);
                    config.get('socket').emit('message', req.session.messages);

                    return next(err); 

                  }

                  var portMax = 0
                    , freePortSplitted = process.env.EZMASTER_FREE_PORT_RANGE.split('-');

                  (function checkPort() {
                    var element = containers.pop();

                    if (element) {
                      var splittedName = element.Names[0].split('/');
                      if (instancesArray.indexOf(splittedName[1]) === -1) {
                        return checkPort();
                      }

                      var container = docker.getContainer(element.Id);

                      container.inspect(function (err, data) {
                        if (err) { 

                          req.session.messages.push(err);
                          config.get('socket').emit('message', req.session.messages);

                          return next(err); 

                        }

                        var keys =  Object.keys(data.HostConfig.PortBindings)
                          , currentPort = data.HostConfig.PortBindings[keys[0]][0].HostPort;

                        if (currentPort >= portMax) { portMax = parseInt(currentPort) + 1; }
                        return checkPort();
                      });
                    }
                    else {
                      if (portMax == 0) { portMax = freePortSplitted[0]; }
                      var cmd = 'docker run -d -p '+portMax+':3000 ' +
                      '-e http_proxy -e https_proxy -e EZMASTER_MONGODB_HOST_PORT '+
                      '--net=ezmaster_default --link ezmaster_db '+
                      '-v '+process.env.EZMASTER_PATH+'/instances/'+
                      technicalName+'/config/config.json:'+'/opt/ezmaster/config/config.json '+
                      '-v '+process.env.EZMASTER_PATH+'/instances/'
                      +technicalName+'/data/:/opt/ezmaster/data/ '+
                      '--name '+technicalName+' '+image;

                      var newlongName = {
                        'longName' : longName
                      };
                      jsonfile.writeFile(
                        path.join(__dirname, '../manifests/'+technicalName+'.json')
                        , newlongName, function (err) {

                        if (err) { 

                          req.session.messages.push(err);
                          config.get('socket').emit('message', req.session.messages);

                          return next(err); 

                        }
                      });

                      exec(cmd, function (err, stdout, stderr) {
                        if (err) { 

                          req.session.messages.push(err);
                          config.get('socket').emit('message', req.session.messages);

                          return next(err); 

                        }

                        req.session.messages.push("Instance Created");
                        config.get('socket').emit('message', req.session.messages);

                        return res.status(200).send('Instance created');
                      });
                    }
                  })();
                });
              });
            });
          });
        }
      });
    }
  });
};<commit_msg>Cleaning route.js from useless socket.emit + eslint debug<commit_after>/*eslint-env node */
/*eslint no-sync: "off", global-require: "off"*/
'use strict';

var path = require('path')
  , basename = path.basename(__filename, '.js')
  , debug = require('debug')('castor:route:' + basename)
  , bodyParser = require('body-parser')
  , fs = require('fs')
  , getSize = require('get-folder-size')
  , filesize = require('filesize')
  , Docker = require('dockerode')
  , docker = new Docker({ socketPath: '/var/run/docker.sock'})
  , exec = require('child_process').exec
  , jsonfile = require('jsonfile')
  , mkdirp = require('mkdirp')
  , rimraf = require('rimraf')
  , fileExists = require('file-exists')
  , instances = require('../helpers/instances')
  , util = require('utile');



jsonfile.spaces = 2;

module.exports = function (router, core) {

  var config = core.config;

  router.route('/').get(function (req, res, next) {

    if (!req.session.messages)
      req.session.messages = new Array();

    return res.render('template.html');

  });

  router.route('/-/v1/instances').get(function (req, res, next) {

    instances.getInstances(req, res, next);

  });

  router.route('/-/v1/instances/:containerId').put(bodyParser(), function (req, res, next) {
    var container = docker.getContainer(req.params.containerId);

    container.inspect(function (err, data) {
      if (err) { return next(err); }
      if (req.body.action == 'start' && data.State.Running == false) {
        container.start(function (err, datas, container) {
          if (err) { return next(err); }
          res.status(200).send('Starting done');
        });
      }
      else if (req.body.action == 'stop' && data.State.Running == true) {
        container.stop(function (err, datas, container) {
          if (err) { return next(err); }
          res.status(200).send('Stoping done');
        });
      }
      else if (req.body.action == 'updateConfig') {
        var splittedName = data.Name.split('/');

        jsonfile.writeFile(
          path.join(__dirname, '../instances/', splittedName[1], '/config/config.json'),
          req.body.newConfig, function (err) {

            if (err) { return next(err); }

            if (data.State.Running == true) {
              container.restart(function (err) {
                if (err) { return next(err); }
                res.status(200).send('Update done');
              });
            }
            else {
              res.status(200).send('Update done');
            }
          });
      }
    });
  });

  router.route('/-/v1/instances/verif').get(bodyParser(), function (req, res, next) {
    if (fileExists(path.join(__dirname, '../manifests/'+req.query.technicalName+'.json')) == false) {
      res.status(200).send('Technical name does not exists');
    }
    else {
      res.status(409).send('Technical name '+req.query.technicalName+' already exists');
    }
  });

  router.route('/-/v1/instances/:containerId').get(bodyParser(), function (req, res, next) {
    var container = docker.getContainer(req.params.containerId);

    container.inspect(function (err, data) {
      if (err) { return next(err); }

      var splittedName = data.Name.split('/');

      if (req.query.action == 'info') {
        var directoryDatas = path.join(__dirname, '../instances/', splittedName[1], '/data/')
          , result = {};

        getSize(directoryDatas, function (err, size) {
          if (err) { return next(err); }

          result['technicalName'] = splittedName[1];
          result['size'] = filesize(size);

          return res.status(200).send(result);
        });
      }
      else if (req.query.action == 'config') {
        jsonfile.readFile(
        path.join(__dirname, '../instances/', splittedName[1], '/config/config.json'),
        function (err, obj) {

          if (err) { return next(err); }

          return res.status(200).send(obj);
        });
      }
    });
  });

  router.route('/-/v1/instances/:containerId').delete(function (req, res, next) {
    var container = docker.getContainer(req.params.containerId);

    container.inspect(function (err, data) {
      if (err) { return next(err); }

      if (data.State.Running == true) {
        container.stop(function (err, datas, cont) {
          if (err) { return next(err); }

          container.remove(function (err, datas, cont) {
            if (err) { return next(err); }
          });
        });
      }
      else if (data.State.Running == false) {
        container.remove(function (err, datas, cont) {
          if (err) { return next(err); }
        });
      }

      var splittedName = data.Name.split('/');
      rimraf(path.join(__dirname, '../instances/', splittedName[1]), function (err) {
        if (err) { return next(err); }

        rimraf(path.join(__dirname, '../manifests/', splittedName[1] + '.json'), function (err) {
          if (err) { return next(err); }

          res.status(200).send('Removing done');
        });
      });
    });
  });

  router.route('/-/v1/instances').post(bodyParser(), function (req, res, next) {
    var technicalName = req.body.technicalName
      , longName = req.body.longName
      , image = req.body.app
      , project = req.body.project
      , study = req.body.study;

    if (/^[a-z0-9]+$/.test(project) == false && project != '' && project != null) {

      return res.status(400).send('Enter a valid project name');

    }
    if (/^[a-z0-9]+$/.test(study) == false && study != '' && study != null) {

      return res.status(400).send('Enter a valid study name');

    }
    if (fileExists(path.join(__dirname, '../manifests/'+req.query.technicalName+'.json')) == true) {

      res.status(409).send('Technical name already exists');

    }
    else {

      docker.pull(image, function (err, stream) {
        if (err) { return res.status(400).send(err); }

        docker.modem.followProgress(stream, onFinished);

        function onFinished(err, output) {
          if (err) { return res.status(400).send(err); }

          mkdirp(path.join(__dirname, '../instances/'+technicalName+'/config/'), function (err) {
            if (err) { return next(err); }

            mkdirp(path.join(__dirname, '../instances/'+technicalName+'/data/'), function (err) {
              if (err) { return next(err); }

              fs.appendFile(
              path.join(__dirname, '../instances/'+technicalName+'/config/config.json')
              , '{}', function (err) {

                if (err) { return next(err); }

                var instancesArray = fs.readdirSync(path.join(__dirname, '../instances/'));

                docker.listContainers({all : true}, function (err, containers) {
                  if (err) { return next(err); }

                  var portMax = 0
                    , freePortSplitted = process.env.EZMASTER_FREE_PORT_RANGE.split('-');

                  (function checkPort() {
                    var element = containers.pop();

                    if (element) {
                      var splittedName = element.Names[0].split('/');
                      if (instancesArray.indexOf(splittedName[1]) === -1) {
                        return checkPort();
                      }

                      var container = docker.getContainer(element.Id);

                      container.inspect(function (err, data) {
                        if (err) { return next(err); }

                        var keys =  Object.keys(data.HostConfig.PortBindings)
                          , currentPort = data.HostConfig.PortBindings[keys[0]][0].HostPort;

                        if (currentPort >= portMax) { portMax = parseInt(currentPort) + 1; }
                        return checkPort();
                      });
                    }
                    else {
                      if (portMax == 0) { portMax = freePortSplitted[0]; }
                      var cmd = 'docker run -d -p '+portMax+':3000 ' +
                      '-e http_proxy -e https_proxy -e EZMASTER_MONGODB_HOST_PORT '+
                      '--net=ezmaster_default --link ezmaster_db '+
                      '-v '+process.env.EZMASTER_PATH+'/instances/'+
                      technicalName+'/config/config.json:'+'/opt/ezmaster/config/config.json '+
                      '-v '+process.env.EZMASTER_PATH+'/instances/'
                      +technicalName+'/data/:/opt/ezmaster/data/ '+
                      '--name '+technicalName+' '+image;

                      var newlongName = {
                        'longName' : longName
                      };
                      jsonfile.writeFile(
                        path.join(__dirname, '../manifests/'+technicalName+'.json')
                        , newlongName, function (err) {
                          if (err) { return next(err); }
                        });

                      exec(cmd, function (err, stdout, stderr) {
                        if (err) { return next(err); }

                        return res.status(200).send('Instance created');
                      });
                    }
                  })();
                });
              });
            });
          });
        }
      });
    }
  });
};
{'fraction_non_alphanumeric': 0.15946137491141035, 'fraction_numerical': 0.006253387251427857, 'mean_word_length': 1.7954783824729053, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '755827', 'n_tokens_mistral': 7133, 'n_tokens_neox': 6567, 'n_words': 1178}