Returns pre/post snapshots made by a given Salt jid

    Looks for 'salt_jid' entries into snapshots userdata which are created
    when 'snapper.run' is executed.
350572
def _get_jid_snapshots(jid, config='root'):
    '''
    
    '''
    jid_snapshots = [x for x in list_snapshots(config) if x['userdata'].get("salt_jid") == jid]
    pre_snapshot = [x for x in jid_snapshots if x['type'] == "pre"]
    post_snapshot = [x for x in jid_snapshots if x['type'] == "post"]

    if not pre_snapshot or not post_snapshot:
        raise CommandExecutionError("Jid '{0}' snapshots not found".format(jid))

    return (
        pre_snapshot[0]['id'],
        post_snapshot[0]['id']
    )
153097
@Nonnull
	@Override
	public RunnableFuture<SnapshotResult<OperatorStateHandle>> snapshot(
		long checkpointId,
		long timestamp,
		@Nonnull CheckpointStreamFactory streamFactory,
		@Nonnull CheckpointOptions checkpointOptions) throws Exception {

		long syncStartTime = System.currentTimeMillis();

		RunnableFuture<SnapshotResult<OperatorStateHandle>> snapshotRunner =
			snapshotStrategy.snapshot(checkpointId, timestamp, streamFactory, checkpointOptions);

		snapshotStrategy.logSyncCompleted(streamFactory, syncStartTime);
		return snapshotRunner;
	}
1052438
def get_jid(jid):
    '''
    
    '''
    serv = _get_serv(ret=None)
    ret = {}
    for minion, data in six.iteritems(serv.hgetall('ret:{0}'.format(jid))):
        if data:
            ret[minion] = salt.utils.json.loads(data)
    return ret
1234741
def save
      run_callbacks(:before_save)
      run_callbacks(:before_create) unless self.is_created

      existing_items = self.class.all
      if self.new_record?
        existing_items << self
      else # update existing record
        updated_item = existing_items.find { |item| item.id == self.id }
        return false unless updated_item
        updated_item.attributes = self.attributes
      end

      raw_data = existing_items ? existing_items.map { |item| item.persisted_attributes } : []
      self.class.write_contents(raw_data) if self.valid?

      run_callbacks(:after_create) unless self.is_created
      run_callbacks(:after_save)
      true
    rescue IOError
      false
    end
848343
def _run_runner(self):
        '''
        
        '''
        import salt.minion
        ret = {}
        low = {'fun': self.opts['fun']}
        try:
            # Allocate a jid
            async_pub = self._gen_async_pub()
            self.jid = async_pub['jid']

            fun_args = salt.utils.args.parse_input(
                    self.opts['arg'],
                    no_parse=self.opts.get('no_parse', []))

            verify_fun(self.functions, low['fun'])
            args, kwargs = salt.minion.load_args_and_kwargs(
                self.functions[low['fun']],
                fun_args)
            low['arg'] = args
            low['kwarg'] = kwargs

            if self.opts.get('eauth'):
                if 'token' in self.opts:
                    try:
                        with salt.utils.files.fopen(os.path.join(self.opts['cachedir'], '.root_key'), 'r') as fp_:
                            low['key'] = salt.utils.stringutils.to_unicode(fp_.readline())
                    except IOError:
                        low['token'] = self.opts['token']

                # If using eauth and a token hasn't already been loaded into
                # low, prompt the user to enter auth credentials
                if 'token' not in low and 'key' not in low and self.opts['eauth']:
                    # This is expensive. Don't do it unless we need to.
                    import salt.auth
                    resolver = salt.auth.Resolver(self.opts)
                    res = resolver.cli(self.opts['eauth'])
                    if self.opts['mktoken'] and res:
                        tok = resolver.token_cli(
                                self.opts['eauth'],
                                res
                                )
                        if tok:
                            low['token'] = tok.get('token', '')
                    if not res:
                        log.error('Authentication failed')
                        return ret
                    low.update(res)
                    low['eauth'] = self.opts['eauth']
            else:
                user = salt.utils.user.get_specific_user()

            if low['fun'] in ['state.orchestrate', 'state.orch', 'state.sls']:
                low['kwarg']['orchestration_jid'] = async_pub['jid']

            # Run the runner!
            if self.opts.get('async', False):
                if self.opts.get('eauth'):
                    async_pub = self.cmd_async(low)
                else:
                    async_pub = self.asynchronous(self.opts['fun'],
                                                  low,
                                                  user=user,
                                                  pub=async_pub)

                # by default: info will be not enough to be printed out !
                log.warning(
                    'Running in asynchronous mode. Results of this execution may '
                    'be collected by attaching to the master event bus or '
                    'by examing the master job cache, if configured. '
                    'This execution is running under tag %s', async_pub['tag']
                )
                return async_pub['jid']  # return the jid

            # otherwise run it in the main process
            if self.opts.get('eauth'):
                ret = self.cmd_sync(low)
                if isinstance(ret, dict) and set(ret) == {'data', 'outputter'}:
                    outputter = ret['outputter']
                    ret = ret['data']
                else:
                    outputter = None
                display_output(ret, outputter, self.opts)
            else:
                ret = self._proc_function(self.opts['fun'],
                                          low,
                                          user,
                                          async_pub['tag'],
                                          async_pub['jid'],
                                          daemonize=False)
        except salt.exceptions.SaltException as exc:
            evt = salt.utils.event.get_event('master', opts=self.opts)
            evt.fire_event({'success': False,
                            'return': '{0}'.format(exc),
                            'retcode': 254,
                            'fun': self.opts['fun'],
                            'fun_args': fun_args,
                            'jid': self.jid},
                           tag='salt/run/{0}/ret'.format(self.jid))
            # Attempt to grab documentation
            if 'fun' in low:
                ret = self.get_docs('{0}*'.format(low['fun']))
            else:
                ret = None

            # If we didn't get docs returned then
            # return the `not availble` message.
            if not ret:
                ret = '{0}'.format(exc)
            if not self.opts.get('quiet', False):
                display_output(ret, 'nested', self.opts)
        else:
            # If we don't have any values in ret by now, that's a problem.
            # Otherwise, we shouldn't be overwriting the retcode.
            if not ret:
                ret = {
                    'retcode': salt.defaults.exitcodes.EX_SOFTWARE,
                }
        log.debug('Runner return: %s', ret)

        return ret
