<commit_before>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
// const webpackMergeDll = webpackMerge.strategy({plugins: 'replace'});
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');

/**
 * Webpack Constants
 */
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HOST = process.env.HOST || '0.0.0.0';
const PORT = process.env.PORT || 80;
const HMR = helpers.hasProcessFlag('hot');
const SHOWBANNER = process.env.SHOW_BANNER || false;
const BANNERTEXT = process.env.BANNER_TEXT || '';
const RUN_MODE = process.env.RUN_MODE || 'DEMO';
const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: HMR,
  SHOWBANNER: SHOWBANNER,
  BANNERTEXT: BANNERTEXT,
  RUN_MODE: RUN_MODE
});
console.log(METADATA.baseUrl)

// const DllBundlesPlugin = require('webpack-dll-bundles-plugin').DllBundlesPlugin;

/**
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  return webpackMerge(commonConfig({env: ENV}), {

    /**
     * Developer tool to enhance debugging
     *
     * See: http://webpack.github.io/docs/configuration.html#devtool
     * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
     */
    devtool: 'cheap-module-source-map',

    /**
     * Options affecting the output of the compilation.
     *
     * See: http://webpack.github.io/docs/configuration.html#output
     */
    output: {

      /**
       * The output directory as absolute path (required).
       *
       * See: http://webpack.github.io/docs/configuration.html#output-path
       */
      path: helpers.root('dist'),
      // publicPath: '/unfetter-ui/',

      /**
       * Specifies the name of each output file on disk.
       * IMPORTANT: You must not specify an absolute path here!
       *
       * See: http://webpack.github.io/docs/configuration.html#output-filename
       */
      filename: '[name].bundle.js',

      /**
       * The filename of the SourceMaps for the JavaScript files.
       * They are inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
       */
      sourceMapFilename: '[file].map',

      /** The filename of non-entry chunks as relative path
       * inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
       */
      chunkFilename: '[id].chunk.js',

      library: 'ac_[name]',
      libraryTarget: 'var',
    },

    module: {

      rules: [
       {
         test: /\.ts$/,
         use: [
           {
             loader: 'tslint-loader',
             options: {
               configFile: 'tslint.json'
             }
           }
         ],
         exclude: [/\.(spec|e2e)\.ts$/]
       },

        /*
         * css loader support for *.css files (styles directory only)
         * Loads external css styles into the DOM, supports HMR
         *
         */
        {
          test: /\.css$/,
          use: ['style-loader', 'css-loader'],
          include: [helpers.root('src', 'styles')]
        },

        /*
         * sass loader support for *.scss files (styles directory only)
         * Loads external sass styles into the DOM, supports HMR
         *
         */
        {
          test: /\.scss$/,
          use: ['style-loader', 'css-loader', 'sass-loader'],
          include: [helpers.root('src', 'styles')]
        },

      ]

    },

    plugins: [

      /**
       * Plugin: DefinePlugin
       * Description: Define free variables.
       * Useful for having development builds with debug logging or adding global constants.
       *
       * Environment helpers
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       */
      // NOTE: when adding more properties, make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'SHOWBANNER': METADATA.SHOWBANNER,
        'RUN_MODE': JSON.stringify(METADATA.RUN_MODE),
        'BANNERTEXT': JSON.stringify(METADATA.BANNERTEXT),
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'HMR': METADATA.HMR,
        }
      }),

      // new DllBundlesPlugin({
      //   bundles: {
      //     polyfills: [
      //       'core-js',
      //       {
      //         name: 'zone.js',
      //         path: 'zone.js/dist/zone.js'
      //       },
      //       {
      //         name: 'zone.js',
      //         path: 'zone.js/dist/long-stack-trace-zone.js'
      //       },
      //     ],
      //     vendor: [
      //       '@angular/platform-browser',
      //       '@angular/platform-browser-dynamic',
      //       '@angular/core',
      //       '@angular/common',
      //       '@angular/forms',
      //       '@angular/http',
      //       '@angular/router',
      //       '@angularclass/hmr',
      //       'rxjs',
      //     ]
      //   },
      //   dllDir: helpers.root('dll'),
      //   webpackConfig: webpackMergeDll(commonConfig({env: ENV}), {
      //     devtool: 'cheap-module-source-map',
      //     plugins: []
      //   })
      // }),

      /**
       * Plugin: AddAssetHtmlPlugin
       * Description: Adds the given JS or CSS file to the files
       * Webpack knows about, and put it into the list of assets
       * html-webpack-plugin injects into the generated html.
       *
       * See: https://github.com/SimenB/add-asset-html-webpack-plugin
       */
      // new AddAssetHtmlPlugin([
      //   { filepath: helpers.root(`dll/${DllBundlesPlugin.resolveFile('polyfills')}`) },
      //   { filepath: helpers.root(`dll/${DllBundlesPlugin.resolveFile('vendor')}`) }
      // ]),

      /**
       * Plugin: NamedModulesPlugin (experimental)
       * Description: Uses file names as module name.
       *
       * See: https://github.com/webpack/webpack/commit/a04ffb928365b19feb75087c63f13cadfc08e1eb
       */
      // new NamedModulesPlugin(),

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({
        debug: true,
        options: {

        }
      }),

    ],

    /**
     * Webpack Development Server configuration
     * Description: The webpack-dev-server is a little node.js Express server.
     * The server emits information about the compilation state to the client,
     * which reacts to those events.
     *
     * See: https://webpack.github.io/docs/webpack-dev-server.html
     */
    devServer: {
      port: METADATA.port,
      host: METADATA.host,
      historyApiFallback: true,
      https: true,
      watchOptions: {
        aggregateTimeout: 300,
        poll: 1000,
        ignored: /node_modules/
      }
      // disableHostCheck: true
    },

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  });
}
<commit_msg>fix invalid host header accessing ui from container<commit_after>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
// const webpackMergeDll = webpackMerge.strategy({plugins: 'replace'});
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');

/**
 * Webpack Constants
 */
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HOST = process.env.HOST || '0.0.0.0';
const PORT = process.env.PORT || 80;
const HMR = helpers.hasProcessFlag('hot');
const SHOWBANNER = process.env.SHOW_BANNER || false;
const BANNERTEXT = process.env.BANNER_TEXT || '';
const RUN_MODE = process.env.RUN_MODE || 'DEMO';
const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: HMR,
  SHOWBANNER: SHOWBANNER,
  BANNERTEXT: BANNERTEXT,
  RUN_MODE: RUN_MODE
});
console.log(METADATA.baseUrl)

// const DllBundlesPlugin = require('webpack-dll-bundles-plugin').DllBundlesPlugin;

/**
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  return webpackMerge(commonConfig({env: ENV}), {

    /**
     * Developer tool to enhance debugging
     *
     * See: http://webpack.github.io/docs/configuration.html#devtool
     * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
     */
    devtool: 'cheap-module-source-map',

    /**
     * Options affecting the output of the compilation.
     *
     * See: http://webpack.github.io/docs/configuration.html#output
     */
    output: {

      /**
       * The output directory as absolute path (required).
       *
       * See: http://webpack.github.io/docs/configuration.html#output-path
       */
      path: helpers.root('dist'),
      // publicPath: '/unfetter-ui/',

      /**
       * Specifies the name of each output file on disk.
       * IMPORTANT: You must not specify an absolute path here!
       *
       * See: http://webpack.github.io/docs/configuration.html#output-filename
       */
      filename: '[name].bundle.js',

      /**
       * The filename of the SourceMaps for the JavaScript files.
       * They are inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
       */
      sourceMapFilename: '[file].map',

      /** The filename of non-entry chunks as relative path
       * inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
       */
      chunkFilename: '[id].chunk.js',

      library: 'ac_[name]',
      libraryTarget: 'var',
    },

    module: {

      rules: [
       {
         test: /\.ts$/,
         use: [
           {
             loader: 'tslint-loader',
             options: {
               configFile: 'tslint.json'
             }
           }
         ],
         exclude: [/\.(spec|e2e)\.ts$/]
       },

        /*
         * css loader support for *.css files (styles directory only)
         * Loads external css styles into the DOM, supports HMR
         *
         */
        {
          test: /\.css$/,
          use: ['style-loader', 'css-loader'],
          include: [helpers.root('src', 'styles')]
        },

        /*
         * sass loader support for *.scss files (styles directory only)
         * Loads external sass styles into the DOM, supports HMR
         *
         */
        {
          test: /\.scss$/,
          use: ['style-loader', 'css-loader', 'sass-loader'],
          include: [helpers.root('src', 'styles')]
        },

      ]

    },

    plugins: [

      /**
       * Plugin: DefinePlugin
       * Description: Define free variables.
       * Useful for having development builds with debug logging or adding global constants.
       *
       * Environment helpers
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       */
      // NOTE: when adding more properties, make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'SHOWBANNER': METADATA.SHOWBANNER,
        'RUN_MODE': JSON.stringify(METADATA.RUN_MODE),
        'BANNERTEXT': JSON.stringify(METADATA.BANNERTEXT),
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'HMR': METADATA.HMR,
        }
      }),

      // new DllBundlesPlugin({
      //   bundles: {
      //     polyfills: [
      //       'core-js',
      //       {
      //         name: 'zone.js',
      //         path: 'zone.js/dist/zone.js'
      //       },
      //       {
      //         name: 'zone.js',
      //         path: 'zone.js/dist/long-stack-trace-zone.js'
      //       },
      //     ],
      //     vendor: [
      //       '@angular/platform-browser',
      //       '@angular/platform-browser-dynamic',
      //       '@angular/core',
      //       '@angular/common',
      //       '@angular/forms',
      //       '@angular/http',
      //       '@angular/router',
      //       '@angularclass/hmr',
      //       'rxjs',
      //     ]
      //   },
      //   dllDir: helpers.root('dll'),
      //   webpackConfig: webpackMergeDll(commonConfig({env: ENV}), {
      //     devtool: 'cheap-module-source-map',
      //     plugins: []
      //   })
      // }),

      /**
       * Plugin: AddAssetHtmlPlugin
       * Description: Adds the given JS or CSS file to the files
       * Webpack knows about, and put it into the list of assets
       * html-webpack-plugin injects into the generated html.
       *
       * See: https://github.com/SimenB/add-asset-html-webpack-plugin
       */
      // new AddAssetHtmlPlugin([
      //   { filepath: helpers.root(`dll/${DllBundlesPlugin.resolveFile('polyfills')}`) },
      //   { filepath: helpers.root(`dll/${DllBundlesPlugin.resolveFile('vendor')}`) }
      // ]),

      /**
       * Plugin: NamedModulesPlugin (experimental)
       * Description: Uses file names as module name.
       *
       * See: https://github.com/webpack/webpack/commit/a04ffb928365b19feb75087c63f13cadfc08e1eb
       */
      // new NamedModulesPlugin(),

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({
        debug: true,
        options: {

        }
      }),

    ],

    /**
     * Webpack Development Server configuration
     * Description: The webpack-dev-server is a little node.js Express server.
     * The server emits information about the compilation state to the client,
     * which reacts to those events.
     *
     * See: https://webpack.github.io/docs/webpack-dev-server.html
     */
    devServer: {
      port: METADATA.port,
      host: METADATA.host,
      historyApiFallback: true,
      https: true,
      watchOptions: {
        aggregateTimeout: 300,
        poll: 1000,
        ignored: /node_modules/
      },
      disableHostCheck: true
    },

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  });
}
<|endoftext|>


