Checks for updates from an admin command.  The target state will be the
initial state, i.e. update will not start a lazy instance.

@param deploy the owning controller
557407
@Override
  public void update(DeployService2Impl<I> deploy, Result<I> result)
  {
    LifecycleState state = deploy.getState();
    
    if (state.isStopped()) {
      deploy.startImpl(result);
    }
    else if (state.isError()) {
      deploy.restartImpl(result);
    }
    else if (deploy.isModifiedNow()) {
      deploy.restartImpl(result);
    }
    else { /* active */
      result.ok(deploy.get());
    }
  }
1200488
protected function deploy()
    {
        // create deploy outputfile
        $this->createOutputFile($this->outputFile, false);

        // create undo deploy outputfile
        $this->createOutputFile($this->undoOutputFile, true);
    }
636065
def run(self):
        

        self.sanity_check()

# TODO - check for devel
#        if not self.version:
#            raise Exception("no version")
# XXX check attr exist
        if not self.release_environment:
            raise Exception("no instance name")

        time_start = time.time()

        cwd = os.getcwd()

        who = getpass.getuser()
        self._make_outdirs()

        append_notices = ""
        if hasattr(self, 'opt_end'):
            append_notices = ". shortened push, only to %s stage" % self.opt_end
        if self.is_devel:
            append_notices += ". devel build"
        if hasattr(self, 'append_notices'):
            append_notices += self.append_notices

        line = "%s %s %s by %s%s" % (
            sys.argv[0], self.version, self.release_environment, who, append_notices)
        b = 'deploy begin %s' % line
        e = 'deploy done %s' % line

        if self.chatty:
            self.alact(b)

        ok = False
        stage_passed = None
        try:
            for stage in self.stages[self.stage_start:self.stage_end]:
                self.debug_msg("stage %s starting" % (stage,))
                getattr(self, stage)()
                self.chdir(cwd)
                stage_passed = stage
                self.debug_msg("stage %s complete" % (stage,))
            ok = True
        finally:
            if not ok:
                if self.chatty:
                    if not stage_passed:
                        self.alact(
                            'deploy failed %s. completed no stages' % line)
                    else:
                        self.alact('deploy failed %s. completed %s' %
                                   (line, stage_passed))
        self.status_msg('[OK]')
        if self.chatty:
            self.alact('%s in %0.3f sec' % (e, time.time() - time_start))

        return 0
727498
function replSetGetStatus(admin, options, callback) {
  executeDbAdminCommand(admin.s.db, { replSetGetStatus: 1 }, options, callback);
}
382006
@Override
  public void updateDeployment(final String host, final Deployment deployment, final String token)
      throws HostNotFoundException, JobNotDeployedException, TokenVerificationException {
    log.info("updating deployment {}: {}", deployment, host);

    final ZooKeeperClient client = provider.get("updateDeployment");

    final JobId jobId = deployment.getJobId();
    final Job job = getJob(client, jobId);
    final Deployment existingDeployment = getDeployment(host, jobId);

    if (job == null) {
      throw new JobNotDeployedException(host, jobId);
    }
    verifyToken(token, job);

    assertHostExists(client, host);
    assertTaskExists(client, host, deployment.getJobId());

    final String path = Paths.configHostJob(host, jobId);
    final Task task = new Task(job, deployment.getGoal(),
        existingDeployment.getDeployerUser(),
        existingDeployment.getDeployerMaster(),
        existingDeployment.getDeploymentGroupName());
    try {
      client.setData(path, task.toJsonBytes());
    } catch (Exception e) {
      throw new HeliosRuntimeException("updating deployment " + deployment
                                       + " on host " + host + " failed", e);
    }
  }
6033
private void updateState(CmsShellCommandResult result) {

        m_errorCode = result.getErrorCode();
        m_prompt = result.getPrompt();
        m_exitCalled = result.isExitCalled();
        m_hasError = result.hasError();
        m_echo = result.hasEcho();
    }