1203005
def _prerun(self):
        
        self.check_required_params()
        self._set_status("RUNNING")
        logger.debug(
            "{}.PreRun: {}[{}]: running...".format(
                self.__class__.__name__, self.__class__.path, self.uuid
            ),
            extra=dict(
                kmsg=Message(
                    self.uuid, entrypoint=self.__class__.path,
                    params=self.params
                ).dump()
            )
        )
        return self.prerun()
341924
def snapshot(self) -> Tuple[Hash32, UUID]:
        
        return self.state_root, self._account_db.record()
650959
def _check_pub_data(self, pub_data, listen=True):
        '''
        
        '''
        if pub_data == '':
            # Failed to authenticate, this could be a bunch of things
            raise EauthAuthenticationError(
                'Failed to authenticate! This is most likely because this '
                'user is not permitted to execute commands, but there is a '
                'small possibility that a disk error occurred (check '
                'disk/inode usage).'
            )

        # Failed to connect to the master and send the pub
        if 'error' in pub_data:
            print(pub_data['error'])
            log.debug('_check_pub_data() error: %s', pub_data['error'])
            return {}
        elif 'jid' not in pub_data:
            return {}
        if pub_data['jid'] == '0':
            print('Failed to connect to the Master, '
                  'is the Salt Master running?')
            return {}

        # If we order masters (via a syndic), don't short circuit if no minions
        # are found
        if not self.opts.get('order_masters'):
            # Check for no minions
            if not pub_data['minions']:
                print('No minions matched the target. '
                      'No command was sent, no jid was assigned.')
                return {}

        # don't install event subscription listeners when the request is asynchronous
        # and doesn't care. this is important as it will create event leaks otherwise
        if not listen:
            return pub_data

        if self.opts.get('order_masters'):
            self.event.subscribe('syndic/.*/{0}'.format(pub_data['jid']), 'regex')

        self.event.subscribe('salt/job/{0}'.format(pub_data['jid']))

        return pub_data
1179946
def market_snapshot(self, prefix=False):
        
        return self.get_stock_data(self.stock_list, prefix=prefix)
327296
@Override
	public void snapshotState(FunctionSnapshotContext context) throws Exception {
		Preconditions.checkState(this.checkpointedState != null,
			"The " + getClass().getSimpleName() + " has not been properly initialized.");

		if (LOG.isDebugEnabled()) {
			LOG.debug("{} checkpointing: Messages: {}, checkpoint id: {}, timestamp: {}",
				idsForCurrentCheckpoint, context.getCheckpointId(), context.getCheckpointTimestamp());
		}

		pendingCheckpoints.addLast(new Tuple2<>(context.getCheckpointId(), idsForCurrentCheckpoint));
		idsForCurrentCheckpoint = new HashSet<>(64);

		this.checkpointedState.clear();
		this.checkpointedState.add(SerializedCheckpointData.fromDeque(pendingCheckpoints, idSerializer));
	}
