示例#1
0
文件: omapi.py 项目: bryson/salt
def delete_host(mac=None, name=None):
    """
    Delete the host with the given mac or name.

    CLI Examples:

    .. code-block:: bash

        salt dhcp-server omapi.delete_host name=host1
        salt dhcp-server omapi.delete_host mac=ab:ab:ab:ab:ab:ab
    """
    if not (mac or name):
        raise TypeError("At least one argument is required")
    o = _conn()
    msg = omapi.OmapiMessage.open(b"host")
    if mac:
        msg.obj.append(("hardware-address", omapi.pack_mac(mac)))
        msg.obj.append(("hardware-type", struct.pack("!I", 1)))
    if name:
        msg.obj.append(("name", name))
    response = o.query_server(msg)
    if response.opcode != omapi.OMAPI_OP_UPDATE:
        return None
    if response.handle == 0:
        return False
    response = o.query_server(omapi.OmapiMessage.delete(response.handle))
    if response.opcode != omapi.OMAPI_OP_STATUS:
        return False
    return True
示例#2
0
def delete_host(mac=None, name=None):
    '''
    Delete the host with the given mac or name.

    CLI Examples:

    .. code-block:: bash

        salt dhcp-server omapi.delete_host name=host1
        salt dhcp-server omapi.delete_host mac=ab:ab:ab:ab:ab:ab
    '''
    if not (mac or name):
        raise TypeError('At least one argument is required')
    o = _conn()
    msg = omapi.OmapiMessage.open(b'host')
    if mac:
        msg.obj.append(('hardware-address', omapi.pack_mac(mac)))
        msg.obj.append(('hardware-type', struct.pack('!I', 1)))
    if name:
        msg.obj.append(('name', name))
    response = o.query_server(msg)
    if response.opcode != omapi.OMAPI_OP_UPDATE:
        return None
    if response.handle == 0:
        return False
    response = o.query_server(omapi.OmapiMessage.delete(response.handle))
    if response.opcode != omapi.OMAPI_OP_STATUS:
        return False
    return True
示例#3
0
def delete_host(mac=None, name=None):
    """
    Delete the host with the given mac or name.

    CLI Examples:

    .. code-block:: bash

        salt dhcp-server omapi.delete_host name=host1
        salt dhcp-server omapi.delete_host mac=ab:ab:ab:ab:ab:ab
    """
    if not (mac or name):
        raise TypeError("At least one argument is required")
    o = _conn()
    msg = omapi.OmapiMessage.open(b"host")
    if mac:
        msg.obj.append((b"hardware-address", omapi.pack_mac(mac)))
        msg.obj.append((b"hardware-type", struct.pack(b"!I", 1)))
    if name:
        msg.obj.append((b"name", salt.utils.stringutils.to_bytes(name)))
    response = o.query_server(msg)
    if response.opcode != omapi.OMAPI_OP_UPDATE:
        return None
    if response.handle == 0:
        return False
    response = o.query_server(omapi.OmapiMessage.delete(response.handle))
    if response.opcode != omapi.OMAPI_OP_STATUS:
        return False
    return True
示例#4
0
文件: omapi.py 项目: sitepoint/salt
def delete_host(mac=None, name=None):
    '''
    Delete the host with the given mac or name.

    CLI Examples::
        
        salt dhcp-server omapi.delete_host name=host1
        salt dhcp-server omapi.delete_host mac=ab:ab:ab:ab:ab:ab
    '''
    if not (mac or name):
        raise TypeError('At least one argument is required')
    o = _conn()
    msg = omapi.OmapiMessage.open(b'host')
    if mac:
        msg.obj.append(('hardware-address', omapi.pack_mac(mac)))
        msg.obj.append(('hardware-type', struct.pack('!I', 1)))
    if name:
        msg.obj.append(('name', name))
    response = o.query_server(msg)
    if response.opcode != omapi.OMAPI_OP_UPDATE:
        return None
    if response.handle == 0:
        return False
    response = o.query_server(omapi.OmapiMessage.delete(response.handle))
    if response.opcode != omapi.OMAPI_OP_STATUS:
        return False
    return True
