Bind a source to a zone

    .. versionadded:: 2016.3.0

    CLI Example:

    .. code-block:: bash

        salt '*' firewalld.add_source zone 192.168.1.0/24
555572
def add_source(zone, source, permanent=True):
    '''
    
    '''
    if source in get_sources(zone, permanent):
        log.info('Source is already bound to zone.')

    cmd = '--zone={0} --add-source={1}'.format(zone, source)

    if permanent:
        cmd += ' --permanent'

    return __firewall_cmd(cmd)
1148952
function(name, zoneLetter, cf, vpc, routeTable) {
  var self = this;

  self.isPublic         = false;

  base.Base.call(this, cf, 'EC2::Subnet', name);
  self.addProperty('VpcId', vpc.ref());

  self.zone = self.addProperty('AvailabilityZone', vpc.az(zoneLetter));

  self.cidrBlock = function(cidr) {
    self.cidr = vpc.mkSubnetCidrBlock(cidr);
    return self.addProperty('CidrBlock', self.cidr);
  };

  self.mapPublicIpOnLaunch = function(value) {
    if (arguments.length === 0) { value = true; }
    return self.addProperty('MapPublicIpOnLaunch', !!value);
  };

  var assocName = name+'RouteTableAssociation';
  cf.data.Resources[assocName] = subnet.makeSubnetRouteTableAssociation(assocName, cf, self, routeTable);

  //self.output(name+"CidrBlock", self.getAtt("CidrBlock"), "Subnet "+name+"CIDR block");   /* Do not know why CidrBlock is not available */
}
676785
def delete_zone(args):
    
    if args.__dict__.get('domain'):
        domain = args.domain

    password = get_password(args)
    token = connect.get_token(args.username, password, args.server)
    processing.delete_zone(args.server, token, domain)
299468
def server_bind(self):
        
        TCPServer.server_bind(self)
        host, port = self.socket.getsockname()[:2]
        self.server_port = port
        try:
            self.server_name = socket.getfqdn(host)
        except ValueError:
            # Use the local host name in case of error, like CPython does
            self.server_name = socket.gethostname()