296666
function(command) {
            var self    = this,
                control = null,
                output  = new mixitup.CommandMultimix(),
                i       = -1;

            self.callActions('beforeUpdateControls', arguments);

            // Sanitise to defaults

            if (command.filter) {
                output.filter = command.filter.selector;
            } else {
                output.filter = self.state.activeFilter.selector;
            }

            if (command.sort) {
                output.sort = self.buildSortString(command.sort);
            } else {
                output.sort = self.buildSortString(self.state.activeSort);
            }

            if (output.filter === self.config.selectors.target) {
                output.filter = 'all';
            }

            if (output.filter === '') {
                output.filter = 'none';
            }

            h.freeze(output);

            for (i = 0; control = self.controls[i]; i++) {
                control.update(output, self.toggleArray);
            }

            self.callActions('afterUpdateControls', arguments);
        }
1048268
@Override
    public void onDeploy(DeploymentEvent event) {
        AbstractRuntimeManager runtimeManager = (AbstractRuntimeManager) event.getDeployedUnit().getRuntimeManager();        
        KieBase kieBase = runtimeManager.getEnvironment().getKieBase();
        Collection<Process> processes = kieBase.getProcesses(); 
        
        Map<String, DeployedAsset> mapProcessById = event.getDeployedUnit().getDeployedAssets()
                                                                            .stream()
                                                                            .collect(toMap(DeployedAsset::getId, asset -> asset));        
        for( Process process : processes ) {
            if( ((WorkflowProcess)process).isDynamic()) {
                String caseIdPrefix = collectCaseIdPrefix(process);
                Collection<CaseMilestone> caseMilestones = collectMilestoness(process);
                Collection<CaseStage> caseStages = collectCaseStages(event.getDeploymentId(), process.getId(), ((WorkflowProcess)process));                
                Collection<CaseRole> caseRoles = collectCaseRoles(process);
                Collection<AdHocFragment> adHocFragments = collectAdHocFragments((WorkflowProcess)process);
                Map<String, List<String>> dataAccessRestrictions = collectDataAccessRestrictions(process);
                
                CaseDefinitionImpl caseDef = new CaseDefinitionImpl((ProcessAssetDesc) mapProcessById.get(process.getId()), caseIdPrefix, caseStages, caseMilestones, caseRoles, adHocFragments, dataAccessRestrictions);
                
                availableCases.add(caseDef);
                caseIdGenerator.register(caseIdPrefix);
            }
        }
        
        // collect role information
        Collection<DeployedAsset> assets = event.getDeployedUnit().getDeployedAssets();
        List<String> roles = null;
        for( DeployedAsset asset : assets ) {
            if( asset instanceof ProcessAssetDesc ) {  
                // if it's not dynamic it's considered as not case definition
                if (!((ProcessAssetDesc) asset).isDynamic()) {
                    availableProcesses.add((ProcessAssetDesc) asset);
                }
                if (roles == null) {
                    roles = ((ProcessAssetDesc) asset).getRoles();
                }
            }
        }
        if (roles == null) {
            roles = Collections.emptyList();
        }
        deploymentRolesManager.addRolesForDeployment(event.getDeploymentId(), roles);

    }
618198
protected void setAdminState(AdminStates newState) {
    if (newState == AdminStates.NORMAL) {
      adminState = null;
    }
    else {
      adminState = newState;
    }
  }
1153030
@Override
    protected void updateState(final String name, final InstallationModificationImpl modification, final InstallationModificationImpl.InstallationState state) {
        final PatchableTarget.TargetInfo identityInfo = modification.getModifiedState();
        this.identity = new Identity() {
            @Override
            public String getVersion() {
                return modification.getVersion();
            }

            @Override
            public String getName() {
                return name;
            }

            @Override
            public TargetInfo loadTargetInfo() throws IOException {
                return identityInfo;
            }

            @Override
            public DirectoryStructure getDirectoryStructure() {
                return modification.getDirectoryStructure();
            }
        };

        this.allPatches = Collections.unmodifiableList(modification.getAllPatches());
        this.layers.clear();
        for (final Map.Entry<String, MutableTargetImpl> entry : state.getLayers().entrySet()) {
            final String layerName = entry.getKey();
            final MutableTargetImpl target = entry.getValue();
            putLayer(layerName, new LayerInfo(layerName, target.getModifiedState(), target.getDirectoryStructure()));
        }
        this.addOns.clear();
        for (final Map.Entry<String, MutableTargetImpl> entry : state.getAddOns().entrySet()) {
            final String addOnName = entry.getKey();
            final MutableTargetImpl target = entry.getValue();
            putAddOn(addOnName, new LayerInfo(addOnName, target.getModifiedState(), target.getDirectoryStructure()));
        }
    }
