Deploys a module component instance in the network's cluster.
12668
private void deployModule(final Node node, final InstanceContext instance, final CountingCompletionHandler<Void> counter) {
    log.debug(String.format("%s - Deploying %s to %s", NetworkManager.this, instance.component().asModule().module(), node.address()));
    node.deployModule(instance.component().asModule().module(), Components.buildConfig(instance, cluster), 1, new Handler<AsyncResult<String>>() {
      @Override
      public void handle(AsyncResult<String> result) {
        if (result.failed()) {
          counter.fail(result.cause());
        } else {
          deploymentIDs.put(instance.address(), result.result(), new Handler<AsyncResult<String>>() {
            @Override
            public void handle(AsyncResult<String> result) {
              counter.succeed();
            }
          });
        }
      }
    });
  }
508245
private void doDeployModule(final Message<JsonObject> message) {
    String moduleName = message.body().getString("module");
    if (moduleName == null) {
      message.reply(new JsonObject().putString("status", "error").putString("message", "No module name specified."));
      return;
    }

    JsonObject config = message.body().getObject("config");
    if (config == null) {
      config = new JsonObject();
    }
    int instances = message.body().getInteger("instances", 1);
    platform.deployModule(moduleName, config, instances, createDeploymentHandler(message));
  }
607003
function createComponent(conf, filename) {
  // create a mixin with the defined lifecycle events
  var events = {};
  for (var i = 0, event; i < lifecycle.length; i++) {
    event = lifecycle[i];
    if (conf[event]) events[event] = conf[event];
  }

  // load the standard mixins
  var mixins = [
    loadingStatus,
    events
  ].concat(conf.mixins || []);

  var component = {
    displayName: conf.displayName,

    mixins: mixins,

    contextTypes: merge({
      canary: ReactObj,
      errorHandler: ReactFunc,
      events: ReactFunc,
      format: ReactObj,
      forms: ReactObj,
      router: ReactObj,
      store: ReactObj.isRequired,
      translate: ReactObj,
    }, conf.contextTypes),

    __onus_onStoreChange: function(href) {
      var self = this;
      self.isMounted() && self.forceUpdate();
    },

    componentWillMount: function() {
      var self = this;
      var context = self.context;

      var store = self._store = context.store.context(self.__onus_onStoreChange);
      if (context.store.getAsync) self.getAsync = context.store.getAsync.bind(context.store);
      self._t = self._t || context.translate ? context.translate.context(store) : noop;
      if (context.canary) self.canary = context.canary.context(self.__onus_onStoreChange);

      Object.defineProperties(self, {
        forms: {
          get: function() {
            return context.forms;
          }
        },
        router: {
          get: function() {
            return context.router;
          }
        },
        location: {
          get: function() {
            return context.router.location;
          }
        }
      });

      self._error_handler = self._error_handler || context.errorHandler || noop;

      if (module.hot) {
        self.__onusComponentId = nextComponentId++;
        (conf.__subs = conf.__subs || {})[self.__onusComponentId] = function() {
          self.forceUpdate();
        };
      }

      if (conf.componentWillMount) conf.componentWillMount.call(this);
    },

    componentWillUnmount: function() {
      var self = this;
      if (module.hot) delete conf.__subs[self.__onusComponentId];
      self._store.destroy();
      if (self.canary) self.canary.destroy();
    },

    statics: conf.statics,

    _DOM: conf._DOM || createDomFn(conf, dom),

    _yield: conf._yield || _yield,

    _render: conf._render || createRenderFn(conf, dom),

    // TODO
    _error: function(DOM,
      get,
      props,
      state,
      _yield,
      params,
      query,
      forms,
      t,
      err) {
      if (err) console.error(err.stack || err);
      return false;
    },

    equalPairs: function() {
      var a = arguments;
      for (var i = 0; i < a.length; i+=2) {
        if (!this.isEqual(a[i], a[i + 1])) return false;
      }
      return true;
    },

    isEqual: function(a, b) {
      var typeA = typeof a;
      var typeB = typeof b
      // the types have changed
      if (typeA !== typeB) return false;
      // scalars
      if (a === b) return true;
      // defined values
      if (a && b) {
        if (typeof a.__hash !== 'undefined' && typeof b.__hash !== 'undefined') return a.__hash === b.__hash;
        if (typeof a.hashCode === 'function' && typeof b.hashCode === 'function') return a.hashCode() === b.hashCode();
      }
      // TODO add other comparisons
      return false;
    },

    loadedClassName: conf.loadedClassName || 'is-loaded',

    loadingClassName: conf.loadingClassName || 'is-loading',

    componentClassName: conf.componentClassName || conf.displayName + '-component',

    render: function() {
      // TODO see if we can cache this
      // TODO detect any recursive re-renders
      if (process.env.NODE_ENV === 'development') {
        if (typeof window !== 'undefined') {
          onus.renderCounts[conf.displayName] |= 0;
          onus.renderCounts[conf.displayName]++;
          onus.renderTotal++;
        }
      }

      return this._render();
    }
  };

  if (conf.initialState) component.getInitialState = function() {
    var state = {};
    for (var k in conf.initialState) {
      state[k] = conf.initialState[k];
    }
    return state;
  };

  for (var k in conf) {
    if (component[k] || !conf.hasOwnProperty(k) || events[k]) continue;
    component[k] = conf[k];
  }

  return React.createClass(component);
}
814031
function(parentModule, kbox, id, app, callback) {

  if (typeof callback === 'undefined' && typeof app === 'function') {
    callback = app;
    app = undefined;
  }

  // Try to load module from node_module directories.
  return requireFromNodeModules(parentModule, id)
  // If module was not found in node_module directories, try to load
  // from other directories.
  .then(function(mod) {
    if (mod) {
      return mod;
    } else {
      return requireFromOtherDirs(kbox, id, app);
    }
  })
  // Return.
  .nodeify(callback);

}
1056135
public Module build() {
        SagaLibModule module = new SagaLibModule();
        module.setStateStorage(stateStorage);
        module.setTimeoutManager(timeoutMgr);
        module.setScanner(scanner);
        module.setProviderFactory(providerFactory);
        module.setExecutionOrder(preferredOrder);
        module.setExecutionContext(executionContext);
        module.setModuleTypes(moduleTypes);
        module.setExecutor(executor);
        module.setInterceptorTypes(interceptorTypes);
        module.setStrategyFinder(strategyFinder);
        module.setInvoker(invoker);
        module.setCoordinatorFactory(coordinatorFactory);

        return module;
    }