<commit_before>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const DefinePlugin = require('webpack/lib/DefinePlugin');
const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');

/**
 * Webpack Constants
 */
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 3000;
const HMR = helpers.hasProcessFlag('hot');
// if env is 'inmemory', the inmemory debug resource is used
const FABRIC8_WIT_API_URL = process.env.FABRIC8_WIT_API_URL || 'http://api.prod-preview.openshift.io/api/';
const FABRIC8_RECOMMENDER_API_URL = process.env.FABRIC8_RECOMMENDER_API_URL || 'http://api-bayesian.dev.rdu2c.fabric8.io/api/v1/';
const FABRIC8_FORGE_URL = process.env.FABRIC8_FORGE_URL;
const PUBLIC_PATH = process.env.PUBLIC_PATH || '/';
const BUILD_NUMBER = process.env.BUILD_NUMBER;
const BUILD_TIMESTAMP = process.env.BUILD_TIMESTAMP;

const METADATA = webpackMerge(commonConfig({ env: ENV }).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: HMR,
  FABRIC8_WIT_API_URL: FABRIC8_WIT_API_URL,
  FABRIC8_RECOMMENDER_API_URL: FABRIC8_RECOMMENDER_API_URL,
  FABRIC8_FORGE_URL: FABRIC8_FORGE_URL,
  PUBLIC_PATH: PUBLIC_PATH,
  BUILD_NUMBER: BUILD_NUMBER,
  BUILD_TIMESTAMP: BUILD_TIMESTAMP
});

/**
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  return webpackMerge(commonConfig({ env: ENV }), {

    /**
     * Developer tool to enhance debugging
     *
     * See: http://webpack.github.io/docs/configuration.html#devtool
     * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
     */
    devtool: 'inline-source-map',

    watchOptions: {
      aggregateTimeout: 3000
    },

    // While this does provide debugging of the imported npm modules it also lists a whole stack of them that it can't find.
    //   This is a distraction while trying to debug actual issues. If you are trying to debug an imported issue then turn
    //   it on, but please don't commit it.
    // module: {
    //   'preLoaders': [
    //     { test: /\.js$/, loader: 'source-map' }
    //   ]
    // },
    /**
     * Options affecting the output of the compilation.
     *
     * See: http://webpack.github.io/docs/configuration.html#output
     */
    output: {

      /**
       * The output directory as absolute path (required).
       *
       * See: http://webpack.github.io/docs/configuration.html#output-path
       */
      path: helpers.root('dist'),

      publicPath: METADATA.PUBLIC_PATH,

      /**
       * Specifies the name of each output file on disk.
       * IMPORTANT: You must not specify an absolute path here!
       *
       * See: http://webpack.github.io/docs/configuration.html#output-filename
       */
      filename: '[name].bundle.js',

      /**
       * The filename of the SourceMaps for the JavaScript files.
       * They are inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
       */
      sourceMapFilename: '[name].map',

      /** The filename of non-entry chunks as relative path
       * inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
       */
      chunkFilename: '[id].chunk.js',

      library: 'ac_[name]',

      libraryTarget: 'var'
    },

    module: {
      rules: [
        {
          test: /\.js$/,
          include: [
            helpers.nodeModulePath("fabric8-planner"),
            helpers.nodeModulePath("ngx-fabric8-wit"),
            helpers.nodeModulePath("ngx-fabric8-login-client"),
            helpers.nodeModulePath("ngx-widgets")
          ],
          use: ["source-map-loader"],
          enforce: "pre"
        }
      ]
    },

    plugins: [
      /**
       * Plugin: DefinePlugin
       * Description: Define free variables.
       * Useful for having development builds with debug logging or adding global constants.
       *
       * Environment helpers
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       */
      // NOTE: when adding more properties, make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'HMR': METADATA.HMR,
          'API_URL': JSON.stringify(METADATA.FABRIC8_WIT_API_URL),
          'FABRIC8_WIT_API_URL': JSON.stringify(METADATA.FABRIC8_WIT_API_URL),
          'FABRIC8_RECOMMENDER_API_URL': JSON.stringify(METADATA.FABRIC8_RECOMMENDER_API_URL),
          'FABRIC8_FORGE_URL': JSON.stringify(METADATA.FABRIC8_FORGE_URL),
          'PUBLIC_PATH': JSON.stringify(METADATA.PUBLIC_PATH),
          'BUILD_NUMBER': JSON.stringify(BUILD_NUMBER),
          'BUILD_TIMESTAMP': JSON.stringify(BUILD_TIMESTAMP)
        }
      }),

      /**
       * Plugin: NamedModulesPlugin (experimental)
       * Description: Uses file names as module name.
       *
       * See: https://github.com/webpack/webpack/commit/a04ffb928365b19feb75087c63f13cadfc08e1eb
       */
      new NamedModulesPlugin(),

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({
        debug: true,
        options: {

          /**
           * Static analysis linter for TypeScript advanced options configuration
           * Description: An extensible linter for the TypeScript language.
           *
           * See: https://github.com/wbuchwalter/tslint-loader
           */
          tslint: {
            emitErrors: false,
            failOnHint: false,
            resourcePath: 'src'
          }

        }
      })

    ],

    /**
     * Webpack Development Server configuration
     * Description: The webpack-dev-server is a little node.js Express server.
     * The server emits information about the compilation state to the client,
     * which reacts to those events.
     *
     * See: https://webpack.github.io/docs/webpack-dev-server.html
     */
    devServer: {
      port: METADATA.port,
      host: METADATA.host,
      historyApiFallback: true,
      watchOptions: {
        aggregateTimeout: 300,
        poll: 1000
      }
      // outputPath: helpers.root('dist/')
    },

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  });
};
<commit_msg>fix(build): comment out the nodeModulePath to get the srouce maps<commit_after>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const DefinePlugin = require('webpack/lib/DefinePlugin');
const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');

/**
 * Webpack Constants
 */
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 3000;
const HMR = helpers.hasProcessFlag('hot');
// if env is 'inmemory', the inmemory debug resource is used
const FABRIC8_WIT_API_URL = process.env.FABRIC8_WIT_API_URL || 'http://api.prod-preview.openshift.io/api/';
const FABRIC8_RECOMMENDER_API_URL = process.env.FABRIC8_RECOMMENDER_API_URL || 'http://api-bayesian.dev.rdu2c.fabric8.io/api/v1/';
const FABRIC8_FORGE_URL = process.env.FABRIC8_FORGE_URL;
const PUBLIC_PATH = process.env.PUBLIC_PATH || '/';
const BUILD_NUMBER = process.env.BUILD_NUMBER;
const BUILD_TIMESTAMP = process.env.BUILD_TIMESTAMP;

const METADATA = webpackMerge(commonConfig({ env: ENV }).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: HMR,
  FABRIC8_WIT_API_URL: FABRIC8_WIT_API_URL,
  FABRIC8_RECOMMENDER_API_URL: FABRIC8_RECOMMENDER_API_URL,
  FABRIC8_FORGE_URL: FABRIC8_FORGE_URL,
  PUBLIC_PATH: PUBLIC_PATH,
  BUILD_NUMBER: BUILD_NUMBER,
  BUILD_TIMESTAMP: BUILD_TIMESTAMP
});

/**
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  return webpackMerge(commonConfig({ env: ENV }), {

    /**
     * Developer tool to enhance debugging
     *
     * See: http://webpack.github.io/docs/configuration.html#devtool
     * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
     */
    devtool: 'inline-source-map',

    watchOptions: {
      aggregateTimeout: 3000
    },

    // While this does provide debugging of the imported npm modules it also lists a whole stack of them that it can't find.
    //   This is a distraction while trying to debug actual issues. If you are trying to debug an imported issue then turn
    //   it on, but please don't commit it.
    // module: {
    //   'preLoaders': [
    //     { test: /\.js$/, loader: 'source-map' }
    //   ]
    // },
    /**
     * Options affecting the output of the compilation.
     *
     * See: http://webpack.github.io/docs/configuration.html#output
     */
    output: {

      /**
       * The output directory as absolute path (required).
       *
       * See: http://webpack.github.io/docs/configuration.html#output-path
       */
      path: helpers.root('dist'),

      publicPath: METADATA.PUBLIC_PATH,

      /**
       * Specifies the name of each output file on disk.
       * IMPORTANT: You must not specify an absolute path here!
       *
       * See: http://webpack.github.io/docs/configuration.html#output-filename
       */
      filename: '[name].bundle.js',

      /**
       * The filename of the SourceMaps for the JavaScript files.
       * They are inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
       */
      sourceMapFilename: '[name].map',

      /** The filename of non-entry chunks as relative path
       * inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
       */
      chunkFilename: '[id].chunk.js',

      library: 'ac_[name]',

      libraryTarget: 'var'
    },

    module: {
      rules: [
        {
          test: /\.js$/,
          // include: [
          //   helpers.nodeModulePath("fabric8-planner"),
          //   helpers.nodeModulePath("ngx-fabric8-wit"),
          //   helpers.nodeModulePath("ngx-fabric8-login-client"),
          //   helpers.nodeModulePath("ngx-widgets")
          // ],
          use: ["source-map-loader"],
          enforce: "pre"
        }
      ]
    },

    plugins: [
      /**
       * Plugin: DefinePlugin
       * Description: Define free variables.
       * Useful for having development builds with debug logging or adding global constants.
       *
       * Environment helpers
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       */
      // NOTE: when adding more properties, make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'HMR': METADATA.HMR,
          'API_URL': JSON.stringify(METADATA.FABRIC8_WIT_API_URL),
          'FABRIC8_WIT_API_URL': JSON.stringify(METADATA.FABRIC8_WIT_API_URL),
          'FABRIC8_RECOMMENDER_API_URL': JSON.stringify(METADATA.FABRIC8_RECOMMENDER_API_URL),
          'FABRIC8_FORGE_URL': JSON.stringify(METADATA.FABRIC8_FORGE_URL),
          'PUBLIC_PATH': JSON.stringify(METADATA.PUBLIC_PATH),
          'BUILD_NUMBER': JSON.stringify(BUILD_NUMBER),
          'BUILD_TIMESTAMP': JSON.stringify(BUILD_TIMESTAMP)
        }
      }),

      /**
       * Plugin: NamedModulesPlugin (experimental)
       * Description: Uses file names as module name.
       *
       * See: https://github.com/webpack/webpack/commit/a04ffb928365b19feb75087c63f13cadfc08e1eb
       */
      new NamedModulesPlugin(),

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({
        debug: true,
        options: {

          /**
           * Static analysis linter for TypeScript advanced options configuration
           * Description: An extensible linter for the TypeScript language.
           *
           * See: https://github.com/wbuchwalter/tslint-loader
           */
          tslint: {
            emitErrors: false,
            failOnHint: false,
            resourcePath: 'src'
          }

        }
      })

    ],

    /**
     * Webpack Development Server configuration
     * Description: The webpack-dev-server is a little node.js Express server.
     * The server emits information about the compilation state to the client,
     * which reacts to those events.
     *
     * See: https://webpack.github.io/docs/webpack-dev-server.html
     */
    devServer: {
      port: METADATA.port,
      host: METADATA.host,
      historyApiFallback: true,
      watchOptions: {
        aggregateTimeout: 300,
        poll: 1000
      }
      // outputPath: helpers.root('dist/')
    },

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  });
};
<|endoftext|>


