Handles the creating or updating of a stack in CloudFormation.

        Also makes sure that we don't try to create or update a stack while
        it is already updating or creating.
561
def _launch_stack(self, stack, **kwargs):
        
        old_status = kwargs.get("status")
        wait_time = 0 if old_status is PENDING else STACK_POLL_TIME
        if self.cancel.wait(wait_time):
            return INTERRUPTED

        if not should_submit(stack):
            return NotSubmittedStatus()

        provider = self.build_provider(stack)

        try:
            provider_stack = provider.get_stack(stack.fqn)
        except StackDoesNotExist:
            provider_stack = None

        if provider_stack and not should_update(stack):
            stack.set_outputs(
                self.provider.get_output_dict(provider_stack))
            return NotUpdatedStatus()

        recreate = False
        if provider_stack and old_status == SUBMITTED:
            logger.debug(
                "Stack %s provider status: %s",
                stack.fqn,
                provider.get_stack_status(provider_stack),
            )

            if provider.is_stack_rolling_back(provider_stack):
                if 'rolling back' in old_status.reason:
                    return old_status

                logger.debug("Stack %s entered a roll back", stack.fqn)
                if 'updating' in old_status.reason:
                    reason = 'rolling back update'
                else:
                    reason = 'rolling back new stack'

                return SubmittedStatus(reason)
            elif provider.is_stack_in_progress(provider_stack):
                logger.debug("Stack %s in progress.", stack.fqn)
                return old_status
            elif provider.is_stack_destroyed(provider_stack):
                logger.debug("Stack %s finished deleting", stack.fqn)
                recreate = True
                # Continue with creation afterwards
            # Failure must be checked *before* completion, as both will be true
            # when completing a rollback, and we don't want to consider it as
            # a successful update.
            elif provider.is_stack_failed(provider_stack):
                reason = old_status.reason
                if 'rolling' in reason:
                    reason = reason.replace('rolling', 'rolled')
                status_reason = provider.get_rollback_status_reason(stack.fqn)
                logger.info(
                    "%s Stack Roll Back Reason: " + status_reason, stack.fqn)
                return FailedStatus(reason)

            elif provider.is_stack_completed(provider_stack):
                stack.set_outputs(
                    provider.get_output_dict(provider_stack))
                return CompleteStatus(old_status.reason)
            else:
                return old_status

        logger.debug("Resolving stack %s", stack.fqn)
        stack.resolve(self.context, self.provider)

        logger.debug("Launching stack %s now.", stack.fqn)
        template = self._template(stack.blueprint)
        stack_policy = self._stack_policy(stack)
        tags = build_stack_tags(stack)
        parameters = self.build_parameters(stack, provider_stack)
        force_change_set = stack.blueprint.requires_change_set

        if recreate:
            logger.debug("Re-creating stack: %s", stack.fqn)
            provider.create_stack(stack.fqn, template, parameters,
                                  tags, stack_policy=stack_policy)
            return SubmittedStatus("re-creating stack")
        elif not provider_stack:
            logger.debug("Creating new stack: %s", stack.fqn)
            provider.create_stack(stack.fqn, template, parameters, tags,
                                  force_change_set,
                                  stack_policy=stack_policy)
            return SubmittedStatus("creating new stack")

        try:
            wait = stack.in_progress_behavior == "wait"
            if wait and provider.is_stack_in_progress(provider_stack):
                return WAITING
            if provider.prepare_stack_for_update(provider_stack, tags):
                existing_params = provider_stack.get('Parameters', [])
                provider.update_stack(
                    stack.fqn,
                    template,
                    existing_params,
                    parameters,
                    tags,
                    force_interactive=stack.protected,
                    force_change_set=force_change_set,
                    stack_policy=stack_policy,
                )

                logger.debug("Updating existing stack: %s", stack.fqn)
                return SubmittedStatus("updating existing stack")
            else:
                return SubmittedStatus("destroying stack for re-creation")
        except CancelExecution:
            stack.set_outputs(provider.get_output_dict(provider_stack))
            return SkippedStatus(reason="canceled execution")
        except StackDidNotChange:
            stack.set_outputs(provider.get_output_dict(provider_stack))
            return DidNotChangeStatus()