1239163
def undo_jid(jid, config='root'):
    '''
    
    '''
    pre_snapshot, post_snapshot = _get_jid_snapshots(jid, config=config)
    return undo(config, num_pre=pre_snapshot, num_post=post_snapshot)
299409
def _snapshot(self) -> Dict[str, Any]:
        
        try:
            return {name: item._snapshot for name, item in self._nested_items.items()}
        except Exception as e:
            raise SnapshotError('Error while creating snapshot for {}'.format(self._name)) from e
388578
def create_snapshot(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The create_snapshot function must be called with -f or --function.'
        )

    if not kwargs or 'name' not in kwargs:
        log.error(
            'A name must be specified when creating a snapshot.'
        )
        return False

    if 'disk_name' not in kwargs:
        log.error(
            'A disk_name must be specified when creating a snapshot.'
        )
        return False

    conn = get_conn()

    name = kwargs.get('name')
    disk_name = kwargs.get('disk_name')

    try:
        disk = conn.ex_get_volume(disk_name)
    except ResourceNotFoundError as exc:
        log.error(
            'Disk %s was not found. Exception was: %s',
            disk_name, exc, exc_info_on_loglevel=logging.DEBUG
        )
        return False

    __utils__['cloud.fire_event'](
        'event',
        'create snapshot',
        'salt/cloud/snapshot/creating',
        args={
            'name': name,
            'disk_name': disk_name,
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    snapshot = conn.create_volume_snapshot(disk, name)

    __utils__['cloud.fire_event'](
        'event',
        'created snapshot',
        'salt/cloud/snapshot/created',
        args={
            'name': name,
            'disk_name': disk_name,
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    return _expand_item(snapshot)
665552
def snapshot_created(name, ami_name, instance_name, wait_until_available=True, wait_timeout_seconds=300, **kwargs):
    '''
    
    '''
    ret = {'name': name,
           'result': True,
           'comment': '',
           'changes': {}
           }

    if not __salt__['boto_ec2.create_image'](ami_name=ami_name, instance_name=instance_name, **kwargs):
        ret['comment'] = 'Failed to create new AMI {ami_name}'.format(ami_name=ami_name)
        ret['result'] = False
        return ret

    ret['comment'] = 'Created new AMI {ami_name}'.format(ami_name=ami_name)
    ret['changes']['new'] = {ami_name: ami_name}
    if not wait_until_available:
        return ret

    starttime = time()
    while True:
        images = __salt__['boto_ec2.find_images'](ami_name=ami_name, return_objs=True, **kwargs)
        if images and images[0].state == 'available':
            break
        if time() - starttime > wait_timeout_seconds:
            if images:
                ret['comment'] = 'AMI still in state {state} after timeout'.format(state=images[0].state)
            else:
                ret['comment'] = 'AMI with name {ami_name} not found after timeout.'.format(ami_name=ami_name)
            ret['result'] = False
            return ret
        sleep(5)

    return ret
233994
def get_load(jid):
    '''
    
    '''
    with _get_serv(ret=None, commit=True) as cur:

        sql = '''SELECT `load` FROM `jids` WHERE `jid` = %s;'''
        cur.execute(sql, (jid,))
        data = cur.fetchone()
        if data:
            return salt.utils.json.loads(data[0])
        return {}
1118605
def get_jid(jid):
    '''
    
    '''
    log.debug('sdstack_etcd returner <get_jid> called jid: %s', jid)
    ret = {}
    client, path = _get_conn(__opts__)
    items = client.get('/'.join((path, 'jobs', jid)))
    for item in items.children:
        if str(item.key).endswith('.load.p'):
            continue
        comps = str(item.key).split('/')
        data = client.get('/'.join((path, 'jobs', jid, comps[-1], 'return'))).value
        ret[comps[-1]] = {'return': salt.utils.json.loads(data)}
    return ret
603093
def snapshot(cls, cluster_id_label, s3_location, backup_type):
        
        conn = Qubole.agent(version=Cluster.api_version)
        parameters = {}
        parameters['s3_location'] = s3_location
        if backup_type:
            parameters['backup_type'] = backup_type
        return conn.post(cls.element_path(cluster_id_label) + "/snapshots", data=parameters)