<commit_before>'use strict'

// //////////////////////////////////////////////////////////////////////////
// actionhero framework in node.js
// http://www.actionherojs.com
// https://github.com/actionhero/actionhero

const path = require('path')
const async = require('async')
const glob = require('glob')

// HELPERS ///

const fatalError = function (api, errors, type) {
  if (errors && !(errors instanceof Array)) { errors = [errors] }
  if (errors) {
    if (api.log) {
      api.log(`Error with initializer step: ${type}`, 'emerg')
      errors.forEach((error) => { api.log(error.stack, 'emerg') })
    } else {
      console.error('Error with initializer step: ' + type)
      errors.forEach((error) => { console.error(error.stack) })
    }
    api.commands.stop.call(api, () => {
      process.exit(1)
    })
  }
}

const sortNumber = function (a, b) {
  return a - b
}

let startCount = 0

const flattenOrderedInitialzer = function (collection) {
  let output = []
  let keys = []
  for (let key in collection) {
    keys.push(parseInt(key))
  }
  keys.sort(sortNumber)
  keys.forEach((key) => {
    collection[key].forEach((d) => {
      output.push(d)
    })
  })

  return output
}

// ACTIONHERO //

const actionhero = function () {
  this.initializers = {}
  this.api = {
    running: false,
    initialized: false,
    shuttingDown: false
  }
}

actionhero.prototype.initialize = function (params, callback) {
  this.api.commands = {
    initialize: (params, callback) => { this.initialize(params, callback) },
    start: (params, callback) => { this.start(params, callback) },
    stop: (callback) => { this.stop(callback) },
    restart: (callback) => { this.restart(callback) }
  }

  this.api.projectRoot = process.cwd()

  if (process.env.project_root) {
    this.api.projectRoot = process.env.project_root
  } else if (process.env.projectRoot) {
    this.api.projectRoot = process.env.projectRoot
  } else if (process.env.PROJECT_ROOT) {
    this.api.projectRoot = process.env.PROJECT_ROOT
  }

  if (!callback && typeof params === 'function') {
    callback = params; params = {}
  }
  if (params === null) { params = {} }
  this.startingParams = params
  this.api._startingParams = this.startingParams

  this.api.initializerDefaults = {
    load: 1000,
    start: 1000,
    stop: 1000
  }

  let loadInitializerRankings = {}
  let startInitializerRankings = {}
  let stopInitializerRankings = {}

  this.configInitializers = []
  this.loadInitializers = []
  this.startInitializers = []
  this.stopInitializers = [];

  // we need to load the config first
  [
    path.resolve(__dirname, 'initializers', 'utils.js'),
    path.resolve(__dirname, 'initializers', 'config.js')
  ].forEach((file) => {
    let filename = file.replace(/^.*[\\/]/, '')
    let initializer = filename.split('.')[0]
    delete require.cache[require.resolve(file)]
    this.initializers[initializer] = require(file)
    this.configInitializers.push((next) => {
      this.initializers[initializer].initialize(this.api, next)
    })
  })

  this.configInitializers.push(() => {
    let customInitializers = []
    let duplicatedInitializers = []
    this.api.config.general.paths.initializer.forEach((startPath) => {
      customInitializers = customInitializers.concat(glob.sync(path.join(startPath, '**', '*.js'), {follow: true}))
    })
    // load all other initializers
    this.api.utils.arrayUniqueify(
      glob.sync(path.join(__dirname, 'initializers', '**', '*.js'), {follow: true})
      .sort()
      .concat(
        customInitializers
        .sort()
      )
    ).forEach((f) => {
      let file = path.normalize(f)
      let initializer = path.basename(f).split('.')[0]
      let fileParts = file.split('.')
      let ext = fileParts[(fileParts.length - 1)]
      if (ext === 'js') {
        // check if initializer already exists (exclude utils and config)
        if (this.initializers[initializer] &&
           file !== path.resolve(__dirname, 'initializers', 'utils.js') &&
           file !== path.resolve(__dirname, 'initializers', 'config.js')) {
          duplicatedInitializers.push(file)
        } else {
          delete require.cache[require.resolve(file)]
          this.initializers[initializer] = require(file)
        }

        const loadFunction = (next) => {
          this.api.watchFileAndAct(file, () => {
            this.api.log(`*** Rebooting due to initializer change (${file}) ***`, 'info')
            this.api.commands.restart()
          })

          if (typeof this.initializers[initializer].initialize === 'function') {
            if (typeof this.api.log === 'function') { this.api.log(`Loading initializer: ${initializer}`, 'debug', file) }
            try {
              this.initializers[initializer].initialize(this.api, (error) => {
                try { this.api.log(`Loaded initializer: ${initializer}`, 'debug', file) } catch (e) { }
                next(error)
              })
            } catch (e) {
              this.api.log(`Exception occured in initializer: ${initializer}  during load`, 'debug', e)
              next(e)
            }
          } else {
            next()
          }
        }

        const startFunction = (next) => {
          if (typeof this.initializers[initializer].start === 'function') {
            if (typeof this.api.log === 'function') { this.api.log(`Starting initializer: ${initializer}`, 'debug', file) }
            try {
              this.initializers[initializer].start(this.api, (error) => {
                this.api.log(`Started initializer: ${initializer}`, 'debug', file)
                next(error)
              })
            } catch (e) {
              this.api.log(`Exception occured in initializer: ${initializer} during start`, 'debug', e)
              next(e)
            }
          } else {
            next()
          }
        }

        const stopFunction = (next) => {
          if (typeof this.initializers[initializer].stop === 'function') {
            if (typeof this.api.log === 'function') { this.api.log(`Stopping initializer: ${initializer}`, 'debug', file) }
            try {
              this.initializers[initializer].stop(this.api, (error) => {
                this.api.log(`Stopped initializer: ${initializer}`, 'debug', file)
                next(error)
              })
            } catch (e) {
              this.api.log(`Exception occured in initializer: ${initializer} during stop`, 'debug', e)
              next(e)
            }
          } else {
            next()
          }
        }

        if (this.initializers[initializer].loadPriority === undefined) {
          this.initializers[initializer].loadPriority = this.api.initializerDefaults.load
        }
        if (this.initializers[initializer].startPriority === undefined) {
          this.initializers[initializer].startPriority = this.api.initializerDefaults.start
        }
        if (this.initializers[initializer].stopPriority === undefined) {
          this.initializers[initializer].stopPriority = this.api.initializerDefaults.stop
        }

        if (loadInitializerRankings[this.initializers[initializer].loadPriority] === undefined) {
          loadInitializerRankings[this.initializers[initializer].loadPriority] = []
        }
        if (startInitializerRankings[this.initializers[initializer].startPriority] === undefined) {
          startInitializerRankings[this.initializers[initializer].startPriority] = []
        }
        if (stopInitializerRankings[this.initializers[initializer].stopPriority] === undefined) {
          stopInitializerRankings[this.initializers[initializer].stopPriority] = []
        }

        if (this.initializers[initializer].loadPriority > 0) {
          loadInitializerRankings[this.initializers[initializer].loadPriority].push(loadFunction)
        }

        if (this.initializers[initializer].startPriority > 0) {
          startInitializerRankings[this.initializers[initializer].startPriority].push(startFunction)
        }

        if (this.initializers[initializer].stopPriority > 0) {
          stopInitializerRankings[this.initializers[initializer].stopPriority].push(stopFunction)
        }
      }
    })

    // flatten all the ordered initializer methods
    this.loadInitializers = flattenOrderedInitialzer(loadInitializerRankings)
    this.startInitializers = flattenOrderedInitialzer(startInitializerRankings)
    this.stopInitializers = flattenOrderedInitialzer(stopInitializerRankings)

    this.loadInitializers.push(() => {
      process.nextTick(() => {
        this.api.initialized = true

        if (duplicatedInitializers.length > 0) {
          duplicatedInitializers.forEach(initializer => this.api.log(`Initializer ${initializer} already exists!`, 'error'))
          this.api.commands.stop.call(this.api, () => {
            process.exit(1)
          })
        }
        callback(null, this.api)
      })
    })

    async.series(this.loadInitializers, (errors) => { fatalError(this.api, errors, 'initialize') })
  })

  async.series(this.configInitializers, (errors) => { fatalError(this.api, errors, 'config') })
}

actionhero.prototype.start = function (params, callback) {
  if (!callback && typeof params === 'function') {
    callback = params; params = {}
  }

  const _start = () => {
    this.api.running = true

    this.api.log('*** Starting ActionHero ***', 'notice')

    this.startInitializers.push(() => {
      this.api.bootTime = new Date().getTime()
      if (startCount === 0) {
        this.api.log('*** ActionHero Started ***', 'alert')
      } else {
        this.api.log('*** ActionHero Restarted ***', 'alert')
      }

      startCount++
      callback(null, this.api)
    })

    async.series(this.startInitializers, (errors) => { fatalError(this.api, errors, 'start') })
  }

  if (this.api.initialized === true) {
    _start()
  } else {
    this.initialize(params, () => {
      _start()
    })
  }
}

actionhero.prototype.stop = function (callback) {
  if (this.api.running === true) {
    this.api.shuttingDown = true
    this.api.running = false
    this.api.initialized = false

    this.api.log('Shutting down open servers and stopping task processing...', 'notice')

    this.stopInitializers.push(() => {
      this.api.unWatchAllFiles()
      this.api.pids.clearPidFile()
      this.api.log('*** ActionHero Stopped ***', 'alert')
      this.api.log('***', 'debug')
      delete this.api.shuttingDown
      // reset initializers to prevent duplicate check on restart
      this.initializers = {}
      process.nextTick(() => {
        if (typeof callback === 'function') { callback(null, this.api) }
      })
    })

    async.series(this.stopInitializers, (errors) => { fatalError(this.api, errors, 'stop') })
  } else if (this.api.shuttingDown === true) {
    // double sigterm; ignore it
  } else {
    if (this.api.log) { this.api.log('Cannot shut down actionhero, not running', 'error') }
    if (typeof callback === 'function') { callback(null, this.api) }
  }
}

actionhero.prototype.restart = function (callback) {
  if (this.api.running === true) {
    this.stop((error) => {
      if (error) { this.api.log(error, 'error') }
      this.start(this.startingParams, (error) => {
        if (error) { this.api.log(error, 'error') }
        if (typeof callback === 'function') { callback(null, this.api) }
      })
    })
  } else {
    this.start(this.startingParams, (error) => {
      if (error) { this.api.log(error, 'error') }
      if (typeof callback === 'function') { callback(null, this.api) }
    })
  }
}

