Save the current in-memory rules to disk

    CLI Example:

    .. code-block:: bash

        salt '*' iptables.save /etc/sysconfig/iptables

        IPv6:
        salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
321655
def save(filename=None, family='ipv4'):
    '''
    
    '''
    if _conf() and not filename:
        filename = _conf(family)

    log.debug('Saving rules to %s', filename)

    parent_dir = os.path.dirname(filename)
    if not os.path.isdir(parent_dir):
        os.makedirs(parent_dir)
    cmd = '{0}-save'.format(_iptables_cmd(family))
    ipt = __salt__['cmd.run'](cmd)

    # regex out the output if configured with filters
    if _conf_save_filters():
        ipt = _regex_iptables_save(ipt)

    out = __salt__['file.write'](filename, ipt)
    return out
1227778
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'):
    '''
    
    '''
    if _conf() and not conf_file and not in_mem:
        conf_file = _conf(family)

    rules = ''
    if conf_file:
        with salt.utils.files.fopen(conf_file, 'r') as ifile:
            rules = ifile.read()
    elif in_mem:
        cmd = '{0}-save' . format(_iptables_cmd(family))
        rules = __salt__['cmd.run'](cmd)
    else:
        raise SaltException('A file was not found to parse')

    ret = {}
    table = ''
    parser = _parser()
    for line in rules.splitlines():
        line = salt.utils.stringutils.to_unicode(line)
        if line.startswith('*'):
            table = line.replace('*', '')
            ret[table] = {}
        elif line.startswith(':'):
            comps = line.split()
            chain = comps[0].replace(':', '')
            ret[table][chain] = {}
            ret[table][chain]['policy'] = comps[1]
            counters = comps[2].replace('[', '').replace(']', '')
            (pcount, bcount) = counters.split(':')
            ret[table][chain]['packet count'] = pcount
            ret[table][chain]['byte count'] = bcount
            ret[table][chain]['rules'] = []
            ret[table][chain]['rules_comment'] = {}
        elif line.startswith('-A'):
            args = salt.utils.args.shlex_split(line)
            index = 0
            while index + 1 < len(args):
                swap = args[index] == '!' and args[index + 1].startswith('-')
                if swap:
                    args[index], args[index + 1] = args[index + 1], args[index]
                if args[index].startswith('-'):
                    index += 1
                    if args[index].startswith('-') or (args[index] == '!' and
                                                       not swap):
                        args.insert(index, '')
                    else:
                        while (index + 1 < len(args) and
                               args[index + 1] != '!' and
                               not args[index + 1].startswith('-')):
                            args[index] += ' {0}'.format(args.pop(index + 1))
                index += 1
            if args[-1].startswith('-'):
                args.append('')
            parsed_args = []
            opts, _ = parser.parse_known_args(args)
            parsed_args = vars(opts)
            ret_args = {}
            chain = parsed_args['append']
            for arg in parsed_args:
                if parsed_args[arg] and arg is not 'append':
                    ret_args[arg] = parsed_args[arg]
            if parsed_args['comment'] is not None:
                comment = parsed_args['comment'][0].strip('"')
                ret[table][chain[0]]['rules_comment'][comment] = ret_args
            ret[table][chain[0]]['rules'].append(ret_args)
    return ret
404126
def persist(name, value, config='/etc/sysctl.conf'):
    '''
    
    '''
    nlines = []
    edited = False
    value = six.text_type(value)

    with salt.utils.files.fopen(config, 'r') as ifile:
        for line in ifile:
            line = salt.utils.stringutils.to_unicode(line).rstrip('\n')
            if not line.startswith('{0}='.format(name)):
                nlines.append(line)
                continue
            else:
                key, rest = line.split('=', 1)
                if rest.startswith('"'):
                    _, rest_v, rest = rest.split('"', 2)
                elif rest.startswith('\''):
                    _, rest_v, rest = rest.split('\'', 2)
                else:
                    rest_v = rest.split()[0]
                    rest = rest[len(rest_v):]
                if rest_v == value:
                    return 'Already set'
                new_line = _formatfor(key, value, config, rest)
                nlines.append(new_line)
                edited = True
    if not edited:
        nlines.append("{0}\n".format(_formatfor(name, value, config)))
    with salt.utils.files.fopen(config, 'w+') as ofile:
        nlines = [salt.utils.stringutils.to_str(_l) + '\n' for _l in nlines]
        ofile.writelines(nlines)
    if config != '/boot/loader.conf':
        assign(name, value)
    return 'Updated'
