def __init__(self): self.token=None thread.start_new(self.daemon_token, ()) while self.token==None: print "Getting token" sleep(1) print "token got" self.unallocated = redis.connect('unallocated') self.allocated=redis.connect('allocated') self.get_timesleep=0.002 self.rec_timesleep=0.002
def clean_redis(): len_all, len_unall = 1, 1 while len_all or len_unall != 0: clear_all() print "清除所有cache" sleep(20) len_all = redis.connect('allocated').qsize() len_unall = redis.connect('unallocated').qsize() print "Cache 可分配IP:" + str(len_all) print "Cache 可回收IP:" + str(len_unall) print "Cache清理完成"
def rec_ip(self): sleep(self.rec_timesleep) token=self.token if token : unallocated = redis.connect('unallocated') ip=unallocated.get_nowait() if ip : try: #从不可用列表拿出IP回收到IPAM self.rec_timesleep = 0.002 print foo.rec_ip(token,ip) except : #异常 丢回可用列表cache self.allocated.put(ip) print str(ip)+" rec false return cache" else: self.rec_timesleep=10
# coding=utf-8 from core import Connect from core.Connect import redis import sys sys.path.append("..") id_store = redis.connectmap() unallocated = redis.connect('unallocated') allocated = redis.connect('allocated') class ip: #回收IP @staticmethod def rec_ip(ips): unallocated.put(ips) return ips #从redis队列拿IP @staticmethod def get_ip(): ip = allocated.get_nowait() return ip class Store: @staticmethod def put_dockerid(key, value): #{"dockerid","ip"} return ip
def get_allocated_ip(): rev = redis.connect('allocated').get_nowait() return rev
def len_unallocat(): len_all = redis.connect('unallocated').qsize() return len_all
def clear_all(): redis.connect('').clear_all()
table = iptc.Table(iptc.Table.FILTER) chain = iptc.Chain(table, "INPUT") rule = iptc.Rule() rule.protocol = "tcp" match = iptc.Match(rule, 'tcp') rule.add_match(match) #关闭5000端口 match.dport = '5000' target = rule.create_target("DROP") rule.target = target chain.insert_rule(rule) table.commit() print "##清空队列所有cache" clean_redis() uselist = search_k8s() allip = search_DB() print "获取网段IP总量完成:" + str(len(allip)) Unuse = [i for i in allip if i not in uselist] print "计算可用IP数:" + str(len(Unuse)) print type(Unuse) for ip in Unuse: print ip redis.connect('allocated').put(ip) Sync_idmap() print "释放端口" ######################### chain.delete_rule(rule) table.commit()