907701
function runMiddlewareStack(stack, req, res, callback) {
  let index = 0;
  // the middleware layer handover callback
  function next(err) {
    // get next middleware callback from stack
    const handle = stack[index++];
    // if no more layers in stack, invoke done callback and exit recursion
    if (!handle) {
      callback(err);
      return;
    }
    let error = err;
    // call the middleware handler
    try {
      if (err && handle.length === 4) {
        // there is an error and it's an error-handling middleware
        handle(err, req, res, next);
        return;
      } else if (!err && handle.length < 4) {
        // no error and it's a request-handling middleware
        handle(req, res, next);
        return;
      }
    } catch (e) {
      // if new error thrown, replace the error
      error = e;
    }
    // otherwise skip layer
    next(error);
  }
  // start going through middleware stack
  next();
}
1082020
function _Error() {
    this.populate.apply(this, arguments);
    var stack = (new Error(this.message)).stack;
    debug('stack ', stack);
}
1045790
public void handleLoadInstruction(LoadInstruction obj) {
        int numProduced = obj.produceStack(cpg);
        if (numProduced == Const.UNPREDICTABLE) {
            throw new InvalidBytecodeException("Unpredictable stack production");
        }

        int index = obj.getIndex() + numProduced;

        // Load values from locals in reverse order.
        // This restores them to the stack in a way consistent
        // with visitStoreInstruction().
        while (numProduced-- > 0) {
            Value value = frame.getValue(--index);
            frame.pushValue(value);
        }
    }
913184
def run
      unless stack_exists?(@stack_name)
        puts "The stack #{@stack_name.color(:green)} does not exist."
        return
      end

      resp = cloudformation.describe_stacks(stack_name: @stack_name)
      stack = resp.stacks.first

      puts "The current status for the stack #{@stack_name.color(:green)} is #{stack.stack_status.color(:green)}"

      status_poller = Stack::Status.new(@stack_name)

      if stack.stack_status =~ /_IN_PROGRESS$/
        puts "Stack events (tailing):"
        # tail all events until done
        status_poller.hide_time_took = true
        status_poller.wait
      else
        puts "Stack events:"
        # show the last events that was user initiated
        status_poller.refresh_events
        status_poller.show_events(true)
      end
    end
1148121
function ErrorWithCaller(caller) {
    Error.prepareStackTrace = function justStoreStackStace(error, frames) {
        error.__StackStace = frames;
        return '';
    };
    Error.captureStackTrace(this, caller);
    this.stack;  // jshint ignore:line
    delete Error.prepareStackTrace;
}
40235
def delete_change_set(awsclient, change_set_name, stack_name):
    
    client = awsclient.get_client('cloudformation')

    response = client.delete_change_set(
        ChangeSetName=change_set_name,
        StackName=stack_name)
444214
@TaskAction
  public void checkCloudSdkAction()
      throws CloudSdkNotFoundException, CloudSdkVersionFileException, CloudSdkOutOfDateException,
          AppEngineJavaComponentsNotInstalledException {
    // These properties are only set by AppEngineCorePluginConfiguration if the correct config
    // params are set in the tools extension.
    if (Strings.isNullOrEmpty(version) || cloudSdk == null) {
      throw new GradleException(
          "Cloud SDK home path and version must be configured in order to run this task.");
    }

    if (!version.equals(cloudSdk.getVersion().toString())) {
      throw new GradleException(
          "Specified Cloud SDK version ("
              + version
              + ") does not match installed version ("
              + cloudSdk.getVersion()
              + ").");
    }

    cloudSdk.validateCloudSdk();
    if (requiresAppEngineJava) {
      cloudSdk.validateAppEngineJavaComponents();
    }
  }
1237588
public function main()
    {
        $this->validate();

        $cloudFormation = $this->getService();

        $stackProperties = [
            'StackName' => $this->getName(),
        ];

        $killed = false;
        $counter = 0;

        while (!$killed && $counter <= $this->getTimeOut()) {
            try {
                $cloudFormation->describeStacks($stackProperties);
            } catch (\Exception $e) {
                $killed = true;
            }

            sleep(1);

            $counter++;
        }
    }