module.exports = actionhero
<commit_msg>warning log on init errors<commit_after>'use strict'

// //////////////////////////////////////////////////////////////////////////
// actionhero framework in node.js
// http://www.actionherojs.com
// https://github.com/actionhero/actionhero

const path = require('path')
const async = require('async')
const glob = require('glob')

// HELPERS ///

const fatalError = function (api, errors, type) {
  if (errors && !(errors instanceof Array)) { errors = [errors] }
  if (errors) {
    if (api.log) {
      api.log(`Error with initializer step: ${type}`, 'emerg')
      errors.forEach((error) => { api.log(error.stack, 'emerg') })
    } else {
      console.error('Error with initializer step: ' + type)
      errors.forEach((error) => { console.error(error.stack) })
    }
    api.commands.stop.call(api, () => {
      process.exit(1)
    })
  }
}

const sortNumber = function (a, b) {
  return a - b
}

let startCount = 0

const flattenOrderedInitialzer = function (collection) {
  let output = []
  let keys = []
  for (let key in collection) {
    keys.push(parseInt(key))
  }
  keys.sort(sortNumber)
  keys.forEach((key) => {
    collection[key].forEach((d) => {
      output.push(d)
    })
  })

  return output
}

// ACTIONHERO //

const actionhero = function () {
  this.initializers = {}
  this.api = {
    running: false,
    initialized: false,
    shuttingDown: false
  }
}

actionhero.prototype.initialize = function (params, callback) {
  this.api.commands = {
    initialize: (params, callback) => { this.initialize(params, callback) },
    start: (params, callback) => { this.start(params, callback) },
    stop: (callback) => { this.stop(callback) },
    restart: (callback) => { this.restart(callback) }
  }

  this.api.projectRoot = process.cwd()

  if (process.env.project_root) {
    this.api.projectRoot = process.env.project_root
  } else if (process.env.projectRoot) {
    this.api.projectRoot = process.env.projectRoot
  } else if (process.env.PROJECT_ROOT) {
    this.api.projectRoot = process.env.PROJECT_ROOT
  }

  if (!callback && typeof params === 'function') {
    callback = params; params = {}
  }
  if (params === null) { params = {} }
  this.startingParams = params
  this.api._startingParams = this.startingParams

  this.api.initializerDefaults = {
    load: 1000,
    start: 1000,
    stop: 1000
  }

  let loadInitializerRankings = {}
  let startInitializerRankings = {}
  let stopInitializerRankings = {}

  this.configInitializers = []
  this.loadInitializers = []
  this.startInitializers = []
  this.stopInitializers = [];

  // we need to load the config first
  [
    path.resolve(__dirname, 'initializers', 'utils.js'),
    path.resolve(__dirname, 'initializers', 'config.js')
  ].forEach((file) => {
    let filename = file.replace(/^.*[\\/]/, '')
    let initializer = filename.split('.')[0]
    delete require.cache[require.resolve(file)]
    this.initializers[initializer] = require(file)
    this.configInitializers.push((next) => {
      this.initializers[initializer].initialize(this.api, next)
    })
  })

  this.configInitializers.push(() => {
    let customInitializers = []
    let duplicatedInitializers = []
    this.api.config.general.paths.initializer.forEach((startPath) => {
      customInitializers = customInitializers.concat(glob.sync(path.join(startPath, '**', '*.js'), {follow: true}))
    })
    // load all other initializers
    this.api.utils.arrayUniqueify(
      glob.sync(path.join(__dirname, 'initializers', '**', '*.js'), {follow: true})
      .sort()
      .concat(
        customInitializers
        .sort()
      )
    ).forEach((f) => {
      let file = path.normalize(f)
      let initializer = path.basename(f).split('.')[0]
      let fileParts = file.split('.')
      let ext = fileParts[(fileParts.length - 1)]
      if (ext === 'js') {
        // check if initializer already exists (exclude utils and config)
        if (this.initializers[initializer] &&
           file !== path.resolve(__dirname, 'initializers', 'utils.js') &&
           file !== path.resolve(__dirname, 'initializers', 'config.js')) {
          duplicatedInitializers.push(file)
        } else {
          delete require.cache[require.resolve(file)]
          this.initializers[initializer] = require(file)
        }

        const loadFunction = (next) => {
          this.api.watchFileAndAct(file, () => {
            this.api.log(`*** Rebooting due to initializer change (${file}) ***`, 'info')
            this.api.commands.restart()
          })

          if (typeof this.initializers[initializer].initialize === 'function') {
            if (typeof this.api.log === 'function') { this.api.log(`Loading initializer: ${initializer}`, 'debug', file) }
            try {
              this.initializers[initializer].initialize(this.api, (error) => {
                try { this.api.log(`Loaded initializer: ${initializer}`, 'debug', file) } catch (e) { }
                next(error)
              })
            } catch (e) {
              this.api.log(`Exception occured in initializer: ${initializer}  during load`, 'warning', e)
              next(e)
            }
          } else {
            next()
          }
        }

        const startFunction = (next) => {
          if (typeof this.initializers[initializer].start === 'function') {
            if (typeof this.api.log === 'function') { this.api.log(`Starting initializer: ${initializer}`, 'debug', file) }
            try {
              this.initializers[initializer].start(this.api, (error) => {
                this.api.log(`Started initializer: ${initializer}`, 'debug', file)
                next(error)
              })
            } catch (e) {
              this.api.log(`Exception occured in initializer: ${initializer} during start`, 'warning', e)
              next(e)
            }
          } else {
            next()
          }
        }

        const stopFunction = (next) => {
          if (typeof this.initializers[initializer].stop === 'function') {
            if (typeof this.api.log === 'function') { this.api.log(`Stopping initializer: ${initializer}`, 'debug', file) }
            try {
              this.initializers[initializer].stop(this.api, (error) => {
                this.api.log(`Stopped initializer: ${initializer}`, 'debug', file)
                next(error)
              })
            } catch (e) {
              this.api.log(`Exception occured in initializer: ${initializer} during stop`, 'warning', e)
              next(e)
            }
          } else {
            next()
          }
        }

        if (this.initializers[initializer].loadPriority === undefined) {
          this.initializers[initializer].loadPriority = this.api.initializerDefaults.load
        }
        if (this.initializers[initializer].startPriority === undefined) {
          this.initializers[initializer].startPriority = this.api.initializerDefaults.start
        }
        if (this.initializers[initializer].stopPriority === undefined) {
          this.initializers[initializer].stopPriority = this.api.initializerDefaults.stop
        }

        if (loadInitializerRankings[this.initializers[initializer].loadPriority] === undefined) {
          loadInitializerRankings[this.initializers[initializer].loadPriority] = []
        }
        if (startInitializerRankings[this.initializers[initializer].startPriority] === undefined) {
          startInitializerRankings[this.initializers[initializer].startPriority] = []
        }
        if (stopInitializerRankings[this.initializers[initializer].stopPriority] === undefined) {
          stopInitializerRankings[this.initializers[initializer].stopPriority] = []
        }

        if (this.initializers[initializer].loadPriority > 0) {
          loadInitializerRankings[this.initializers[initializer].loadPriority].push(loadFunction)
        }

        if (this.initializers[initializer].startPriority > 0) {
          startInitializerRankings[this.initializers[initializer].startPriority].push(startFunction)
        }

        if (this.initializers[initializer].stopPriority > 0) {
          stopInitializerRankings[this.initializers[initializer].stopPriority].push(stopFunction)
        }
      }
    })

    // flatten all the ordered initializer methods
    this.loadInitializers = flattenOrderedInitialzer(loadInitializerRankings)
    this.startInitializers = flattenOrderedInitialzer(startInitializerRankings)
    this.stopInitializers = flattenOrderedInitialzer(stopInitializerRankings)

    this.loadInitializers.push(() => {
      process.nextTick(() => {
        this.api.initialized = true

        if (duplicatedInitializers.length > 0) {
          duplicatedInitializers.forEach(initializer => this.api.log(`Initializer ${initializer} already exists!`, 'error'))
          this.api.commands.stop.call(this.api, () => {
            process.exit(1)
          })
        }
        callback(null, this.api)
      })
    })

    async.series(this.loadInitializers, (errors) => { fatalError(this.api, errors, 'initialize') })
  })

  async.series(this.configInitializers, (errors) => { fatalError(this.api, errors, 'config') })
}

actionhero.prototype.start = function (params, callback) {
  if (!callback && typeof params === 'function') {
    callback = params; params = {}
  }

  const _start = () => {
    this.api.running = true

    this.api.log('*** Starting ActionHero ***', 'notice')

    this.startInitializers.push(() => {
      this.api.bootTime = new Date().getTime()
      if (startCount === 0) {
        this.api.log('*** ActionHero Started ***', 'alert')
      } else {
        this.api.log('*** ActionHero Restarted ***', 'alert')
      }

      startCount++
      callback(null, this.api)
    })

    async.series(this.startInitializers, (errors) => { fatalError(this.api, errors, 'start') })
  }

  if (this.api.initialized === true) {
    _start()
  } else {
    this.initialize(params, () => {
      _start()
    })
  }
}

actionhero.prototype.stop = function (callback) {
  if (this.api.running === true) {
    this.api.shuttingDown = true
    this.api.running = false
    this.api.initialized = false

    this.api.log('Shutting down open servers and stopping task processing...', 'notice')

    this.stopInitializers.push(() => {
      this.api.unWatchAllFiles()
      this.api.pids.clearPidFile()
      this.api.log('*** ActionHero Stopped ***', 'alert')
      this.api.log('***', 'debug')
      delete this.api.shuttingDown
      // reset initializers to prevent duplicate check on restart
      this.initializers = {}
      process.nextTick(() => {
        if (typeof callback === 'function') { callback(null, this.api) }
      })
    })

    async.series(this.stopInitializers, (errors) => { fatalError(this.api, errors, 'stop') })
  } else if (this.api.shuttingDown === true) {
    // double sigterm; ignore it
  } else {
    if (this.api.log) { this.api.log('Cannot shut down actionhero, not running', 'error') }
    if (typeof callback === 'function') { callback(null, this.api) }
  }
}

actionhero.prototype.restart = function (callback) {
  if (this.api.running === true) {
    this.stop((error) => {
      if (error) { this.api.log(error, 'error') }
      this.start(this.startingParams, (error) => {
        if (error) { this.api.log(error, 'error') }
        if (typeof callback === 'function') { callback(null, this.api) }
      })
    })
  } else {
    this.start(this.startingParams, (error) => {
      if (error) { this.api.log(error, 'error') }
      if (typeof callback === 'function') { callback(null, this.api) }
    })
  }
}