示例#5
0
 def get_host(self, macaddr):
     msg = OmapiMessage.open(to_bytes("host", errors='surrogate_or_strict'))
     msg.obj.append((to_bytes("hardware-address", errors='surrogate_or_strict'), pack_mac(macaddr)))
     msg.obj.append((to_bytes("hardware-type", errors='surrogate_or_strict'), struct.pack("!I", 1)))
     response = self.omapi.query_server(msg)
     if response.opcode != OMAPI_OP_UPDATE:
         return None
     return response
示例#6
0
 def get_host(self, macaddr):
     msg = OmapiMessage.open(to_bytes("host", errors='surrogate_or_strict'))
     msg.obj.append((to_bytes("hardware-address", errors='surrogate_or_strict'), pack_mac(macaddr)))
     msg.obj.append((to_bytes("hardware-type", errors='surrogate_or_strict'), struct.pack("!I", 1)))
     response = self.omapi.query_server(msg)
     if response.opcode != OMAPI_OP_UPDATE:
         return None
     return response
示例#7
0
 def lookup_lease_mac(self, mac):
     """
     Lookup lease by MAC
     """
     msg = pypureomapi.OmapiMessage.open(b"lease")
     msg.obj.append((b"hardware-address", pypureomapi.pack_mac(mac)))
     response = self.query_server(msg)
     if response.opcode != pypureomapi.OMAPI_OP_UPDATE:
         raise pypureomapi.OmapiErrorNotFound()
     return Lease(response.obj)
示例#8
0
 def lookup_host_mac(self, mac):
     """
     Lookup host by MAC
     """
     msg = pypureomapi.OmapiMessage.open("host")
     msg.obj.append(("hardware-address", pypureomapi.pack_mac(mac)))
     response = self.query_server(msg)
     if response.opcode != pypureomapi.OMAPI_OP_UPDATE:
         raise pypureomapi.OmapiErrorNotFound()
     try:
         return pypureomapi.unpack_ip(dict(response.obj)["ip-address"])
     except KeyError:  # ip-address
         raise pypureomapi.OmapiErrorNotFound()
示例#9
0
def add_host_w_args(omapi, ip, hwaddr, host, state_list):
    msg = pypureomapi.OmapiMessage.open(b'host')
    msg.message.append(('create', struct.pack('!I', 1)))
    msg.message.append(('exclusive', struct.pack('!I', 1)))
    msg.obj.append(('hardware-address', pypureomapi.pack_mac(hwaddr)))
    msg.obj.append(("hardware-type", struct.pack("!I", 1)))
    msg.obj.append(('ip-address', pypureomapi.pack_ip(ip)))
    msg.obj.append(("name", host))
    statements = ""
    for s in state_list:
        statements += s
    statements += 'supersede host-name "%s";' % host
    msg.obj.append(('statements', statements))
    resp = omapi.query_server(msg)
    print(resp.message)
示例#10
0
 def add_host_with_group(self, mac, groupname):
     """Create a host object with given mac address and group.
     @type mac: str
     @type groupname: str
     @raises ValueError:
     @raises OmapiError:
     @raises socket.error:
     """
     msg = OmapiMessage.open(b"host")
     msg.message.append((b"create", struct.pack("!I", 1)))
     msg.message.append((b"exclusive", struct.pack("!I", 1)))
     msg.obj.append((b"hardware-address", pack_mac(mac)))
     msg.obj.append((b"hardware-type", struct.pack("!I", 1)))
     msg.obj.append((b"group", str(groupname)))
     response = self.query_server(msg)
     if response.opcode != OMAPI_OP_UPDATE:
         raise OmapiError("Adding host '%s' failed" % mac)