764003
def list_stacks(awsclient):
    
    client_cf = awsclient.get_client('cloudformation')
    response = client_cf.list_stacks(
        StackStatusFilter=[
            'CREATE_IN_PROGRESS', 'CREATE_COMPLETE', 'ROLLBACK_IN_PROGRESS',
            'ROLLBACK_COMPLETE', 'DELETE_IN_PROGRESS', 'DELETE_FAILED',
            'UPDATE_IN_PROGRESS', 'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS',
            'UPDATE_COMPLETE', 'UPDATE_ROLLBACK_IN_PROGRESS',
            'UPDATE_ROLLBACK_FAILED',
            'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',
            'UPDATE_ROLLBACK_COMPLETE',
        ]
    )
    result = {}
    stack_sum = 0
    for summary in response['StackSummaries']:
        result['StackName'] = summary["StackName"]
        result['CreationTime'] = summary['CreationTime']
        result['StackStatus'] = summary['StackStatus']
        print(json2table(result))
        stack_sum += 1
    print('listed %s stacks' % str(stack_sum))
1090319
def do_delete_stack(self,args):
        """"""
        parser = CommandArgumentParser("delete_stack")
        parser.add_argument(dest='stack',help='stack index or name');
        args = vars(parser.parse_args(args))

        try:
            index = int(args['stack'])
            if self.stackList == None:
                self.do_stacks('-s')
            stack = AwsConnectionFactory.instance.getCfResource().Stack(self.stackList[index]['StackName'])
        except ValueError:
            stack = AwsConnectionFactory.instance.getCfResource().Stack(args['stack'])

        print "Here are the details of the stack you are about to delete:"
        print "Stack.name: {}".format(stack.name)
        print "Stack.stack_id: {}".format(stack.stack_id)
        print "Stack.creation_time: {}".format(stack.creation_time)
        confirmation = raw_input("If you are sure, enter the Stack.name here: ")
        if stack.name == confirmation:
            stack.delete()
            print "Stack deletion in progress"
        else:
            print "Stack deletion canceled: '{}' != '{}'".format(stack.name,confirmation)
1001044
private void handleCreate(TableInfo tableInfo, KsDef ksDef) throws Exception
    {
        if (containsCompositeKey(tableInfo))
        {
            validateCompoundKey(tableInfo);
            // First drop existing column family.
            dropTableUsingCql(tableInfo);
        }
        else
        {
            onDrop(tableInfo);
        }
        createOrUpdateColumnFamily(tableInfo, ksDef);
    }