module.exports = actionhero
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { Router } from 'meteor/iron:router';
import { Bert } from 'meteor/themeteorchef:bert';
import { lodash } from 'meteor/stevezhu:lodash';
import { ReactiveVar } from 'meteor/reactive-var';
import 'meteor/mizzao:autocomplete';
import 'meteor/sacha:spin';

import './addAGame.jade';

Template.addAGame.onCreated(function() {
	this.autorun(() => {
		this.subscribe('allUsersForAChampionship', Router.current().params._id);
	});
});

Template.addAGame.onRendered(function() {
	this.player1Id = new ReactiveVar('');
	this.player2Id = new ReactiveVar('');
	$(document).on('click', 'input[type=text]', function() { this.select(); });
	let list = Meteor.users.find({ 'profile.championships': Router.current().params._id }, {
		fields: {
			'profile.firstName': 1,
			'profile.lastName': 1
		}
	}).fetch();
	list.map((cur, index, array) => {
		let data = {
			userId: cur._id,
			firstName: cur.profile.firstName,
			lastName: cur.profile.lastName
		};
		Meteor.call('updateUserData', data);
	});
});

Template.addAGame.helpers({
	settings() {
		return {
			position: 'bottom',
			limit: 5,
			matchAll: true,
			rules: [{
				collection: Meteor.users,
				field: 'profile.fullName',
				template: Template.userPill
			}]
		};
	},
	playerInChampionship() {
		if (lodash.includes(Meteor.user().profile.championships, Router.current().params._id)) {
			return true;
		} else {
			return false;
		}
	}
});

Template.addAGame.events({
	'autocompleteselect #player1fullName': function(event, template, doc) {
		Template.instance().player1Id.set(doc._id);
	},
	'autocompleteselect #player2fullName': function(event, template, doc) {
		Template.instance().player2Id.set(doc._id);
	},
	'click #addAGame': function(event) {
		event.preventDefault();

		function saveBegin() {
			$('#addAGame').remove();
			Blaze.render(Template.progressBar, $('#buttonOrProgressBar').get(0));
		}

		function saveEnd() {
			$('.progress').remove();
			Blaze.render(Template.validateButton, $('#buttonOrProgressBar').get(0));
		}

		function cleanForm() {
			$('.has-feedback').removeClass('has-success');
			$('.has-feedback').removeClass('has-warning');
			$('.has-feedback').removeClass('has-error');
			$('.saveAGame').find('span').remove();
		}

		function addValidation(template, element, state) {
			if (!element.hasClass('has-warning') && !element.hasClass('has-error') && !element.hasClass('has-success')) {
				element.addClass(state);
				Blaze.render(template, element.get(0));
			}
		}

		function playerInChampionship(playerId) {
			let inDb = Meteor.users.findOne({
				_id: playerId,
				'profile.championships': Router.current().params._id
			}, {
				fields: { _id: 1 }
			});
			if (inDb) {
				return true;
			} else {
				return false;
			}
		}

		// Init
		cleanForm();
		saveBegin();
		let player1OK = true;
		let player2OK = true;
		let score = true;

		const data = {
			player1: Template.instance().player1Id.get(),
			player2: Template.instance().player2Id.get(),
			scorePlayer1: Number($('#player1Score').val()),
			scorePlayer2: Number($('#player2Score').val()),
			gameDate: new Date(),
			addedBy: Meteor.userId(),
			championshipId: Router.current().params._id
		};

		if (!data.player1) {
			player1OK = false;
			addValidation(Template.playerNotDefined, $('.player1fullName'), 'has-error');
		}
		if (!data.player2) {
			player2OK = false;
			addValidation(Template.playerNotDefined, $('.player2fullName'), 'has-error');
		}
		if (!data.scorePlayer1) {
			score = false;
			addValidation(Template.scoreNotDefined, $('.player1Score'), 'has-error');
		}
		if (!data.scorePlayer2) {
			score = false;
			addValidation(Template.scoreNotDefined, $('.player2Score'), 'has-error');
		}
		if (data.scorePlayer1 < 10 && data.scorePlayer2 < 10) {
			score = false;
			addValidation(Template.minToWin, $('.player1Score'), 'has-warning');
			addValidation(Template.minToWin, $('.player2Score'), 'has-warning');
		}
		if (data.player1 === data.player2) {
			player1OK = false;
			player2OK = false;
			addValidation(Template.bothPlayersEqual, $('.player1fullName'), 'has-warning');
			addValidation(Template.bothPlayersEqual, $('.player2fullName'), 'has-warning');
		}
		if (data.scorePlayer1 === data.scorePlayer2) {
			score = false;
			addValidation(Template.bothScoresEqual, $('.player1Score'), 'has-warning');
			addValidation(Template.bothScoresEqual, $('.player2Score'), 'has-warning');
		}
		if (!playerInChampionship(data.player1)) {
			player1OK = false;
			addValidation(Template.playerNotInDb, $('.player1fullName'), 'has-error');
		}
		if (!playerInChampionship(data.player2)) {
			player2OK = false;
			addValidation(Template.playerNotInDb, $('.player2fullName'), 'has-error');
		}
		if (player1OK) {
			addValidation(Template.fieldOK, $('.player1fullName'), 'has-success');
		}
		if (player2OK) {
			addValidation(Template.fieldOK, $('.player2fullName'), 'has-success');
		}
		if (score) {
			addValidation(Template.fieldOK, $('.player1Score'), 'has-success');
			addValidation(Template.fieldOK, $('.player2Score'), 'has-success');
		}
		if (!player1OK) {
			return saveEnd();
		}
		if (!player2OK) {
			return saveEnd();
		}
		if (!score) {
			return saveEnd();
		}
		if (data.scorePlayer1 < data.scorePlayer2) {
			data.player1 = Template.instance().player2Id.get();
			data.player2 = Template.instance().player1Id.get();
			data.scorePlayer1 = Number($('#player2Score').val());
			data.scorePlayer2 = Number($('#player1Score').val());
		}

		Meteor.call('addAChampionshipGame', data, (error, result) => {
			if (error) {
				return Bert.alert(error.message, 'danger', 'growl-top-right');
			} else {
				$('input').val('');
				cleanForm();
				saveEnd();
			}
		});
	}
});
<commit_msg>Remove action in the onRendered part<commit_after>import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { Router } from 'meteor/iron:router';
import { Bert } from 'meteor/themeteorchef:bert';
import { lodash } from 'meteor/stevezhu:lodash';
import { ReactiveVar } from 'meteor/reactive-var';
import 'meteor/mizzao:autocomplete';
import 'meteor/sacha:spin';

import './addAGame.jade';

Template.addAGame.onCreated(function() {
	this.autorun(() => {
		this.subscribe('allUsersForAChampionship', Router.current().params._id);
	});
});

Template.addAGame.onRendered(function() {
	this.player1Id = new ReactiveVar('');
	this.player2Id = new ReactiveVar('');
	$(document).on('click', 'input[type=text]', function() { this.select(); });
});

Template.addAGame.helpers({
	settings() {
		return {
			position: 'bottom',
			limit: 5,
			matchAll: true,
			rules: [{
				collection: Meteor.users,
				field: 'profile.fullName',
				template: Template.userPill
			}]
		};
	},
	playerInChampionship() {
		if (lodash.includes(Meteor.user().profile.championships, Router.current().params._id)) {
			return true;
		} else {
			return false;
		}
	}
});

Template.addAGame.events({
	'autocompleteselect #player1fullName': function(event, template, doc) {
		Template.instance().player1Id.set(doc._id);
	},
	'autocompleteselect #player2fullName': function(event, template, doc) {
		Template.instance().player2Id.set(doc._id);
	},
	'click #addAGame': function(event) {
		event.preventDefault();

		function saveBegin() {
			$('#addAGame').remove();
			Blaze.render(Template.progressBar, $('#buttonOrProgressBar').get(0));
		}

		function saveEnd() {
			$('.progress').remove();
			Blaze.render(Template.validateButton, $('#buttonOrProgressBar').get(0));
		}

		function cleanForm() {
			$('.has-feedback').removeClass('has-success');
			$('.has-feedback').removeClass('has-warning');
			$('.has-feedback').removeClass('has-error');
			$('.saveAGame').find('span').remove();
		}

		function addValidation(template, element, state) {
			if (!element.hasClass('has-warning') && !element.hasClass('has-error') && !element.hasClass('has-success')) {
				element.addClass(state);
				Blaze.render(template, element.get(0));
			}
		}

		function playerInChampionship(playerId) {
			let inDb = Meteor.users.findOne({
				_id: playerId,
				'profile.championships': Router.current().params._id
			}, {
				fields: { _id: 1 }
			});
			if (inDb) {
				return true;
			} else {
				return false;
			}
		}

		// Init
		cleanForm();
		saveBegin();
		let player1OK = true;
		let player2OK = true;
		let score = true;

		const data = {
			player1: Template.instance().player1Id.get(),
			player2: Template.instance().player2Id.get(),
			scorePlayer1: Number($('#player1Score').val()),
			scorePlayer2: Number($('#player2Score').val()),
			gameDate: new Date(),
			addedBy: Meteor.userId(),
			championshipId: Router.current().params._id
		};

		if (!data.player1) {
			player1OK = false;
			addValidation(Template.playerNotDefined, $('.player1fullName'), 'has-error');
		}
		if (!data.player2) {
			player2OK = false;
			addValidation(Template.playerNotDefined, $('.player2fullName'), 'has-error');
		}
		if (!data.scorePlayer1) {
			score = false;
			addValidation(Template.scoreNotDefined, $('.player1Score'), 'has-error');
		}
		if (!data.scorePlayer2) {
			score = false;
			addValidation(Template.scoreNotDefined, $('.player2Score'), 'has-error');
		}
		if (data.scorePlayer1 < 10 && data.scorePlayer2 < 10) {
			score = false;
			addValidation(Template.minToWin, $('.player1Score'), 'has-warning');
			addValidation(Template.minToWin, $('.player2Score'), 'has-warning');
		}
		if (data.player1 === data.player2) {
			player1OK = false;
			player2OK = false;
			addValidation(Template.bothPlayersEqual, $('.player1fullName'), 'has-warning');
			addValidation(Template.bothPlayersEqual, $('.player2fullName'), 'has-warning');
		}
		if (data.scorePlayer1 === data.scorePlayer2) {
			score = false;
			addValidation(Template.bothScoresEqual, $('.player1Score'), 'has-warning');
			addValidation(Template.bothScoresEqual, $('.player2Score'), 'has-warning');
		}
		if (!playerInChampionship(data.player1)) {
			player1OK = false;
			addValidation(Template.playerNotInDb, $('.player1fullName'), 'has-error');
		}
		if (!playerInChampionship(data.player2)) {
			player2OK = false;
			addValidation(Template.playerNotInDb, $('.player2fullName'), 'has-error');
		}
		if (player1OK) {
			addValidation(Template.fieldOK, $('.player1fullName'), 'has-success');
		}
		if (player2OK) {
			addValidation(Template.fieldOK, $('.player2fullName'), 'has-success');
		}
		if (score) {
			addValidation(Template.fieldOK, $('.player1Score'), 'has-success');
			addValidation(Template.fieldOK, $('.player2Score'), 'has-success');
		}
		if (!player1OK) {
			return saveEnd();
		}
		if (!player2OK) {
			return saveEnd();
		}
		if (!score) {
			return saveEnd();
		}
		if (data.scorePlayer1 < data.scorePlayer2) {
			data.player1 = Template.instance().player2Id.get();
			data.player2 = Template.instance().player1Id.get();
			data.scorePlayer1 = Number($('#player2Score').val());
			data.scorePlayer2 = Number($('#player1Score').val());
		}

		Meteor.call('addAChampionshipGame', data, (error, result) => {
			if (error) {
				return Bert.alert(error.message, 'danger', 'growl-top-right');
			} else {
				$('input').val('');
				cleanForm();
				saveEnd();
			}
		});
	}
});
<|endoftext|>