示例#11
0
文件: omapi.py 项目: morinap/salt-1
def add_host(mac,
             name=None,
             ip=None,
             ddns=False,
             group=None,
             supersede_host=False):
    '''
    Add a host object for the given mac.

    CLI Example:

    .. code-block:: bash

        salt dhcp-server omapi.add_host ab:ab:ab:ab:ab:ab name=host1

    Add ddns-hostname and a fixed-ip statements:

    .. code-block:: bash

        salt dhcp-server omapi.add_host ab:ab:ab:ab:ab:ab name=host1 ip=10.1.1.1 ddns=true
    '''
    statements = ''
    o = _conn()
    msg = omapi.OmapiMessage.open(b'host')
    msg.message.append((b'create', struct.pack(b'!I', 1)))
    msg.message.append((b'exclusive', struct.pack(b'!I', 1)))
    msg.obj.append((b'hardware-address', omapi.pack_mac(mac)))
    msg.obj.append((b'hardware-type', struct.pack(b'!I', 1)))
    if ip:
        msg.obj.append((b'ip-address', omapi.pack_ip(ip)))
    if name:
        msg.obj.append((b'name', salt.utils.stringutils.to_bytes(name)))
    if group:
        msg.obj.append((b'group', salt.utils.stringutils.to_bytes(group)))
    if supersede_host:
        statements += 'option host-name "{0}"; '.format(name)
    if ddns and name:
        statements += 'ddns-hostname "{0}"; '.format(name)
    if statements:
        msg.obj.append(
            (b'statements', salt.utils.stringutils.to_bytes(statements)))
    response = o.query_server(msg)
    if response.opcode != omapi.OMAPI_OP_UPDATE:
        return False
    return True
示例#12
0
文件: omapi.py 项目: 1mentat/salt
def add_host(mac, name=None, ip=None, ddns=False, group=None,
        supersede_host=False):
    '''
    Add a host object for the given mac.

    CLI Example:

    .. code-block:: bash

        salt dhcp-server omapi.add_host ab:ab:ab:ab:ab:ab name=host1

    Add ddns-hostname and a fixed-ip statements:

    .. code-block:: bash

        salt dhcp-server omapi.add_host ab:ab:ab:ab:ab:ab name=host1 ip=10.1.1.1 ddns=true
    '''
    statements = ''
    o = _conn()
    msg = omapi.OmapiMessage.open(b'host')
    msg.message.append(('create', struct.pack('!I', 1)))
    msg.message.append(('exclusive', struct.pack('!I', 1)))
    msg.obj.append(('hardware-address', omapi.pack_mac(mac)))
    msg.obj.append(('hardware-type', struct.pack('!I', 1)))
    if ip:
        msg.obj.append(('ip-address', omapi.pack_ip(ip)))
    if name:
        msg.obj.append(('name', name))
    if group:
        msg.obj.append(('group', group))
    if supersede_host:
        statements += 'option host-name {0}; '.format(name)
    if ddns and name:
        statements += 'ddns-hostname {0}; '.format(name)
    if statements:
        msg.obj.append(('statements', statements))
    response = o.query_server(msg)
    if response.opcode != omapi.OMAPI_OP_UPDATE:
        return False
    return True
示例#13
0
文件: omapi.py 项目: bryson/salt
def add_host(mac, name=None, ip=None, ddns=False, group=None, supersede_host=False):
    """
    Add a host object for the given mac.

    CLI Example:

    .. code-block:: bash

        salt dhcp-server omapi.add_host ab:ab:ab:ab:ab:ab name=host1

    Add ddns-hostname and a fixed-ip statements:

    .. code-block:: bash

        salt dhcp-server omapi.add_host ab:ab:ab:ab:ab:ab name=host1 ip=10.1.1.1 ddns=true
    """
    statements = ""
    o = _conn()
    msg = omapi.OmapiMessage.open(b"host")
    msg.message.append(("create", struct.pack("!I", 1)))
    msg.message.append(("exclusive", struct.pack("!I", 1)))
    msg.obj.append(("hardware-address", omapi.pack_mac(mac)))
    msg.obj.append(("hardware-type", struct.pack("!I", 1)))
    if ip:
        msg.obj.append(("ip-address", omapi.pack_ip(ip)))
    if name:
        msg.obj.append(("name", name))
    if group:
        msg.obj.append(("group", group))
    if supersede_host:
        statements += 'option host-name "{0}"; '.format(name)
    if ddns and name:
        statements += 'ddns-hostname "{0}"; '.format(name)
    if statements:
        msg.obj.append(("statements", statements))
    response = o.query_server(msg)
    if response.opcode != omapi.OMAPI_OP_UPDATE:
        return False
    return True
