Mercurial > hg > Applications > docker-wrapper
view portops.py @ 16:c64a640558ba
add remove.py
author | taiki |
---|---|
date | Tue, 10 Mar 2015 06:57:12 +0900 |
parents | 855a5e399f6e |
children |
line wrap: on
line source
#!/usr/bin/python portlist_file = "/etc/iecloud/iedockerport.list" CONTAINER_NUM_LIMIT = 8 testuser = "testuser" DELIMITER = "," HOST = "localhost" import sys,os import socket def remove_port_list(user, projectname): portlist = read_port_list() delete_line = "" release_port = "" print(user + projectname) for port in portlist: portline = port.split(DELIMITER) if (len(portline) < 3): continue if (portline[1] == user and portline[2] == projectname): delete_line = port release_port = portline[0] break if release_port == "": print("[!] No remove port.") return False portlist.remove(delete_line) portlist.append(release_port) write_port_list(portlist) return True def read_port_list(): f = open(portlist_file, "r") portlist = [] for port in f: portlist.append(port.rstrip()) f.close() return portlist def write_port_list(portlist): portlist_tmp = [] for port in portlist: portlist_tmp.append(port + "\n") f = open(portlist_file, "w") f.writelines(portlist_tmp) f.close() def is_limit(portlist, user): count = 0 for port in portlist: portline = port.split(DELIMITER) if len(portline) < 2: continue if portline[1] == user: count = count + 1 if count < CONTAINER_NUM_LIMIT: return True else: return False def connect_to(host, port): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host,port)) return sock except: sock.close() return None def is_used_port(port): sock = connect_to(HOST, port) socket.setdefaulttimeout(5) if sock: sock.close() return True else: return False def mark_use_port(user, projectname): portlist = read_port_list() port_num = "" for port in portlist: portline = port.split(DELIMITER) if len(portline) == 1: port_num = portline[0] break # if is_used_port(port_num): # print("[!] This port is already used.") # sys.exit() print("This port is not already used.") portlist.remove(port_num) portlist.append(port_num + DELIMITER + user + DELIMITER + projectname) write_port_list(portlist) def get_marked_port(user): ports = read_port_list() for port in ports: portline = port.split(DELIMITER) if len(portline) < 2: continue if portline[1] == user: return portline[0] def reserve_port(user, projectname): portlist = read_port_list() if not is_limit(portlist, user): return False mark_use_port(user,projectname) return True if __name__ == "__main__": print("put test source.") remove_port_list("taira", "sample")