1100765
private void updateFromStack(Stack stack) {
    long startTime = System.currentTimeMillis();

    // Update LocalPeer
    Peer sLocalPeer = stack.getMetaData().getLocalPeer();

    localPeer.setUri(sLocalPeer.getUri().toString());
    for (InetAddress ipAddress : sLocalPeer.getIPAddresses()) {
      localPeer.addIpAddress(ipAddress.getHostAddress());
    }
    localPeer.setRealm(sLocalPeer.getRealmName());
    localPeer.setVendorId(sLocalPeer.getVendorId());
    localPeer.setProductName(sLocalPeer.getProductName());
    localPeer.setFirmwareRev(sLocalPeer.getFirmware());
    for (org.jdiameter.api.ApplicationId appId : sLocalPeer.getCommonApplications()) {
      if (appId.getAuthAppId() != org.jdiameter.api.ApplicationId.UNDEFINED_VALUE) {
        localPeer.addDefaultApplication(ApplicationIdJMX.createAuthApplicationId(appId.getVendorId(), appId.getAuthAppId()));
      }
      else {
        localPeer.addDefaultApplication(ApplicationIdJMX.createAcctApplicationId(appId.getVendorId(), appId.getAcctAppId()));
      }
    }
    HashMap<String, DiameterStatistic> lpStats = new HashMap<String, DiameterStatistic>();
    for (StatisticRecord stat : ((IPeer) sLocalPeer).getStatistic().getRecords()) {
      lpStats.put(stat.getName(), new DiameterStatistic(stat.getName(), stat.getDescription(), stat.toString()));
    }
    localPeer.setStatistics(lpStats);

    MutableConfiguration config = (MutableConfiguration) stack.getMetaData().getConfiguration();

    // Update Parameters
    this.parameters = new ParametersImpl(config);

    // Update Network ...
    // ... Peers (config)
    for (Configuration curPeer : config.getChildren(PeerTable.ordinal())) {
      String name = curPeer.getStringValue(PeerName.ordinal(), "");
      Boolean attemptConnect = curPeer.getBooleanValue(PeerAttemptConnection.ordinal(), false);
      Integer rating = curPeer.getIntValue(PeerRating.ordinal(), 0);
      String ip = curPeer.getStringValue(PeerIp.ordinal(), null);
      String portRange = curPeer.getStringValue(PeerLocalPortRange.ordinal(), "");
      Integer portRangeLow = null;
      Integer portRangeHigh = null;
      if (portRange != null && !portRange.equals("")) {
        String[] rng = portRange.trim().split("-");
        portRangeLow = Integer.parseInt(rng[0]);
        portRangeHigh = Integer.parseInt(rng[1]);
      }
      String securityRef = curPeer.getStringValue(SecurityRef.ordinal(), "");
      network.addPeer(new NetworkPeerImpl(name, attemptConnect, rating, ip, portRangeLow, portRangeHigh, securityRef));
    }

    // ... More Peers (mutable)
    try {
      MutablePeerTable peerTable;
      peerTable = stack.unwrap(MutablePeerTable.class);
      //Peer p = n.addPeer("aaa://127.0.0.1:13868", "mobicents.org", true);
      for (Peer peer : peerTable.getPeerTable()) {
        PeerImpl p = (PeerImpl) peer;
        NetworkPeerImpl nPeer = new NetworkPeerImpl(p.getUri().toString(), p.isAttemptConnection(), p.getRating(), null, null, null, null);
        HashMap<String, DiameterStatistic> npStats = new HashMap<String, DiameterStatistic>();
        for (StatisticRecord stat : p.getStatistic().getRecords()) {
          npStats.put(stat.getName(), new DiameterStatistic(stat.getName(), stat.getDescription(), stat.toString()));
        }
        nPeer.setStatistics(npStats);
        network.addPeer(nPeer);
      }
    }
    catch (InternalException e) {
      logger.error("Failed to update Diameter Configuration from Stack Mutable Peer Table", e);
    }

    // ... Realms (configuration)
    /*for(Configuration realmTable : config.getChildren(RealmTable.ordinal())) {
      for(Configuration curRealm : realmTable.getChildren(RealmEntry.ordinal())) {
        String name = curRealm.getStringValue(RealmName.ordinal(), "");
        String hosts = curRealm.getStringValue(RealmHosts.ordinal(), "localhost");
        ArrayList<String> peers = new ArrayList<String>();
        for(String peer : hosts.split(",")) {
          peers.add(peer.trim());
        }
        String localAction = curRealm.getStringValue(RealmLocalAction.ordinal(), "LOCAL");
        Boolean dynamic = curRealm.getBooleanValue(RealmEntryIsDynamic.ordinal(), false);
        Long expTime = curRealm.getLongValue(RealmEntryExpTime.ordinal(), 0);
        Configuration[] sAppIds = curRealm.getChildren(ApplicationId.ordinal());
        ArrayList<ApplicationIdJMX> appIds = new ArrayList<ApplicationIdJMX>();
        for(Configuration appId : sAppIds) {
          Long acctAppId = appId.getLongValue(AcctApplId.ordinal(), 0);
          Long authAppId = appId.getLongValue(AuthApplId.ordinal(), 0);
          Long vendorId = appId.getLongValue(VendorId.ordinal(), 0);
          if(authAppId != 0) {
            appIds.add(ApplicationIdJMX.createAuthApplicationId(vendorId, authAppId));
          }
          else if (acctAppId != 0){
            appIds.add(ApplicationIdJMX.createAcctApplicationId(vendorId, acctAppId));
          }
        }
        network.addRealm(new RealmImpl(appIds, name, peers, localAction, dynamic, expTime));
      }
    }
     */
    // ... Realms (mutable)
    try {
      MutablePeerTableImpl mpt = (MutablePeerTableImpl) stack.unwrap(PeerTable.class);
      for (org.jdiameter.api.Realm realm : mpt.getAllRealms()) {
        IRealm irealm = null;
        if (realm instanceof IRealm) {
          irealm = (IRealm) realm;
        }
        ArrayList<ApplicationIdJMX> x = new ArrayList<ApplicationIdJMX>();
        x.add(ApplicationIdJMX.fromApplicationId(realm.getApplicationId()));
        network.addRealm(new RealmImpl(x, realm.getName(), new ArrayList<String>(Arrays.asList(((IRealm) realm).getPeerNames())),
            realm.getLocalAction().toString(), irealm != null ? irealm.getAgentConfiguration() : null, realm.isDynamic(), realm.getExpirationTime()));
      }
    }
    catch (Exception e) {
      logger.error("Failed to update Diameter Configuration from Stack Mutable Peer Table", e);
    }

    long endTime = System.currentTimeMillis();

    logger.debug("Info gathered in {}ms", (endTime - startTime));
  }