978882
def persist(name, value, config='/etc/sysctl.conf'):
    '''
    
    '''
    nlines = []
    edited = False
    value = six.text_type(value)

    # create /etc/sysctl.conf if not present
    if not os.path.isfile(config):
        try:
            with salt.utils.files.fopen(config, 'w+'):
                pass
        except (IOError, OSError):
            msg = 'Could not create {0}'
            raise CommandExecutionError(msg.format(config))

    with salt.utils.files.fopen(config, 'r') as ifile:
        for line in ifile:
            line = salt.utils.stringutils.to_unicode(line)
            m = re.match(r'{0}(\??=)'.format(name), line)
            if not m:
                nlines.append(line)
                continue
            else:
                key, rest = line.split('=', 1)
                if rest.startswith('"'):
                    _, rest_v, rest = rest.split('"', 2)
                elif rest.startswith('\''):
                    _, rest_v, rest = rest.split('\'', 2)
                else:
                    rest_v = rest.split()[0]
                    rest = rest[len(rest_v):]
                if rest_v == value:
                    return 'Already set'
                new_line = '{0}{1}{2}{3}'.format(name, m.group(1), value, rest)
                nlines.append(new_line)
                edited = True

    if not edited:
        newline = '{0}={1}'.format(name, value)
        nlines.append("{0}\n".format(newline))

    with salt.utils.files.fopen(config, 'wb') as ofile:
        ofile.writelines(
            salt.utils.data.encode(nlines)
        )

    assign(name, value)

    return 'Updated'
1319599
def export(name, path, replace=False):
    '''
    

    '''
    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': ''}

    zones = __salt__['zoneadm.list'](installed=True, configured=True)
    if name in zones:
        ## zone exists
        if __opts__['test']:
            ## pretend we did the correct thing
            ret['result'] = True
            ret['comment'] = 'Zone configartion for {0} exported to {1}'.format(
                name,
                path,
            )
            ret['changes'][name] = 'exported'
            if __salt__['file.file_exists'](path) and not replace:
                ret['result'] = False
                ret['changes'] = {}
                ret['comment'] = 'File {0} exists, zone configuration for {1} not exported.'.format(
                    path,
                    name,
                )
        else:
            ## export and update file
            cfg_tmp = salt.utils.files.mkstemp()
            __salt__['zonecfg.export'](name, cfg_tmp)
            if not __salt__['file.file_exists'](path):
                ## move cfg_tmp to path
                try:
                    __salt__['file.move'](cfg_tmp, path)
                except CommandExecutionError:
                    if __salt__['file.file_exists'](cfg_tmp):
                        __salt__['file.remove'](cfg_tmp)
                    ret['result'] = False
                    ret['comment'] = 'Unable to export zone configuration for {0} to {1}!'.format(
                        name,
                        path,
                    )
                else:
                    ret['result'] = True
                    ret['comment'] = 'Zone configuration for {0} was exported to {1}.'.format(
                        name,
                        path,
                    )
                    ret['changes'][name] = 'exported'
            else:
                cfg_diff = __salt__['file.get_diff'](path, cfg_tmp)
                if not cfg_diff:
                    ret['result'] = True
                    ret['comment'] = 'Zone configuration for {0} was already exported to {1}.'.format(
                        name,
                        path
                    )
                    if __salt__['file.file_exists'](cfg_tmp):
                        __salt__['file.remove'](cfg_tmp)
                else:
                    if replace:
                        try:
                            __salt__['file.move'](cfg_tmp, path)
                        except CommandExecutionError:
                            if __salt__['file.file_exists'](cfg_tmp):
                                __salt__['file.remove'](cfg_tmp)
                            ret['result'] = False
                            ret['comment'] = 'Unable to be re-export zone configuration for {0} to {1}!'.format(
                                name,
                                path,
                            )
                        else:
                            ret['result'] = True
                            ret['comment'] = 'Zone configuration for {0} was re-exported to {1}.'.format(
                                name,
                                path,
                            )
                            ret['changes'][name] = 'exported'
                    else:
                        ret['result'] = False
                        ret['comment'] = 'Zone configuration for {0} is different from the one exported to {1}!'.format(
                            name,
                            path
                        )
                        if __salt__['file.file_exists'](cfg_tmp):
                            __salt__['file.remove'](cfg_tmp)
    else:
        ## zone does not exist
        ret['comment'] = []
        ret['comment'].append(
            'The zone {0} does not exist.'.format(name)
        )
        for zone in zones:
            if zones[zone]['uuid'] == name:
                ret['comment'].append(
                    'The zone {0} has a uuid of {1}, please use the zone name instead!'.format(
                        name,
                        path,
                    )
                )

        ret['result'] = False
        ret['comment'] = "\n".join(ret['comment'])

    return ret