示例#14
0
  def add_host_with_options(self, mac, options={}, group=None):
    optionList=[]
    msg = pypureomapi.OmapiMessage.open(b'host')
    msg.message.append((b'create', struct.pack('!I', 1)))
    msg.message.append((b'exclusive', struct.pack('!I', 1)))
    msg.obj.append((b'hardware-type', struct.pack('!I', 1)))
    msg.obj.append((b'hardware-address', pypureomapi.pack_mac(mac)))

    for key, value in options.items():
      optionList.append('option {0} "{1}";'.format(key,value))
    if optionList:
      msg.obj.append((b'statements', ''.join(optionList).lower().encode('utf8')))

    # unsupported since group takes precedence over options
    # if group:
    #   msg.obj.append((b'group', group.encode('utf8')))

    logger.debug('Omapi message: {0}'.format(msg.obj))

    response = self.query_server(msg)
    if response.opcode !=  pypureomapi.OMAPI_OP_UPDATE:
      raise pypureomapi.OmapiError('Add failed')
示例#15
0
    def setup_host(self):
        if self.module.params['hostname'] is None or len(self.module.params['hostname']) == 0:
            self.module.fail_json(msg="name attribute could not be empty when adding or modifying host.")

        msg = None
        host_response = self.get_host(self.module.params['macaddr'])
        # If host was not found using macaddr, add create message
        if host_response is None:
            msg = OmapiMessage.open(to_bytes('host', errors='surrogate_or_strict'))
            msg.message.append(('create', struct.pack('!I', 1)))
            msg.message.append(('exclusive', struct.pack('!I', 1)))
            msg.obj.append(('hardware-address', pack_mac(self.module.params['macaddr'])))
            msg.obj.append(('hardware-type', struct.pack('!I', 1)))
            msg.obj.append(('name', self.module.params['hostname']))
            if self.module.params['ip'] is not None:
                msg.obj.append((to_bytes("ip-address", errors='surrogate_or_strict'), pack_ip(self.module.params['ip'])))

            stmt_join = ""
            if self.module.params['ddns']:
                stmt_join += 'ddns-hostname "{0}"; '.format(self.module.params['hostname'])

            try:
                if len(self.module.params['statements']) > 0:
                    stmt_join += "; ".join(self.module.params['statements'])
                    stmt_join += "; "
            except TypeError:
                e = get_exception()
                self.module.fail_json(msg="Invalid statements found: %s" % e)

            if len(stmt_join) > 0:
                msg.obj.append(('statements', stmt_join))

            try:
                response = self.omapi.query_server(msg)
                if response.opcode != OMAPI_OP_UPDATE:
                    self.module.fail_json(msg="Failed to add host, ensure authentication and host parameters "
                                              "are valid.")
                self.module.exit_json(changed=True, lease=self.unpack_facts(response.obj))
            except OmapiError:
                e = get_exception()
                self.module.fail_json(msg="OMAPI error: %s" % e)
        # Forge update message
        else:
            response_obj = self.unpack_facts(host_response.obj)
            fields_to_update = {}

            if to_bytes('ip-address', errors='surrogate_or_strict') not in response_obj or \
                            unpack_ip(response_obj[to_bytes('ip-address', errors='surrogate_or_strict')]) != self.module.params['ip']:
                fields_to_update['ip-address'] = pack_ip(self.module.params['ip'])

            # Name cannot be changed
            if 'name' not in response_obj or response_obj['name'] != self.module.params['hostname']:
                self.module.fail_json(msg="Changing hostname is not supported. Old was %s, new is %s. "
                                          "Please delete host and add new." %
                                          (response_obj['name'], self.module.params['hostname']))

            """
            # It seems statements are not returned by OMAPI, then we cannot modify them at this moment.
            if 'statements' not in response_obj and len(self.module.params['statements']) > 0 or \
                response_obj['statements'] != self.module.params['statements']:
                with open('/tmp/omapi', 'w') as fb:
                    for (k,v) in iteritems(response_obj):
                        fb.writelines('statements: %s %s\n' % (k, v))
            """
            if len(fields_to_update) == 0:
                self.module.exit_json(changed=False, lease=response_obj)
            else:
                msg = OmapiMessage.update(host_response.handle)
                msg.update_object(fields_to_update)

            try:
                response = self.omapi.query_server(msg)
                if response.opcode != OMAPI_OP_STATUS:
                    self.module.fail_json(msg="Failed to modify host, ensure authentication and host parameters "
                                              "are valid.")
                self.module.exit_json(changed=True)
            except OmapiError:
                e = get_exception()
                self.module.fail_json(msg="OMAPI error: %s" % e)