918503
def _deploy(self):
        """"""
        timeout = int(os.environ.get('AMULET_SETUP_TIMEOUT', 900))
        try:
            self.d.setup(timeout=timeout)
            self.d.sentry.wait(timeout=timeout)
        except amulet.helpers.TimeoutError:
            amulet.raise_status(
                amulet.FAIL,
                msg="Deployment timed out ({}s)".format(timeout)
            )
        except Exception:
            raise
11141
@Bind(optional = true, aggregate = true)
    public synchronized void bindModule(Module module) {
        register(module);
    }
772470
private void doDeployModule(final Message<JsonObject> message) {
    String moduleName = message.body().getString("module");
    if (moduleName == null) {
      message.reply(new JsonObject().putString("status", "error").putString("message", "No module name specified."));
      return;
    }

    JsonObject config = message.body().getObject("config");
    if (config == null) {
      config = new JsonObject();
    }
    int instances = message.body().getInteger("instances", 1);
    platform.deployModule(moduleName, config, instances, new Handler<AsyncResult<String>>() {
      @Override
      public void handle(AsyncResult<String> result) {
        if (result.failed()) {
          message.reply(new JsonObject().putString("status", "error").putString("message", result.cause().getMessage()));
        } else {
          final String deploymentID = result.result();
          context.execute(new Action<String>() {
            @Override
            public String perform() {
              deployments.put(node, message.body().copy().putString("id", deploymentID).encode());
              return deploymentID;
            }
          }, new Handler<AsyncResult<String>>() {
            @Override
            public void handle(AsyncResult<String> result) {
              message.reply(new JsonObject().putString("status", "ok").putString("id", deploymentID));
            }
          });
        }
      }
    });
  }
1073907
public static void populateModuleSpecWithCoreDependencies(ModuleSpec.Builder moduleSpecBuilder, ScriptArchive scriptArchive) throws ModuleLoadException {
        Objects.requireNonNull(moduleSpecBuilder, "moduleSpecBuilder");
        Objects.requireNonNull(scriptArchive, "scriptArchive");

        Set<String> compilerPlugins = scriptArchive.getModuleSpec().getCompilerPluginIds();
        for (String compilerPluginId : compilerPlugins) {
            moduleSpecBuilder.addDependency(DependencySpec.createModuleDependencySpec(getPluginModuleId(compilerPluginId), false));
        }
        moduleSpecBuilder.addDependency(JRE_DEPENDENCY_SPEC);
        // TODO: Why does a module need a dependency on Nicobar itself?
        moduleSpecBuilder.addDependency(NICOBAR_CORE_DEPENDENCY_SPEC);
        moduleSpecBuilder.addDependency(DependencySpec.createLocalDependencySpec());
    }