<commit_before>App.NodesController = Ember.ArrayController.extend(App.Filterable, App.Sortable, {
  columns: ['select', 'health', 'state', 'status.trust', 'isTrustRegistered', 'name', 'vmInfo.count', 'cpuFrequency', 'utilization.gips_current','utilization.ipc','utilization.memory'],
  //needs: ['logBar'],
  filteredModel: function () {
    return App.Node.find();
  }.property('App.Node.@each'),
  filterProperties: ['name'],
  multipleNodesAreSelected: function () {
    return this.get('model').filterProperty('isSelected').length > 1;
  }.property('model.@each.isSelected'),
  totalVms: function () {
    if (this.get('model') === undefined) return null;
    return this.get('model').reduce(function (previousValue, item, index, enumerable) {
      var count = (item.get('vmInfo.count') > 0) ? item.get('vmInfo.count') : 0;
      return previousValue + count;
    }, 0);
  }.property('model.@each.vmInfo.count'),
  totalVcpus: function () {
    if (this.get('model') === undefined) return null;
    return this.get('model').reduce(function (previousValue, item, index, enumerable) {
      var count = (item.get('vcpus.used') > 0) ? item.get('vcpus.used') : 0;
      return previousValue + count;
    }, 0);
  }.property('model.@each.vcpus.used'),
  maxVcpus: function () {
    if (this.get('model') === undefined) return null;
    return this.get('model').reduce(function (previousValue, item, index, enumerable) {
      var max = (item.get('vcpus.max') > 0) ? item.get('vcpus.max') : 0;
      return previousValue + max;
    }, 0);
  }.property('model.@each.vcpus.max'),
  totalVcpusMessage: function () {
    var maxVcpus = (this.get('maxVcpus') == 0) ? 'N/A' : this.get('maxVcpus');
    return this.get('totalVcpus') + ' out of ' + maxVcpus + ' vCPUs';
  }.property('totalVcpus', 'maxVcpus'),
  totalVcpusWidth: function () {
    var percentage = (this.get('maxVcpus') == 0) ? 0 : (this.get('totalVcpus')/this.get('maxVcpus')) * 100;
    return 'width:' + percentage + '%;';
  }.property('totalVcpus', 'maxVcpus'),
  totalRam: function () {
    if (this.get('model') === undefined) return null;
    return this.get('model').reduce(function (previousValue, item, index, enumerable) {
      var count = (item.get('memory.used') > 0) ? item.get('memory.used') : 0;
      return previousValue + count;
    }, 0);
  }.property('model.@each.memory.used'),
  maxRam: function () {
    if (this.get('model') === undefined) return null;
    return this.get('model').reduce(function (previousValue, item, index, enumerable) {
      var max = (item.get('memory.max') > 0) ? item.get('memory.max') : 0;
      return previousValue + max;
    }, 0);
  }.property('model.@each.memory.max'),
  totalRamMessage: function () {
    return App.readableSize(this.get('totalRam') * 1048576) + ' out of ' + App.readableSize(this.get('maxRam') * 1048576);
  }.property('totalRam', 'maxRam'),
  totalRamWidth: function () {
    var percentage = (this.get('maxRam') == 0) ? 0 : (this.get('totalRam')/this.get('maxRam')) * 100;
    return 'width:' + percentage + '%;';
  }.property('totalRam', 'maxRam'),

  // Actions
  selectAll: function () {
    var isEverythingSelected = this.get('model').everyProperty('isSelected');
    this.get('model').setEach('isSelected', !isEverythingSelected);
  },
  expand: function (model) {
    if (!model.get('isActive')) {
      this.transitionToRoute('nodesNode', model);
    } else {
      this.transitionToRoute('nodes');
    }
  },
  exportTrustReport: function (reportContent){
    App.NodeTrustReport.find(reportContent.get('id')).then(function (nodeTrustReport) {
      if (nodeTrustReport !== null && (nodeTrustReport.get('attestations.length') > 0)) {
        var title = "SAM Node Trust Report";
        var subtitle = reportContent.get('name') + ' ('+reportContent.get('ids.ip_address')+')';
        var rowContent = [];
        rowContent.push("item.get('attestation_time_formatted')");
        rowContent.push("((item.get('trust_status'))?'The node was booted and was found attested as trusted.':'The node was booted and failed to be found attested as trusted.')");
        rowContent.push("item.get('trust_message')");
        App.pdfReport(nodeTrustReport, rowContent, title, subtitle, 'attestations');
      } else {
        App.Event('No trust attestation logs were found for this node.', App.WARNING);
      }
    }, function () {
      App.Event('Failed to load node trust report', App.ERROR);
    });
  },
  trustReportModal: function (model){
    var controller = this;
    modal = Ember.View.create({
      templateName: "nodeTrustReport-modal",
      controller: controller,
      content: model,
      modalHide: function() {
        $('#modal').modal('hide');
        var context = this;
        //setTimeout(context.remove, 3000);
        this.remove(); //destroys the element
      },
      didInsertElement: function (){
        $('#modal').modal('show');
      }
    }).appendTo('body');
  },
  unregister: function (node) {
    var confirmed = confirm('Note: You must uninstall the SAM node agent before doing the unregister action, or the node will be re-register once the SAM agent sends its next heartbeat message. Are you sure you want to unregister node "' + node.get('name') + '"? It will thereafter not be managed by ' + App.application.title + ' and disappear from this list of nodes. ');
    if (confirmed) {
      // TODO: add error handling for this delete node action
      node.deleteRecord();
      node.get('transaction').commit();
    }
  },
  reboot: function (node) {
    var confirmed = confirm('Are you sure you want to reboot node "' + node.get('name') + '"?');
    if (confirmed) {
      var jsonData = {
        "node": {
          "status": {
            "operational": 4
          }
        }
      };
      var ajaxOptions = $.extend({
        type: 'PUT',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/nodes/' + node.get('id'),
        data: JSON.stringify(jsonData),
        contentType: 'application/json',
        dataType: 'json'
      }, App.ajaxSetup);
      $.ajax(ajaxOptions).then(function (data, textStatus, jqXHR) {
        node.set('status.operational', App.REBOOTING);
        node.get('stateManager').transitionTo('rootState.loaded.saved');
        App.event('Successfully started rebooting node "' + node.get('name') + '"', App.SUCCESS);
      }, function (jqXHR, textStatus, errorThrown) {
        App.event('Failed to reboot node "' + node.get('name') + '"', App.ERROR);
      });
    }
  },
  control: function (node) {
    var confirmed = confirm('Are you sure you want to put node "' + node.get('name') + '" under the control of ' + App.application.get('title') + '?');
    if (confirmed) {
      var jsonData = {
        "node": {
          "under_sam_control": true
        }
      };
      var ajaxOptions = $.extend({
        type: 'PUT',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/nodes/' + node.get('id'),
        data: JSON.stringify(jsonData),
        contentType: 'application/json',
        dataType: 'json'
      }, App.ajaxSetup);
      $.ajax(ajaxOptions).then(function (data, textStatus, jqXHR) {
        node.set('underSamControl', true);
        node.get('stateManager').transitionTo('rootState.loaded.saved');
        App.event('Successfully put node "' + node.get('name') + '" under the control of ' + App.application.get('title'), App.SUCCESS);
      }, function (jqXHR, textStatus, errorThrown) {
        App.event('Failed to put node "' + node.get('name') + '" under the control of ' + App.application.get('title'), App.ERROR);
      });
    }
  },
  uncontrol: function (node) {
    var confirmed = confirm('Are you sure you want to remove node "' + node.get('name') + '" from the control of ' + App.application.get('title') + '?');
    if (confirmed) {
      var jsonData = {
        "node": {
          "under_sam_control": false
        }
      };
      var ajaxOptions = $.extend({
        type: 'PUT',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/nodes/' + node.get('id'),
        data: JSON.stringify(jsonData),
        contentType: 'application/json',
        dataType: 'json'
      }, App.ajaxSetup);
      $.ajax(ajaxOptions).then(function (data, textStatus, jqXHR) {
        node.set('underSamControl', false);
        node.get('stateManager').transitionTo('rootState.loaded.saved');
        App.event('Successfully removed node "' + node.get('name') + '" from the control of ' + App.application.get('title'), App.SUCCESS);
      }, function (jqXHR, textStatus, errorThrown) {
        App.event('Failed to removed node "' + node.get('name') + '" from the control of ' + App.application.get('title'), App.ERROR);
      });
    }
  },
  schedule: function (node, socketNumber) {
    socketNumber = Ember.isEmpty(socketNumber) ? 0 : parseInt(socketNumber.toFixed());
    var confirmed = confirm('Are you sure you want all future VMs to be placed on node "' + node.get('name') + '"?');
    if (confirmed) {
      var jsonData = {
        "node": {
          "scheduler_mark": socketNumber,
          "scheduler_persistent": true
        }
      };
      var ajaxOptions = $.extend({
        type: 'PUT',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/nodes/' + node.get('id'),
        data: JSON.stringify(jsonData),
        contentType: 'application/json',
        dataType: 'json'
      }, App.ajaxSetup);
      $.ajax(ajaxOptions).then(function (data, textStatus, jqXHR) {
        // Unset all other nodes
        App.Node.all().filterProperty('isScheduled', true).forEach(function (item, index) {
          item.set('schedulerMark', null);
          item.get('stateManager').transitionTo('rootState.loaded.saved');
        });
        // Set this node for VM placement
        node.set('schedulerMark', 0);
        node.set('schedulerPersistent', true);
        node.get('stateManager').transitionTo('rootState.loaded.saved');
        App.event('Successfully set node "' + node.get('name') + '" for VM placement', App.SUCCESS);
      }, function (jqXHR, textStatus, errorThrown) {
        App.event('Failed to set node "' + node.get('name') + '" for VM placement', App.ERROR);
      });
    }
  },
  unschedule: function (node) {
    var confirmed = confirm('Are you sure you want to unset node "' + node.get('name') + '" for future VM placement and return to standard VM placement?');
    if (confirmed) {
      var jsonData = {
        "node": {
          "scheduler_mark": null
        }
      };
      var ajaxOptions = $.extend({
        type: 'PUT',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/nodes/' + node.get('id'),
        data: JSON.stringify(jsonData),
        contentType: 'application/json',
        dataType: 'json'
      }, App.ajaxSetup);
      $.ajax(ajaxOptions).then(function (data, textStatus, jqXHR) {
        node.set('schedulerMark', null);
        node.get('stateManager').transitionTo('rootState.loaded.saved');
        App.event('Successfully unset node "' + node.get('name') + '" for VM placement', App.SUCCESS);
      }, function (jqXHR, textStatus, errorThrown) {
        App.event('Failed to unset node "' + node.get('name') + '" for VM placement', App.ERROR);
      });
    }
  },
  addTrust: function (node) {
    var confirmed = confirm('Are you sure you want to register node "' + node.get('name') + '" as trusted?');
    if (confirmed) {
      var jsonData = {
        "node_ids": [{
          "node_id": node.get('id')
        }]
      };
      var ajaxOptions = $.extend({
        type: 'POST',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/trust_nodes',
        data: JSON.stringify(jsonData),
        contentType: 'application/json',
        dataType: 'json'
      }, App.ajaxSetup);
      App.ajaxPromise(ajaxOptions).then(function (data, textStatus, jqXHR) {
        node.reload();
        node.get('nodeTrust').reload();
        App.event('Successfully registered node "' + node.get('name') + '" as trusted', App.SUCCESS);
      }, function (qXHR, textStatus, errorThrown) {
        App.event('Failed to register node "' + node.get('name') + '" as trusted', App.ERROR);
      });
    }
  },
  removeTrust: function (node) {
    var confirmed = confirm('Are you sure you want to unregister node "' + node.get('name') + ' as trusted"?');
    if (confirmed) {
      var ajaxOptions = $.extend({
        type: 'DELETE',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/trust_nodes/' + node.get('id'),
        contentType: "application/json",
        dataType: "json"
      }, App.ajaxSetup);
      App.ajaxPromise(ajaxOptions).then(function (data, textStatus, jqXHR) {
        node.reload();
        node.get('trustNode').reload();
        App.event('Successfully unregistered node "' + node.get('name') + '" as trusted', App.SUCCESS);
      }, function (qXHR, textStatus, errorThrown) {
        App.event('Failed to unregister node "' + node.get('name') + '" as trusted', App.ERROR);
      });
    }
  },
  trustFingerprint: function (node) {
    var confirmed = confirm('Are you sure you want to fingerprint node "' + node.get('name') + '"?');
    if (confirmed) {
      var jsonData = {
        "node_id": node.get('id')
      };
      var ajaxOptions = $.extend({
        type: 'POST',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/trust_mles',
        data: JSON.stringify(jsonData),
        contentType: 'application/json',
        dataType: 'json'
      }, App.ajaxSetup);
      App.ajaxPromise(ajaxOptions).then(function (data, textStatus, jqXHR) {
        node.reload();
        App.event('Successfully fingerprinted node "' + node.get('name') + '"', App.SUCCESS);
      }, function (qXHR, textStatus, errorThrown) {
        App.event('Failed to fingerprint node "' + node.get('name') + '"', App.ERROR);
      });
    }
  },
  refresh: function () {
    App.Node.all().clear();
    if (App.mtWilson.get('isInstalled') === true) {
      App.TrustNode.find().then(function() {
        App.Node.find();
      });
    } else {
      App.Node.find();
    }
  }
});
<commit_msg>Trust node reload on the trustFingerprint action.<commit_after>App.NodesController = Ember.ArrayController.extend(App.Filterable, App.Sortable, {
  columns: ['select', 'health', 'state', 'status.trust', 'isTrustRegistered', 'name', 'vmInfo.count', 'cpuFrequency', 'utilization.gips_current','utilization.ipc','utilization.memory'],
  //needs: ['logBar'],
  filteredModel: function () {
    return App.Node.find();
  }.property('App.Node.@each'),
  filterProperties: ['name'],
  multipleNodesAreSelected: function () {
    return this.get('model').filterProperty('isSelected').length > 1;
  }.property('model.@each.isSelected'),
  totalVms: function () {
    if (this.get('model') === undefined) return null;
    return this.get('model').reduce(function (previousValue, item, index, enumerable) {
      var count = (item.get('vmInfo.count') > 0) ? item.get('vmInfo.count') : 0;
      return previousValue + count;
    }, 0);
  }.property('model.@each.vmInfo.count'),
  totalVcpus: function () {
    if (this.get('model') === undefined) return null;
    return this.get('model').reduce(function (previousValue, item, index, enumerable) {
      var count = (item.get('vcpus.used') > 0) ? item.get('vcpus.used') : 0;
      return previousValue + count;
    }, 0);
  }.property('model.@each.vcpus.used'),
  maxVcpus: function () {
    if (this.get('model') === undefined) return null;
    return this.get('model').reduce(function (previousValue, item, index, enumerable) {
      var max = (item.get('vcpus.max') > 0) ? item.get('vcpus.max') : 0;
      return previousValue + max;
    }, 0);
  }.property('model.@each.vcpus.max'),
  totalVcpusMessage: function () {
    var maxVcpus = (this.get('maxVcpus') == 0) ? 'N/A' : this.get('maxVcpus');
    return this.get('totalVcpus') + ' out of ' + maxVcpus + ' vCPUs';
  }.property('totalVcpus', 'maxVcpus'),
  totalVcpusWidth: function () {
    var percentage = (this.get('maxVcpus') == 0) ? 0 : (this.get('totalVcpus')/this.get('maxVcpus')) * 100;
    return 'width:' + percentage + '%;';
  }.property('totalVcpus', 'maxVcpus'),
  totalRam: function () {
    if (this.get('model') === undefined) return null;
    return this.get('model').reduce(function (previousValue, item, index, enumerable) {
      var count = (item.get('memory.used') > 0) ? item.get('memory.used') : 0;
      return previousValue + count;
    }, 0);
  }.property('model.@each.memory.used'),
  maxRam: function () {
    if (this.get('model') === undefined) return null;
    return this.get('model').reduce(function (previousValue, item, index, enumerable) {
      var max = (item.get('memory.max') > 0) ? item.get('memory.max') : 0;
      return previousValue + max;
    }, 0);
  }.property('model.@each.memory.max'),
  totalRamMessage: function () {
    return App.readableSize(this.get('totalRam') * 1048576) + ' out of ' + App.readableSize(this.get('maxRam') * 1048576);
  }.property('totalRam', 'maxRam'),
  totalRamWidth: function () {
    var percentage = (this.get('maxRam') == 0) ? 0 : (this.get('totalRam')/this.get('maxRam')) * 100;
    return 'width:' + percentage + '%;';
  }.property('totalRam', 'maxRam'),

  // Actions
  selectAll: function () {
    var isEverythingSelected = this.get('model').everyProperty('isSelected');
    this.get('model').setEach('isSelected', !isEverythingSelected);
  },
  expand: function (model) {
    if (!model.get('isActive')) {
      this.transitionToRoute('nodesNode', model);
    } else {
      this.transitionToRoute('nodes');
    }
  },
  exportTrustReport: function (reportContent){
    App.NodeTrustReport.find(reportContent.get('id')).then(function (nodeTrustReport) {
      if (nodeTrustReport !== null && (nodeTrustReport.get('attestations.length') > 0)) {
        var title = "SAM Node Trust Report";
        var subtitle = reportContent.get('name') + ' ('+reportContent.get('ids.ip_address')+')';
        var rowContent = [];
        rowContent.push("item.get('attestation_time_formatted')");
        rowContent.push("((item.get('trust_status'))?'The node was booted and was found attested as trusted.':'The node was booted and failed to be found attested as trusted.')");
        rowContent.push("item.get('trust_message')");
        App.pdfReport(nodeTrustReport, rowContent, title, subtitle, 'attestations');
      } else {
        App.Event('No trust attestation logs were found for this node.', App.WARNING);
      }
    }, function () {
      App.Event('Failed to load node trust report', App.ERROR);
    });
  },
  trustReportModal: function (model){
    var controller = this;
    modal = Ember.View.create({
      templateName: "nodeTrustReport-modal",
      controller: controller,
      content: model,
      modalHide: function() {
        $('#modal').modal('hide');
        var context = this;
        //setTimeout(context.remove, 3000);
        this.remove(); //destroys the element
      },
      didInsertElement: function (){
        $('#modal').modal('show');
      }
    }).appendTo('body');
  },
  unregister: function (node) {
    var confirmed = confirm('Note: You must uninstall the SAM node agent before doing the unregister action, or the node will be re-register once the SAM agent sends its next heartbeat message. Are you sure you want to unregister node "' + node.get('name') + '"? It will thereafter not be managed by ' + App.application.title + ' and disappear from this list of nodes. ');
    if (confirmed) {
      // TODO: add error handling for this delete node action
      node.deleteRecord();
      node.get('transaction').commit();
    }
  },
  reboot: function (node) {
    var confirmed = confirm('Are you sure you want to reboot node "' + node.get('name') + '"?');
    if (confirmed) {
      var jsonData = {
        "node": {
          "status": {
            "operational": 4
          }
        }
      };
      var ajaxOptions = $.extend({
        type: 'PUT',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/nodes/' + node.get('id'),
        data: JSON.stringify(jsonData),
        contentType: 'application/json',
        dataType: 'json'
      }, App.ajaxSetup);
      $.ajax(ajaxOptions).then(function (data, textStatus, jqXHR) {
        node.set('status.operational', App.REBOOTING);
        node.get('stateManager').transitionTo('rootState.loaded.saved');
        App.event('Successfully started rebooting node "' + node.get('name') + '"', App.SUCCESS);
      }, function (jqXHR, textStatus, errorThrown) {
        App.event('Failed to reboot node "' + node.get('name') + '"', App.ERROR);
      });
    }
  },
  control: function (node) {
    var confirmed = confirm('Are you sure you want to put node "' + node.get('name') + '" under the control of ' + App.application.get('title') + '?');
    if (confirmed) {
      var jsonData = {
        "node": {
          "under_sam_control": true
        }
      };
      var ajaxOptions = $.extend({
        type: 'PUT',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/nodes/' + node.get('id'),
        data: JSON.stringify(jsonData),
        contentType: 'application/json',
        dataType: 'json'
      }, App.ajaxSetup);
      $.ajax(ajaxOptions).then(function (data, textStatus, jqXHR) {
        node.set('underSamControl', true);
        node.get('stateManager').transitionTo('rootState.loaded.saved');
        App.event('Successfully put node "' + node.get('name') + '" under the control of ' + App.application.get('title'), App.SUCCESS);
      }, function (jqXHR, textStatus, errorThrown) {
        App.event('Failed to put node "' + node.get('name') + '" under the control of ' + App.application.get('title'), App.ERROR);
      });
    }
  },
  uncontrol: function (node) {
    var confirmed = confirm('Are you sure you want to remove node "' + node.get('name') + '" from the control of ' + App.application.get('title') + '?');
    if (confirmed) {
      var jsonData = {
        "node": {
          "under_sam_control": false
        }
      };
      var ajaxOptions = $.extend({
        type: 'PUT',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/nodes/' + node.get('id'),
        data: JSON.stringify(jsonData),
        contentType: 'application/json',
        dataType: 'json'
      }, App.ajaxSetup);
      $.ajax(ajaxOptions).then(function (data, textStatus, jqXHR) {
        node.set('underSamControl', false);
        node.get('stateManager').transitionTo('rootState.loaded.saved');
        App.event('Successfully removed node "' + node.get('name') + '" from the control of ' + App.application.get('title'), App.SUCCESS);
      }, function (jqXHR, textStatus, errorThrown) {
        App.event('Failed to removed node "' + node.get('name') + '" from the control of ' + App.application.get('title'), App.ERROR);
      });
    }
  },
  schedule: function (node, socketNumber) {
    socketNumber = Ember.isEmpty(socketNumber) ? 0 : parseInt(socketNumber.toFixed());
    var confirmed = confirm('Are you sure you want all future VMs to be placed on node "' + node.get('name') + '"?');
    if (confirmed) {
      var jsonData = {
        "node": {
          "scheduler_mark": socketNumber,
          "scheduler_persistent": true
        }
      };
      var ajaxOptions = $.extend({
        type: 'PUT',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/nodes/' + node.get('id'),
        data: JSON.stringify(jsonData),
        contentType: 'application/json',
        dataType: 'json'
      }, App.ajaxSetup);
      $.ajax(ajaxOptions).then(function (data, textStatus, jqXHR) {
        // Unset all other nodes
        App.Node.all().filterProperty('isScheduled', true).forEach(function (item, index) {
          item.set('schedulerMark', null);
          item.get('stateManager').transitionTo('rootState.loaded.saved');
        });
        // Set this node for VM placement
        node.set('schedulerMark', 0);
        node.set('schedulerPersistent', true);
        node.get('stateManager').transitionTo('rootState.loaded.saved');
        App.event('Successfully set node "' + node.get('name') + '" for VM placement', App.SUCCESS);
      }, function (jqXHR, textStatus, errorThrown) {
        App.event('Failed to set node "' + node.get('name') + '" for VM placement', App.ERROR);
      });
    }
  },
  unschedule: function (node) {
    var confirmed = confirm('Are you sure you want to unset node "' + node.get('name') + '" for future VM placement and return to standard VM placement?');
    if (confirmed) {
      var jsonData = {
        "node": {
          "scheduler_mark": null
        }
      };
      var ajaxOptions = $.extend({
        type: 'PUT',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/nodes/' + node.get('id'),
        data: JSON.stringify(jsonData),
        contentType: 'application/json',
        dataType: 'json'
      }, App.ajaxSetup);
      $.ajax(ajaxOptions).then(function (data, textStatus, jqXHR) {
        node.set('schedulerMark', null);
        node.get('stateManager').transitionTo('rootState.loaded.saved');
        App.event('Successfully unset node "' + node.get('name') + '" for VM placement', App.SUCCESS);
      }, function (jqXHR, textStatus, errorThrown) {
        App.event('Failed to unset node "' + node.get('name') + '" for VM placement', App.ERROR);
      });
    }
  },
  addTrust: function (node) {
    var confirmed = confirm('Are you sure you want to register node "' + node.get('name') + '" as trusted?');
    if (confirmed) {
      var jsonData = {
        "node_ids": [{
          "node_id": node.get('id')
        }]
      };
      var ajaxOptions = $.extend({
        type: 'POST',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/trust_nodes',
        data: JSON.stringify(jsonData),
        contentType: 'application/json',
        dataType: 'json'
      }, App.ajaxSetup);
      App.ajaxPromise(ajaxOptions).then(function (data, textStatus, jqXHR) {
        node.reload();
        node.get('nodeTrust').reload();
        App.event('Successfully registered node "' + node.get('name') + '" as trusted', App.SUCCESS);
      }, function (qXHR, textStatus, errorThrown) {
        App.event('Failed to register node "' + node.get('name') + '" as trusted', App.ERROR);
      });
    }
  },
  removeTrust: function (node) {
    var confirmed = confirm('Are you sure you want to unregister node "' + node.get('name') + ' as trusted"?');
    if (confirmed) {
      var ajaxOptions = $.extend({
        type: 'DELETE',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/trust_nodes/' + node.get('id'),
        contentType: "application/json",
        dataType: "json"
      }, App.ajaxSetup);
      App.ajaxPromise(ajaxOptions).then(function (data, textStatus, jqXHR) {
        node.reload();
        node.get('trustNode').reload();
        App.event('Successfully unregistered node "' + node.get('name') + '" as trusted', App.SUCCESS);
      }, function (qXHR, textStatus, errorThrown) {
        App.event('Failed to unregister node "' + node.get('name') + '" as trusted', App.ERROR);
      });
    }
  },
  trustFingerprint: function (node) {
    var confirmed = confirm('Are you sure you want to fingerprint node "' + node.get('name') + '"?');
    if (confirmed) {
      var jsonData = {
        "node_id": node.get('id')
      };
      var ajaxOptions = $.extend({
        type: 'POST',
        url: ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/trust_mles',
        data: JSON.stringify(jsonData),
        contentType: 'application/json',
        dataType: 'json'
      }, App.ajaxSetup);
      App.ajaxPromise(ajaxOptions).then(function (data, textStatus, jqXHR) {
        node.reload();
        node.get('trustNode').reload();
        App.event('Successfully fingerprinted node "' + node.get('name') + '"', App.SUCCESS);
      }, function (qXHR, textStatus, errorThrown) {
        App.event('Failed to fingerprint node "' + node.get('name') + '"', App.ERROR);
      });
    }
  },
  refresh: function () {
    App.Node.all().clear();
    if (App.mtWilson.get('isInstalled') === true) {
      App.TrustNode.find().then(function() {
        App.Node.find();
      });
    } else {
      App.Node.find();
    }
  }
});
<|endoftext|>