655369
@VisibleForTesting
  void checkSchedulerForInconsistentState() {
    final long now = System.currentTimeMillis();

    final Map<SingularityDeployKey, SingularityPendingTaskId> deployKeyToPendingTaskId = getDeployKeyToPendingTaskId();

    for (SingularityRequestWithState requestWithState : requestManager.getRequests()) {
      switch (requestWithState.getState()) {
        case ACTIVE:
        case SYSTEM_COOLDOWN:
        case DEPLOYING_TO_UNPAUSE:
          checkActiveRequest(requestWithState, deployKeyToPendingTaskId, now);
          break;
        case DELETED:
        case PAUSED:
        case FINISHED:
          break;
      }
    }
  }
973152
private RollingUpdateOp forceRollingUpdateUndeploy(final ZooKeeperClient client,
                                                     final RollingUpdateOpFactory opFactory,
                                                     final DeploymentGroup deploymentGroup,
                                                     final String host) {
    return rollingUpdateUndeploy(client, opFactory, deploymentGroup, host, false);
  }
664562
function updateDeploy() {

    function promisedGit(args, options) {
        const argsArr = ['git'];
        Array.prototype.push.apply(argsArr, args);
        options = options || {};
        options.capture = options.capture === undefined ? true : options.capture;
        options.useErrHandler = options.useErrHandler === undefined ? true : options.useErrHandler;
        return promisedSpawn(argsArr, options);
    }

    function chainedPgit(args, options) {
        const arg = args.shift();
        if (!arg) {
            return P.resolve();
        }
        return promisedGit(arg, options)
        .then((data) => {
            if (args.length === 0) {
                return P.resolve(data);
            }
            return chainedPgit(args, options);
        });
    }

    // check if there is an alternative repo name defined
    return P.props({
        name: promisedGit(['config', 'deploy.name'], { ignoreErr: true }),
        remote: promisedGit(['config', 'deploy.remote'], { ignoreErr: true }),
        submodule_ref: promisedGit(['config', 'deploy.submodule'], { ignoreErr: true }),
        deploy_branch: promisedGit(['config', 'deploy.deploybranch'], { ignoreErr: true }),
        src_branch: promisedGit(['config', 'deploy.srcbranch'], { ignoreErr: true })
    }).then((props) => {
        opts.name = props.name || pkg.name;
        opts.remote_name = props.remote || 'origin';
        opts.submodule_ref = props.submodule_ref ||
            `https://gerrit.wikimedia.org/r/mediawiki/services/${opts.name}`;
        opts.src_branch = props.src_branch || 'master';
        opts.deploy_branch = props.deploy_branch || 'master';
        opts.remote_branch = `${opts.remote_name}/${opts.deploy_branch}`;
        // we need to CHDIR into the deploy dir for subsequent operations
        process.chdir(opts.dir);
        return chainedPgit([
            // make sure we are on master
            ['checkout', 'master'],
            // fetch all possible updates
            ['fetch', '--all'],
            // work on a topic branch forked off of the target branch
            ['checkout', '-B', 'sync-repo', opts.remote_branch],
            // check if the submodule is present
            ['submodule', 'status']
       ]);
    }).then((list) => {
        if (list) {
            // the submodule is present
            // in submodule the remote is always called 'origin', so ignore opts.
            opts.submodule = list.split(' ')[1];
            // update it fully
            return promisedGit(['submodule', 'update', '--init'])
            .then(() => {
                process.chdir(`${opts.dir}/${opts.submodule}`);
                return chainedPgit([
                    // fetch new commits
                    ['fetch', 'origin'],
                    // inspect what has changed
                    ['diff', '--name-only', `origin/${opts.src_branch}`]
               ]).then((changes) => {
                    if (/package\.json/.test(changes)) {
                        // package.json has changed, so we need
                        // to rebuild the node_modules directory
                        opts.need_build = true;
                    }
                    // get the SHA1 of the latest commit on the src branch
                    return promisedGit(['rev-parse', '--short', `origin/${opts.src_branch}`]);
                }).then((shortSha1) => {
                    opts.commit_msg = `Update ${opts.name} to ${shortSha1}\n\n`;
                    // get a nice list of commits included in the change
                    return promisedGit(['log',
                        `..origin/${opts.src_branch}`,
                        '--oneline',
                        '--no-merges',
                        '--reverse',
                        '--color=never']);
                }).then((logs) => {
                    if (!logs && !opts.need_build) {
                        // no updates have happened, nothing to do here any more but clean up
                        // go back to the root dir
                        process.chdir(opts.dir);
                        // and get back to master
                        return promisedGit(['checkout', 'master'])
                        .then(() => {
                            console.log('The deploy repository is up to date already, exiting.');
                            process.exit(0);
                        });
                    } else if (logs) {
                        logs += '\n';
                    } else if (!logs) {
                        logs = '';
                    }
                    opts.commit_msg += `List of changes:\n${logs}`;
                    return promisedGit(['checkout', `origin/${opts.src_branch}`]);
                }).then(() => {
                    // go back to the root dir
                    process.chdir(opts.dir);
                    // add the submodule changes
                    return promisedGit(['add', opts.submodule]);
                });
            });
        } else {
            // no submodule, need to add it
            opts.submodule = 'src';
            opts.need_build = true;
            opts.commit_msg = `Initial import of ${opts.name}`;
            return promisedGit(['submodule',
                'add',
                opts.submodule_ref,
                opts.submodule]);
        }
    }).then(() => // make sure the package.json symlink is in place
        fs.symlinkAsync(`${opts.submodule}/package.json`, 'package.json')
    .catch(() => {}).then(() => promisedGit(['add', 'package.json']))).then(() => {
        if (!opts.need_build) {
            return;
        }
        // update the commit message
        if (!/^initial/i.test(opts.commit_msg)) {
            opts.commit_msg += 'xxxxxxx Update node module dependencies\n';
        }
        // a rebuild is needed, start by removing the existing modules
        return promisedGit(['rm', '-r', 'node_modules'], { ignoreErr: true })
        .then(() => promisedSpawn(['rm', '-rf', 'node_modules'],
            { capture: true, ignoreErr: true }))
        // start the container which builds the modules
        .then(() => startContainer(['-v', `${opts.dir}:/opt/service`, '-w', '/opt/service'], true))
        .then(() => {
            // remove unnecessary files
            let findAttr;
            if (os.type() === 'Darwin') {
                findAttr = [
                    'find',
                    '-E',
                    'node_modules/',
                    '-iregex',
                    '.*\\.git.*|.*\\.md|.*readme|.*licence',
                    '-exec', 'rm', '-rf', '{}', ';'
               ];
            } else {
                findAttr = [
                    'find',
                    'node_modules/',
                    '-regextype',
                    'posix-egrep',
                    '-iregex',
                    '(.*\\.git.*|.*\\.md|.*readme|.*licence)',
                    '-exec', 'rm', '-rf', '{}', ';'
               ];
            }
            return promisedSpawn(findAttr, { capture: true, ignoreErr: true });
        }).then(() => // add the built submodules
            promisedGit(['add', 'node_modules']));
    }).then(() => // commit the changes
        promisedGit(['commit', '-m', opts.commit_msg]))
        .then(() => {
            if (!opts.review) {
                console.log('\n\nChanges are sitting in the sync-repo branch in');
                console.log(`${opts.dir} with the commit:`);
                console.log(opts.commit_msg);
                return;
            }
            return chainedPgit([
                // send them for review
                ['review', '-R', opts.deploy_branch],
                // get back to master
                ['checkout', 'master'],
                // and reset the submodule pointer
                ['submodule', 'update', '--init']
           ], { capture: false }).then(() => {
                console.log('\n\nChanges sent to Gerrit for review!');
            });
        });
}
1335701
function initializeState(requester, updateParams) {
        var currentRequester = requester || "";
        _updateParams = updateParams;
        installerPath = path.resolve(updateDir, updateParams.installerName);
        postMessageToBrackets(MessageIds.NOTIFY_INITIALIZATION_COMPLETE, currentRequester);
    }