139409
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();    
    final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION);
    
    // must be EE Module
    if(eeModuleDescription == null) {
      return;
    }

    // discover user-provided component
    ComponentDescription paComponent = detectExistingComponent(deploymentUnit); 

    if(paComponent != null) {      
      log.log(Level.INFO, "Detected user-provided @"+ProcessApplication.class.getSimpleName()+" component with name '"+paComponent.getComponentName()+"'.");
      
      // mark this to be a process application
      ProcessApplicationAttachments.attachProcessApplicationComponent(deploymentUnit, paComponent);
      ProcessApplicationAttachments.mark(deploymentUnit);
      ProcessApplicationAttachments.markPartOfProcessApplication(deploymentUnit);
    }
  }
923015
function setupSymlinks (module, modulesDir, callback) {

    let details = module.split('/');
    let modulePath = resolve(NODE_MODULES, details[1]);
    let devModulePath = resolve(modulesDir, module);

    rimraf(modulePath, err => {

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

        fs.symlink(devModulePath, modulePath, err => {

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

            callback();
        });
    });
}
380178
private <T> void deployJob(ExecutionContext<T> context, JobGraph jobGraph, Result<T> result) {
		// create or retrieve cluster and deploy job
		try (final ClusterDescriptor<T> clusterDescriptor = context.createClusterDescriptor()) {
			try {
				// new cluster
				if (context.getClusterId() == null) {
					deployJobOnNewCluster(clusterDescriptor, jobGraph, result, context.getClassLoader());
				}
				// reuse existing cluster
				else {
					deployJobOnExistingCluster(context.getClusterId(), clusterDescriptor, jobGraph, result);
				}
			} catch (Exception e) {
				throw new SqlExecutionException("Could not retrieve or create a cluster.", e);
			}
		} catch (SqlExecutionException e) {
			throw e;
		} catch (Exception e) {
			throw new SqlExecutionException("Could not locate a cluster.", e);
		}
	}
595652
def add(self, snapshot, distributions, component='main', storage=""):
        
        for dist in distributions:
            self.publish(dist, storage=storage).add(snapshot, component)
950673
function createVpcNetwork(mCb) {
			let networksOptions = Object.assign({}, options);
			networksOptions.params = {
				name,
				returnGlobalOperation: true
			};
			networks.add(networksOptions, (error, globalOperationResponse) => {
				if (error) return cb(error);
				
				//assign network name to deployment entry
				oneDeployment.options.network = name;
				
				//check if network is ready then update firewall rules
				checkVpcNetwork(globalOperationResponse, mCb);
			});
			
			function checkVpcNetwork(globalOperationResponse, mCb) {
				
				function globalOperations(miniCB) {
					options.soajs.log.debug("Checking network Create Status");
					//Ref https://cloud.google.com/compute/docs/reference/latest/globalOperations/get
					let request = getConnector(options.infra.api);
					delete request.projectId;
					request.operation = globalOperationResponse.name;
					v1Compute().globalOperations.get(request, (error, response) => {
						if (error) {
							return miniCB(error);
						}
						if (!response || response.status !== "DONE") {
							setTimeout(function () {
								globalOperations(miniCB);
							}, (process.env.SOAJS_CLOOSTRO_TEST) ? 1 : 5000);
						} else {
							return miniCB(null, response);
						}
					});
				}
				
				globalOperations(function (err) {
					if (err) {
						return mCb(err);
					} else {
						//Ref: https://cloud.google.com/compute/docs/reference/latest/firewalls/insert
						let firewallRules = getFirewallRules(oneDeployment.options.network);
						
						let request = getConnector(options.infra.api);
						async.eachSeries(firewallRules, (oneRule, vCb) => {
							options.soajs.log.debug("Registering new firewall rule:", oneRule.name);
							request.resource = oneRule;
							v1Compute().firewalls.insert(request, vCb);
						}, mCb);
					}
				});
				
			}
		}