<commit_before>import AppDispatcher from 'dispatchers/AppDispatcher';
import Utils from './Utils';
import NotificationController from 'controllers/NotificationController';

// Constants
import ImageVersionConstants from 'constants/ImageVersionConstants';

// Models
import ImageVersion from 'models/ImageVersion';

// Modals
import ModalHelpers from 'components/modals/ModalHelpers';

export default {

    update: function(version, newAttributes) {
      if(!version) throw new Error("Missing Image Version");
      if(!newAttributes) throw new Error("No attributes to be updated");

      version.set(newAttributes);
      //TODO:
      version.save(newAttributes, {
        patch:true,
      }).done(function(){
        // UPDATE_VERSION here if we do NOT want 'optimistic updating'
        // Othewise, do nothing..
      }).fail(function(err_resp){
        var error_json = err_resp.responseJSON;
        if (error_json.hasOwnProperty('non_field_errors')) {
            err_message = error_json.non_field_errors.join(" , ");
        } else {
            err_message = error_json;
        }
        var message = "Error updating Image Version " + version.get('name') + ": "+ err_message;
        NotificationController.error(null, message);
        Utils.dispatch(ImageVersionConstants.REMOVE_IMAGE_VERSION, {version: version});
      }).always(function(){
        // todo: add a POLL_IMAGE_VERSION constant if you want this to work (also need
        // to add a handler in the ImageVersionStore)
        //Utils.dispatch(ImageVersionConstants.POLL_IMAGE_VERSION, {version: version});
      });
    },

  }