842727
def attached(name, force=False):
    '''
    

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

    zones = __salt__['zoneadm.list'](installed=True, configured=True)
    if name in zones:
        if zones[name]['state'] == 'configured':
            if __opts__['test']:
                res_attach = {'status': True}
            else:
                res_attach = __salt__['zoneadm.attach'](name, force)
            ret['result'] = res_attach['status']
            if ret['result']:
                ret['changes'][name] = 'attached'
                ret['comment'] = 'The zone {0} was attached.'.format(name)
            else:
                ret['comment'] = []
                ret['comment'].append('Failed to attach zone {0}!'.format(name))
                if 'message' in res_attach:
                    ret['comment'].append(res_attach['message'])
                ret['comment'] = "\n".join(ret['comment'])
        else:
            ret['result'] = True
            ret['comment'] = 'zone {0} already attached.'.format(name)
    else:
        ret['result'] = False
        ret['comment'] = 'zone {0} is not configured!'.format(name)

    return ret
166075
def parse_delete_zone(prs, conn):
    
    prs_zone_delete = prs.add_parser('zone_delete', help='delete zone')
    prs_zone_delete.add_argument('--domain', action='store', required=True,
                                 help='specify zone')
    conn_options(prs_zone_delete, conn)
    prs_zone_delete.set_defaults(func=delete_zone)
70295
def add_source(self, filename, env_filename):
    
    self._ensure_unfrozen('Adding source')
    self._copy_or_link(filename, env_filename, "source")
1332999
def create(name, availability_zones, listeners, subnets=None,
           security_groups=None, scheme='internet-facing',
           region=None, key=None, keyid=None,
           profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    if exists(name, region, key, keyid, profile):
        return True
    if isinstance(availability_zones, six.string_types):
        availability_zones = salt.utils.json.loads(availability_zones)

    if isinstance(listeners, six.string_types):
        listeners = salt.utils.json.loads(listeners)

    _complex_listeners = []
    for listener in listeners:
        _complex_listeners.append(listener_dict_to_tuple(listener))

    try:
        lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets,
                                       security_groups=security_groups, scheme=scheme,
                                       complex_listeners=_complex_listeners)
        if lb:
            log.info('Created ELB %s', name)
            return True
        else:
            log.error('Failed to create ELB %s', name)
            return False
    except boto.exception.BotoServerError as error:
        log.error('Failed to create ELB %s: %s: %s',
                  name, error.error_code, error.message,
                  exc_info_on_loglevel=logging.DEBUG)
        return False
592596
def set_source(self, controller, zone, source):
        

        _LOGGER.info("Begin - controller= %s, zone= %s change source to %s.", controller, zone, source)
        send_msg = self.create_send_message("F0 @cc 00 7F 00 @zz @kk 05 02 00 00 00 F1 3E 00 00 00 @pr 00 01",
                                            controller, zone, source)
        try:
            self.lock.acquire()
            _LOGGER.debug('Zone %s - acquired lock for ', zone)
            self.send_data(send_msg)
            _LOGGER.debug("Zone %s - sent message %s", zone, send_msg)
            # Clear response buffer in case there is any response data(ensures correct results on future reads)
            self.get_response_message()
        finally:
            self.lock.release()
            _LOGGER.debug("Zone %s - released lock for ", zone)
            _LOGGER.debug("End - controller= %s, zone= %s source set to %s.\n", controller, zone, source)
379019
def add_firewalld_port(port, permanent=True):
    

    yum_install(packages=['firewalld'])

    log_green('adding a new fw rule: %s' % port)
    with settings(hide('warnings', 'running', 'stdout', 'stderr'),
                  warn_only=True, capture=True):
        p = ''
        if permanent:
            p = '--permanent'
        sudo('firewall-cmd --add-port %s %s' % (port, p))
        sudo('systemctl restart firewalld')
1338923
def parse_zone(zonefile=None, zone=None):
    '''
    
    '''
    if zonefile:
        try:
            with salt.utils.files.fopen(zonefile, 'r') as fp_:
                zone = salt.utils.stringutils.to_unicode(fp_.read())
        except Exception:
            pass

    if not zone:
        return 'Error: Zone data was not found'

    zonedict = {}
    mode = 'single'
    for line in zone.splitlines():
        comps = line.split(';')
        line = comps[0].strip()
        if not line:
            continue
        comps = line.split()
        if line.startswith('$'):
            zonedict[comps[0].replace('$', '')] = comps[1]
            continue
        if '(' in line and ')' not in line:
            mode = 'multi'
            multi = ''
        if mode == 'multi':
            multi += ' {0}'.format(line)
            if ')' in line:
                mode = 'single'
                line = multi.replace('(', '').replace(')', '')
            else:
                continue
        if 'ORIGIN' in zonedict:
            comps = line.replace('@', zonedict['ORIGIN']).split()
        else:
            comps = line.split()
        if 'SOA' in line:
            if comps[1] != 'IN':
                comps.pop(1)
            zonedict['ORIGIN'] = comps[0]
            zonedict['NETWORK'] = comps[1]
            zonedict['SOURCE'] = comps[3]
            zonedict['CONTACT'] = comps[4].replace('.', '@', 1)
            zonedict['SERIAL'] = comps[5]
            zonedict['REFRESH'] = _to_seconds(comps[6])
            zonedict['RETRY'] = _to_seconds(comps[7])
            zonedict['EXPIRE'] = _to_seconds(comps[8])
            zonedict['MINTTL'] = _to_seconds(comps[9])
            continue
        if comps[0] == 'IN':
            comps.insert(0, zonedict['ORIGIN'])
        if not comps[0].endswith('.') and 'NS' not in line:
            comps[0] = '{0}.{1}'.format(comps[0], zonedict['ORIGIN'])
        if comps[2] == 'NS':
            zonedict.setdefault('NS', []).append(comps[3])
        elif comps[2] == 'MX':
            if 'MX' not in zonedict:
                zonedict.setdefault('MX', []).append({'priority': comps[3],
                                                      'host': comps[4]})
        elif comps[3] in ('A', 'AAAA'):
            zonedict.setdefault(comps[3], {})[comps[0]] = {
                'TARGET': comps[4],
                'TTL': comps[1],
            }
        else:
            zonedict.setdefault(comps[2], {})[comps[0]] = comps[3]
    return zonedict
970355
def _bind(self):
        
        self._bind_as(self.settings.BIND_DN, self.settings.BIND_PASSWORD, sticky=True)
138878
def edit_standard_fwl_rules(self, firewall_id, rules):
        

        rule_svc = self.client['Network_Firewall_Update_Request']
        template = {'networkComponentFirewallId': firewall_id, 'rules': rules}

        return rule_svc.createObject(template)
896632
def createLinkToSelf(self, new_zone, callback=None, errback=None,
                         **kwargs):
        
        zone = Zone(self.config, new_zone)
        kwargs['link'] = self.data['zone']
        return zone.create(callback=callback, errback=errback, **kwargs)
225210
def setup_zone(self):
        
        # Initialize current zone
        zones_content = self.request(self.api_url, 'get')
        try:
            if len(self.domain.split('.')) == 3:
                domain = self.domain.split('.', 1)[1]
            else:
                domain = self.domain
            zone = [zone for zone in zones_content['result'] if zone['name'] == domain][0]
        except IndexError:
            raise ZoneNotFound('Cannot find zone information for the domain {domain}.'
                               .format(domain=self.domain))
        self.zone = zone

        # Initialize dns_records of current zone
        dns_content = self.request(self.api_url + zone['id'] + '/dns_records', 'get')
        self.dns_records = dns_content['result']
1261894
def bind_addr(self, value):
        """"""
        if isinstance(value, tuple) and value[0] in ('', None):
            # Despite the socket module docs, using '' does not
            # allow AI_PASSIVE to work. Passing None instead
            # returns '0.0.0.0' like we want. In other words:
            #     host    AI_PASSIVE     result
            #      ''         Y         192.168.x.y
            #      ''         N         192.168.x.y
            #     None        Y         0.0.0.0
            #     None        N         127.0.0.1
            # But since you can get the same effect with an explicit
            # '0.0.0.0', we deny both the empty string and None as values.
            raise ValueError(
                "Host values of '' or None are not allowed. "
                "Use '0.0.0.0' (IPv4) or '::' (IPv6) instead "
                'to listen on all active interfaces.',
            )
        self._bind_addr = value
1206996
def get_interfaces(zone, permanent=True):
    '''
    
    '''
    cmd = '--zone={0} --list-interfaces'.format(zone)

    if permanent:
        cmd += ' --permanent'

    return __firewall_cmd(cmd).split()