Skip to content

Commit

Permalink
restrict port range for ssh
Browse files Browse the repository at this point in the history
  • Loading branch information
xudifsd committed Dec 29, 2019
1 parent 549da63 commit 0ad280f
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions src/docker-images/init-container/runtime/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from contextlib import closing
import json
import time
import random
from pathlib import Path

from kubernetes import client as k8s_client
Expand All @@ -22,13 +23,24 @@
"environment": 1,
"network": 2,
"k8s_api": 3,
"port": 4,
}

def find_free_port():
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(("", 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return s.getsockname()[1]
def find_free_port(min=40000, max=49999):
for i in range(100): # try 100 times
port = random.randint(min, max)

with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
try:
s.bind(("", port))
except OSError:
if i > 10:
logger.warning("failed %d times to get free port", i)
continue
return port

logger.error("failed to get free port")
sys.exit(ERROR_EXIT_CODE["port"])

def get_pod_name():
return os.environ.get("POD_NAME")
Expand Down

0 comments on commit 0ad280f

Please sign in to comment.