1326740
public void addModule(Module module) {
        PreconditionUtil.verify(!initialized, "CrnkClient already initialized, cannot add further modules");
        if (module instanceof HttpAdapterAware) {
            ((HttpAdapterAware) module).setHttpAdapter(getHttpAdapter());
        }
        this.moduleRegistry.addModule(module);
    }
573611
async def loadmodule(self, module):
        '''
        
        '''
        self._logger.debug('Try to load module %r', module)
        if hasattr(module, '_instance'):
            self._logger.debug('Module is already initialized, module state is: %r', module._instance.state)
            if module._instance.state == ModuleLoadStateChanged.UNLOADING or module._instance.state == ModuleLoadStateChanged.UNLOADED:
                # Wait for unload
                um = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.UNLOADED)
                await um
            elif module._instance.state == ModuleLoadStateChanged.SUCCEEDED:
                pass
            elif module._instance.state == ModuleLoadStateChanged.FAILED:
                raise ModuleLoadException('Cannot load module %r before unloading the failed instance' % (module,))
            elif module._instance.state == ModuleLoadStateChanged.NOTLOADED or module._instance.state == ModuleLoadStateChanged.LOADED or module._instance.state == ModuleLoadStateChanged.LOADING:
                # Wait for succeeded or failed
                sm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.SUCCEEDED)
                fm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.FAILED)
                _, m = await M_(sm, fm)
                if m is sm:
                    pass
                else:
                    raise ModuleLoadException('Module load failed for %r' % (module,))
        if not hasattr(module, '_instance'):
            self._logger.info('Loading module %r', module)
            inst = module(self.server)
            # Avoid duplicated loading
            module._instance = inst
            # When reloading, some of the dependencies are broken, repair them
            if hasattr(module, 'referencedBy'):
                inst.dependedBy = set([m for m in module.referencedBy if hasattr(m, '_instance') and m._instance.state != ModuleLoadStateChanged.UNLOADED])
            # Load Module
            for d in module.depends:
                if hasattr(d, '_instance') and d._instance.state == ModuleLoadStateChanged.FAILED:
                    raise ModuleLoadException('Cannot load module %r, it depends on %r, which is in failed state.' % (module, d))
            try:
                for d in module.depends:
                    if hasattr(d, '_instance') and d._instance.state == ModuleLoadStateChanged.SUCCEEDED:
                        d._instance.dependedBy.add(module)
                preloads = [d for d in module.depends if not hasattr(d, '_instance') or \
                            d._instance.state != ModuleLoadStateChanged.SUCCEEDED]
                for d in preloads:
                    self.subroutine(self.loadmodule(d), False)
                sms = [ModuleLoadStateChanged.createMatcher(d, ModuleLoadStateChanged.SUCCEEDED) for d in preloads]
                fms = [ModuleLoadStateChanged.createMatcher(d, ModuleLoadStateChanged.FAILED) for d in preloads]
                def _callback(event, matcher):
                    raise ModuleLoadException('Cannot load module %r, it depends on %r, which is in failed state.' % (module, event.module))
                await self.with_callback(self.wait_for_all(*sms), _callback, *fms)
            except:
                for d in module.depends:
                    if hasattr(d, '_instance') and module in d._instance.dependedBy:
                        self._removeDepend(module, d)
                self._logger.warning('Loading module %r stopped', module, exc_info=True)
                # Not loaded, send a message to notify that parents can not 
                async def _msg():
                    await self.wait_for_send(ModuleLoadStateChanged(module, ModuleLoadStateChanged.UNLOADED, inst))
                self.subroutine(_msg(), False)
                del module._instance
                raise
            for d in preloads:
                d._instance.dependedBy.add(module)
            self.activeModules[inst.getServiceName()] = module
            await module._instance.changestate(ModuleLoadStateChanged.LOADING, self)
            await module._instance.load(self)
            if module._instance.state == ModuleLoadStateChanged.LOADED or module._instance.state == ModuleLoadStateChanged.LOADING:
                sm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.SUCCEEDED)
                fm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.FAILED)
                _, m = await M_(sm, fm)
                if m is sm:
                    pass
                else:
                    raise ModuleLoadException('Module load failed for %r' % (module,))
            self._logger.info('Loading module %r completed, module state is %r', module, module._instance.state)
            if module._instance.state == ModuleLoadStateChanged.FAILED:
                raise ModuleLoadException('Module load failed for %r' % (module,))
969376
def module_broadcast(m, broadcast_fn, *args, **kwargs):
    
    apply_leaf(m, lambda x: module_apply_broadcast(x, broadcast_fn, args, kwargs))