<commit_msg>'err_message' is not defined<commit_after>import AppDispatcher from 'dispatchers/AppDispatcher';
import Utils from './Utils';
import NotificationController from 'controllers/NotificationController';

// Constants
import ImageVersionConstants from 'constants/ImageVersionConstants';

// Models
import ImageVersion from 'models/ImageVersion';

// Modals
import ModalHelpers from 'components/modals/ModalHelpers';

export default {

    update: function(version, newAttributes) {
      if(!version) throw new Error("Missing Image Version");
      if(!newAttributes) throw new Error("No attributes to be updated");

      version.set(newAttributes);
      version.save(newAttributes, {
        patch:true,
      }).done(function(){
        // UPDATE_VERSION here if we do NOT want 'optimistic updating'
        // Othewise, do nothing..
      }).fail(function(err_resp){
        var error_json = err_resp.responseJSON;
        let err_message = error_json;
        if (error_json.hasOwnProperty('non_field_errors')) {
            err_message = error_json.non_field_errors.join(" , ");
        }
        var message = "Error updating Image Version " + version.get('name') + ": "+ err_message;
        NotificationController.error(null, message);
        Utils.dispatch(ImageVersionConstants.REMOVE_IMAGE_VERSION, {version: version});
      }).always(function(){
        // todo: add a POLL_IMAGE_VERSION constant if you want this to work (also need
        // to add a handler in the ImageVersionStore)
        //Utils.dispatch(ImageVersionConstants.POLL_IMAGE_VERSION, {version: version});
      });
    },

  }
<|endoftext|>


<commit_before>define(function (require) {

  var Dispatcher = require('dispatchers/Dispatcher'),
    BaseStore = require('stores/BaseStore'),
    ResourceRequestCollection = require('collections/ResourceRequestCollection'),
    ResourceRequestConstants = require('constants/ResourceRequestConstants'),
    stores = require('stores');

  var ResourceRequestStore = BaseStore.extend({
    collection: ResourceRequestCollection
  });

  var store = new ResourceRequestStore();

  Dispatcher.register(function (dispatch) {
    var actionType = dispatch.action.actionType;
    var payload = dispatch.action.payload;
    var options = dispatch.action.options || options;

    switch (actionType) {
      case ResourceRequestConstants.UPDATE:
        store.update(payload.model);
        break;

      case ResourceRequestConstants.REMOVE:
        store.remove(payload.model);
        break;

      case ResourceRequestConstants.EMIT_CHANGE:
        break;

      default:
        return true;
    }

    if (!options.silent) {
      store.emitChange();
    }

    return true;
  });

  return store;

});
<commit_msg>send 'at' attribute when adding model<commit_after>define(function (require) {

  var Dispatcher = require('dispatchers/Dispatcher'),
    BaseStore = require('stores/BaseStore'),
    ResourceRequestCollection = require('collections/ResourceRequestCollection'),
    ResourceRequestConstants = require('constants/ResourceRequestConstants'),
    stores = require('stores');

  var ResourceRequestStore = BaseStore.extend({
    collection: ResourceRequestCollection
  });

  var store = new ResourceRequestStore();

  Dispatcher.register(function (dispatch) {
    var actionType = dispatch.action.actionType;
    var payload = dispatch.action.payload;
    var options = dispatch.action.options || options;

    switch (actionType) {
      case ResourceRequestConstants.ADD:
        store.add({data: payload.model, at: 0});
        break;

      case ResourceRequestConstants.UPDATE:
        store.update(payload.model);
        break;

      case ResourceRequestConstants.REMOVE:
        store.remove(payload.model);
        break;

      case ResourceRequestConstants.EMIT_CHANGE:
        break;

      default:
        return true;
    }

    if (!options.silent) {
      store.emitChange();
    }

    return true;
  });

  return store;

});
<|endoftext|>