777592
def _save_or_update(self):
        
        with self._resource_lock:
            if not self._config or not self._config._storage_path:
                raise Exception("self._config._storage path is undefined")
            if not self._config._base_name:
                raise Exception("self._config._base_name is undefined")
            if not os.path.exists(self._config._storage_path):
                os.makedirs(self._config._storage_path)
            path = self._get_cloud_provider_storage_path()
            with open(path, 'wb') as storage:
                pickle.dump(self._config, storage, pickle.HIGHEST_PROTOCOL)
                pickle.dump(self._subscriptions, storage,
                            pickle.HIGHEST_PROTOCOL)
1218224
function (clt_name, op, err, onFail, is_exception) {

	var msg = 'DB ' + op + ' error for [' + clt_name + ']';
	LOG.error(msg, 'SR.DB');
	LOG.error(err, 'SR.DB');
	if (typeof err.stack !== 'undefined') {
		LOG.error(err.stack, 'SR.DB');
		msg += ('\n\n' + err.stack);
	}
	UTIL.safeCall(onFail, err);

	if (is_exception) {
		return;
	}

	// notify project admin if it's not code exception
	// NOTE: only project admins are notified
	UTIL.notifyAdmin(
		'[SR DB error: ' + clt_name + ']',
		msg
	);
}
1250615
def refresh_stack(self):
        
        self.stack, _ = self.compute_stack(self.fullstack)
        # find the current frame in the new stack
        for i, (frame, _) in enumerate(self.stack):
            if frame is self.curframe:
                self.curindex = i
                break
        else:
            self.curindex = len(self.stack)-1
            self.curframe = self.stack[-1][0]
            self.print_current_stack_entry()
1345933
def wait_for_stack_state(wait_target, past_tense_verb)
      result = true

      stack_id = get_stack(@name).stack_id

      events = StackEventsPoller.new(cf_client, stack_id)
      events.show_only_errors unless @config.show_all_stack_events

      @ilog.start_threaded "Waiting for #{stack_name} to be successfully #{past_tense_verb}." do |s|
        begin
          cf_client.wait_until(wait_target, stack_name: stack_id) do |w|
            w.delay = 10
            w.max_attempts = 360 # 60 minutes.
            w.before_wait do |attempt, resp|
              begin
                events.latest_events.each { |e| @ilog.error(format_event(e)) }
                # rubocop:disable Lint/HandleExceptions
              rescue Aws::CloudFormation::Errors::ValidationError
                # Do nothing.  The above event logging block may result in
                # a ValidationError while waiting for a stack to delete.
              end
              # rubocop:enable Lint/HandleExceptions

              if attempt == w.max_attempts - 1
                s.failure "#{stack_name} was not #{past_tense_verb} after 30 minutes."
                result = false

                # We don't want the interactive logger to catch an exception.
                throw :success
              end
              s.continue "Waiting for CloudFormation Stack to be successfully #{past_tense_verb}, current status '#{resp.stacks.first.stack_status}'." # rubocop:disable LineLength
            end
          end

          s.success "#{stack_name} successfully #{past_tense_verb}." if result
        rescue Aws::Waiters::Errors::FailureStateError
          result = false
          s.failure "#{stack_name} failed to update."
        end
      end

      result
    end