1085037
protected ActionCommand createUpdateCommand()
    {
        ActionCommand command = new ActionCommand(UPDATE_COMMAND_ID)
        {

            @Override
            protected void doExecuteCommand()
            {
                doUpdate();
            }
        };
        command.setSecurityControllerId(getId() + "." + UPDATE_COMMAND_ID);
        getApplicationConfig().commandConfigurer().configure(command);
        getDetailForm().addGuarded(command, FormGuard.LIKE_COMMITCOMMAND);
        return command;
    }
1128742
function(launchConfiguration, checkStatus) {
			var errorHandler = function (error) {
				// stop the progress spinner in the launch config dropdown trigger
				this.setStatus({
					error: error || true //if no error was passed in we still want to ensure that the error state is recorded
				});
			}.bind(this);
			
			if (launchConfiguration) {
				this._selectedLaunchConfiguration = launchConfiguration;
				this._setLaunchConfigurationsLabel(launchConfiguration);
				
				if (checkStatus) {
					this._displayStatusCheck(launchConfiguration);
					var startTime = Date.now();
					this._checkLaunchConfigurationStatus(launchConfiguration).then(function(_status) {
						var interval = Date.now() - startTime;
						mMetrics.logTiming("deployment", "check status (launch config)", interval, launchConfiguration.Type); //$NON-NLS-1$ //$NON-NLS-2$

						launchConfiguration.status = _status;
						this._updateLaunchConfiguration(launchConfiguration);
					}.bind(this), errorHandler);
				} else {
					// do not check the status, only set it in the UI if it is already in the launchConfiguration
					if (launchConfiguration.status) {
						this.setStatus(launchConfiguration.status);
					}
				}
			} else {
				this._stopStatusPolling(); //stop before clearing selected config
				this._selectedLaunchConfiguration = null;
				this._setLaunchConfigurationsLabel(null);
				this.setStatus({});
			}
			this._menuItemsCache = [];
		}
1204116
def deploy():
    

    init_tasks()

    if not has_hook("copy"):
        return report("No copy method has been defined")

    if not env.exists(paths.get_shared_path()):
        return report("You need to run setup before running deploy")

    run_hook("before_deploy")

    release_name = int(time.time()*1000)
    release_path = paths.get_releases_path(release_name)

    env.current_release = release_path

    try:
        run_hook("copy")
    except Exception as e:
        return report("Error occurred on copy. Aborting deploy", err=e)

    if not env.exists(paths.get_source_path(release_name)):
        return report("Source path not found '%s'" %
                      paths.get_source_path(release_name))

    try:
        run_hook("deploy")
    except Exception as e:
        message = "Error occurred on deploy, starting rollback..."

        logger.error(message)
        logger.error(e)

        run_task("rollback")
        return report("Error occurred on deploy")

    # Symlink current folder
    paths.symlink(paths.get_source_path(release_name),
                  paths.get_current_path())

    # Clean older releases
    if "max_releases" in env:
        cleanup_releases(int(env.max_releases))

    run_hook("after_deploy")

    if "public_path" in env:
        paths.symlink(paths.get_source_path(release_name), env.public_path)

    logger.info("Deploy complete")