示例#16
0
    def setup_host(self):
        if self.module.params['hostname'] is None or len(self.module.params['hostname']) == 0:
            self.module.fail_json(msg="name attribute could not be empty when adding or modifying host.")

        msg = None
        host_response = self.get_host(self.module.params['macaddr'])
        # If host was not found using macaddr, add create message
        if host_response is None:
            msg = OmapiMessage.open(to_bytes('host', errors='surrogate_or_strict'))
            msg.message.append(('create', struct.pack('!I', 1)))
            msg.message.append(('exclusive', struct.pack('!I', 1)))
            msg.obj.append(('hardware-address', pack_mac(self.module.params['macaddr'])))
            msg.obj.append(('hardware-type', struct.pack('!I', 1)))
            msg.obj.append(('name', self.module.params['hostname']))
            if self.module.params['ip'] is not None:
                msg.obj.append((to_bytes("ip-address", errors='surrogate_or_strict'), pack_ip(self.module.params['ip'])))

            stmt_join = ""
            if self.module.params['ddns']:
                stmt_join += 'ddns-hostname "{0}"; '.format(self.module.params['hostname'])

            try:
                if len(self.module.params['statements']) > 0:
                    stmt_join += "; ".join(self.module.params['statements'])
                    stmt_join += "; "
            except TypeError as e:
                self.module.fail_json(msg="Invalid statements found: %s" % to_native(e),
                                      exception=traceback.format_exc())

            if len(stmt_join) > 0:
                msg.obj.append(('statements', stmt_join))

            try:
                response = self.omapi.query_server(msg)
                if response.opcode != OMAPI_OP_UPDATE:
                    self.module.fail_json(msg="Failed to add host, ensure authentication and host parameters "
                                              "are valid.")
                self.module.exit_json(changed=True, lease=self.unpack_facts(response.obj))
            except OmapiError as e:
                self.module.fail_json(msg="OMAPI error: %s" % to_native(e), exception=traceback.format_exc())
        # Forge update message
        else:
            response_obj = self.unpack_facts(host_response.obj)
            fields_to_update = {}

            if to_bytes('ip-address', errors='surrogate_or_strict') not in response_obj or \
                            unpack_ip(response_obj[to_bytes('ip-address', errors='surrogate_or_strict')]) != self.module.params['ip']:
                fields_to_update['ip-address'] = pack_ip(self.module.params['ip'])

            # Name cannot be changed
            if 'name' not in response_obj or response_obj['name'] != self.module.params['hostname']:
                self.module.fail_json(msg="Changing hostname is not supported. Old was %s, new is %s. "
                                          "Please delete host and add new." %
                                          (response_obj['name'], self.module.params['hostname']))

            """
            # It seems statements are not returned by OMAPI, then we cannot modify them at this moment.
            if 'statements' not in response_obj and len(self.module.params['statements']) > 0 or \
                response_obj['statements'] != self.module.params['statements']:
                with open('/tmp/omapi', 'w') as fb:
                    for (k,v) in iteritems(response_obj):
                        fb.writelines('statements: %s %s\n' % (k, v))
            """
            if len(fields_to_update) == 0:
                self.module.exit_json(changed=False, lease=response_obj)
            else:
                msg = OmapiMessage.update(host_response.handle)
                msg.update_object(fields_to_update)

            try:
                response = self.omapi.query_server(msg)
                if response.opcode != OMAPI_OP_STATUS:
                    self.module.fail_json(msg="Failed to modify host, ensure authentication and host parameters "
                                              "are valid.")
                self.module.exit_json(changed=True)
            except OmapiError as e:
                self.module.fail_json(msg="OMAPI error: %s" % to_native(e), exception=traceback.format_exc())