1054087
def do_save(self, fp=None):
        
        if fp is None:
            fp = sys.stdout
        data = {
            'settings': self.settings,
            'nodes': self.nodes,
            'backward': self.backward
        }
        json.dump(data, fp, ensure_ascii=False)
350228
function save() {

		if ($this->cacheConf['type'] == 'noop') {
			// do nothing
		}
		else { // non-noop

			$stateCopy = $this->state;
			$stateCopy['loaded'] = [];

			if ($this->cacheConf['type'] == 'file') {
				$username = \get_current_user();
				$cacheDir = realpath($this->syspath.'/'.\trim($this->cacheConf['path'], '\\/'));
				$cachePath = $cacheDir.'/freia.'.(\php_sapi_name() === 'cli' ? 'cli' : 'server').'.'.$username.'.symbols.json';
				if ($this->file_exists($cacheDir)) {
					try {
						$this->file_put_contents($cachePath, \json_encode($stateCopy, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
						if ( ! $this->chmod($cachePath, $this->filePermission())) {
							$this->error_log("Unable to set permissions on cache file: $cachePath");
						}
					}
					catch (\Exception $e) {
						$this->error_log('Failed to save state to cache file ['.$cachePath.'] Error: '.$e->getMessage());
					}
				}
				else {
					$this->error_log('Missing cache directory: '.$this->cacheConf['path']);
				}
			}
			else if ($this->cacheConf['type'] == 'memcached') {
				$mc = $this->memcachedInstance();
				$success = $mc->set('freia-symbols', $stateCopy, time() + 604800);
				if ( ! $success) {
					$this->error_log("Memcached failed to store key freia-symbols, code: ".$mc->getResultCode());
				}
			}
		}
	}
288632
def save_config(self, data: dict) -> Path:
        """"""
        out_dir = Path(self.families_dir) / data['family']
        out_dir.mkdir(parents=True, exist_ok=True)
        out_path = out_dir / 'pedigree.yaml'
        dump = ruamel.yaml.round_trip_dump(data, indent=4, block_seq_indent=2)
        out_path.write_text(dump)
        return out_path
424359
def save_config(self):
        
        if not os.path.exists(self._conf_dir):
            os.makedirs(self._conf_dir)
        conf_file = os.path.join(self._conf_dir, "dql.json")
        with open(conf_file, "w") as ofile:
            json.dump(self.conf, ofile, indent=2)
1335738
def flush(name, family='ipv4', **kwargs):
    '''
    

    '''
    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': ''}

    for ignore in _STATE_INTERNAL_KEYWORDS:
        if ignore in kwargs:
            del kwargs[ignore]

    if 'table' not in kwargs:
        kwargs['table'] = 'filter'

    res = __salt__['nftables.check_table'](kwargs['table'], family=family)
    if not res['result']:
        ret['result'] = False
        ret['comment'] = 'Failed to flush table {0} in family {1}, table does not exist.'.format(
            kwargs['table'],
            family
        )
        return ret

    if 'chain' not in kwargs:
        kwargs['chain'] = ''
    else:
        res = __salt__['nftables.check_chain'](kwargs['table'],
                                               kwargs['chain'],
                                               family=family)
        if not res['result']:
            ret['result'] = False
            ret['comment'] = 'Failed to flush chain {0} in table {1} in family {2}, chain does not exist.'.format(
                kwargs['chain'],
                kwargs['table'],
                family
            )
            return ret

    res = __salt__['nftables.flush'](kwargs['table'],
                                     kwargs['chain'],
                                     family)
    if res['result']:
        ret['changes'] = {'locale': name}
        ret['result'] = True
        ret['comment'] = 'Flush nftables rules in {0} table {1} chain {2} family'.format(
            kwargs['table'],
            kwargs['chain'],
            family
        )
        return ret
    else:
        ret['result'] = False
        ret['comment'] = 'Failed to flush nftables rules'
        return ret
768664
def insert_io( args ):
    
    global CACHE_
    load_cache()
    hash = args['hash']
    record_used('cache', hash)
    packet_num = args['packet_num']
    if hash not in CACHE_['cache']:
        CACHE_['cache'][hash] = {}
    CACHE_['cache'][hash][packet_num] = pickle.dumps(args, PPROT)
    write_out()
721574
def save_rules(self, op_file):
        
        with open(op_file, 'w') as f:
            for m in self.maps:
                f.write(m.format_for_file_output())
729568
def store_db_obj(cls, in_obj, out_obj):
        
        cls.ip_db_obj['in'] = in_obj
        cls.ip_db_obj['out'] = out_obj
150651
def save_load(jid, clear_load, minions=None):
    '''
    
    '''
    jid = _escape_jid(jid)
    conn = _get_conn()
    if conn is None:
        return None
    cur = conn.cursor()
    sql = '''INSERT INTO jids ''' \
          '''(jid, started, tgt_type, cmd, tgt, kwargs, ret, username, arg,''' \
          ''' fun) ''' \
          '''VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'''

    cur.execute(
        sql, (
            jid,
            salt.utils.jid.jid_to_time(jid),
            six.text_type(clear_load.get("tgt_type")),
            six.text_type(clear_load.get("cmd")),
            six.text_type(clear_load.get("tgt")),
            six.text_type(clear_load.get("kwargs")),
            six.text_type(clear_load.get("ret")),
            six.text_type(clear_load.get("user")),
            six.text_type(salt.utils.json.dumps(clear_load.get("arg"))),
            six.text_type(clear_load.get("fun")),
        )
    )
    # TODO: Add Metadata support when it is merged from develop
    _close_conn(conn)
1336347
def save(self):
        
        # We don't save during the loading otherwise we could lost stuff
        if self._settings is None:
            return
        data = {
            "computes": [],
            "settings": self._settings,
            "gns3vm": self.gns3vm.__json__(),
            "version": __version__
        }

        for c in self._computes.values():
            if c.id != "local" and c.id != "vm":
                data["computes"].append({
                    "host": c.host,
                    "name": c.name,
                    "port": c.port,
                    "protocol": c.protocol,
                    "user": c.user,
                    "password": c.password,
                    "compute_id": c.id
                })
        try:
            os.makedirs(os.path.dirname(self._config_file), exist_ok=True)
            with open(self._config_file, 'w+') as f:
                json.dump(data, f, indent=4)
        except OSError as e:
            log.error("Can't write the configuration {}: {}".format(self._config_file, str(e)))
947140
def save_current_config(self, ):
        
        # check if all configs validate correctly
        btn = None
        for row in range(self.inimodel.rowCount()):
            i = self.inimodel.index(row, 0)
            r = self.inimodel.validate(i)
            if r is not True:
                btn = self.invalid_prompt()
                break

        if btn == QtGui.QMessageBox.Cancel:
            return
        current = self.files_lv.currentIndex()
        c = self.inimodel.data(current, self.inimodel.confobjRole)
        c.write()
        self.inimodel.set_index_edited(current, False)
423205
def salt_cp():
    '''
    
    '''
    import salt.cli.cp
    client = salt.cli.cp.SaltCPCli()
    _install_signal_handlers(client)
    client.run()