Skip to content

Commit 5a6fb80

Browse files
authored
Refactor sidecar (#688)
* Add threading to the sidecar
1 parent fad1d3d commit 5a6fb80

File tree

1 file changed

+56
-30
lines changed

1 file changed

+56
-30
lines changed

foundationdb-kubernetes-sidecar/sidecar.py

Lines changed: 56 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121

2222
import argparse
2323
import hashlib
24-
import http.server
2524
import logging
2625
import json
2726
import os
@@ -32,8 +31,11 @@
3231
import time
3332
import traceback
3433
import sys
34+
import tempfile
3535
from pathlib import Path
3636

37+
from http.server import HTTPServer, ThreadingHTTPServer, BaseHTTPRequestHandler
38+
3739
from watchdog.observers import Observer
3840
from watchdog.events import FileSystemEventHandler
3941

@@ -58,7 +60,7 @@ def __init__(self):
5860
)
5961
parser.add_argument(
6062
"--tls",
61-
help=("This flag enables TLS for incoming " "connections"),
63+
help=("This flag enables TLS for incoming connections"),
6264
action="store_true",
6365
)
6466
parser.add_argument(
@@ -103,7 +105,7 @@ def __init__(self):
103105
)
104106
parser.add_argument(
105107
"--input-dir",
106-
help=("The directory containing the input files " "the config map."),
108+
help=("The directory containing the input files the config map."),
107109
default="/var/input-files",
108110
)
109111
parser.add_argument(
@@ -125,28 +127,26 @@ def __init__(self):
125127
)
126128
parser.add_argument(
127129
"--copy-file",
128-
help=("A file to copy from the config map to the " "output directory."),
130+
help=("A file to copy from the config map to the output directory."),
129131
action="append",
130132
)
131133
parser.add_argument(
132134
"--copy-binary",
133-
help=("A binary to copy from the to the output" "directory."),
135+
help=("A binary to copy from the to the output directory."),
134136
action="append",
135137
)
136138
parser.add_argument(
137139
"--copy-library",
138-
help=(
139-
"A version of the client library to copy " "to the output directory."
140-
),
140+
help=("A version of the client library to copy to the output directory."),
141141
action="append",
142142
)
143143
parser.add_argument(
144144
"--input-monitor-conf",
145-
help=("The name of a monitor conf template in the " "input files"),
145+
help=("The name of a monitor conf template in the input files"),
146146
)
147147
parser.add_argument(
148148
"--main-container-version",
149-
help=("The version of the main foundationdb " "container in the pod"),
149+
help=("The version of the main foundationdb container in the pod"),
150150
)
151151
parser.add_argument(
152152
"--main-container-conf-dir",
@@ -306,7 +306,7 @@ def is_at_least(self, target_version):
306306
)
307307

308308

309-
class Server(http.server.BaseHTTPRequestHandler):
309+
class Server(BaseHTTPRequestHandler):
310310
ssl_context = None
311311

312312
@classmethod
@@ -316,12 +316,12 @@ def start(cls):
316316
"""
317317
config = Config.shared()
318318
(address, port) = config.bind_address.split(":")
319-
log.info("Listening on %s:%s" % (address, port))
320-
httpd = http.server.HTTPServer((address, int(port)), cls)
319+
log.info(f"Listening on {address}:{port}")
320+
server = ThreadingHTTPServer((address, int(port)), cls)
321321

322322
if config.enable_tls:
323323
context = Server.load_ssl_context()
324-
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
324+
server.socket = context.wrap_socket(server.socket, server_side=True)
325325
observer = Observer()
326326
event_handler = CertificateEventHandler()
327327
for path in set(
@@ -333,7 +333,7 @@ def start(cls):
333333
observer.schedule(event_handler, path)
334334
observer.start()
335335

336-
httpd.serve_forever()
336+
server.serve_forever()
337337

338338
@classmethod
339339
def load_ssl_context(cls):
@@ -516,7 +516,19 @@ def log_message(self, format, *args):
516516

517517
class CertificateEventHandler(FileSystemEventHandler):
518518
def on_any_event(self, event):
519-
log.info("Detected change to certificates")
519+
if event.is_directory:
520+
return None
521+
522+
if event.event_type not in ["created", "modified"]:
523+
return None
524+
525+
# We ignore all old files
526+
if event.src_path.endswith(".old"):
527+
return None
528+
529+
log.info(
530+
f"Detected change to certificates path: {event.src_path}, type: {event.event_type }"
531+
)
520532
time.sleep(10)
521533
log.info("Reloading certificates")
522534
Server.load_ssl_context()
@@ -536,10 +548,13 @@ def copy_files():
536548
path = os.path.join(config.input_dir, filename)
537549
if not os.path.isfile(path) or os.path.getsize(path) == 0:
538550
raise Exception("No contents for file %s" % path)
551+
539552
for filename in config.copy_files:
540-
tmp_file = os.path.join(config.output_dir, f"{filename}.tmp")
541-
shutil.copy(os.path.join(config.input_dir, filename), tmp_file)
542-
os.replace(tmp_file, os.path.join(config.output_dir, filename))
553+
tmp_file = tempfile.NamedTemporaryFile(
554+
mode="w+b", dir=config.output_dir, delete=False
555+
)
556+
shutil.copy(os.path.join(config.input_dir, filename), tmp_file.name)
557+
os.replace(tmp_file.name, os.path.join(config.output_dir, filename))
543558

544559
return "OK"
545560

@@ -554,9 +569,13 @@ def copy_binaries():
554569
)
555570
if not target_path.exists():
556571
target_path.parent.mkdir(parents=True, exist_ok=True)
557-
tmp_file = f"{target_path}.tmp"
558-
shutil.copy(path, tmp_file)
559-
os.replace(tmp_file, target_path)
572+
tmp_file = tempfile.NamedTemporaryFile(
573+
mode="w+b",
574+
dir=target_path.parent,
575+
delete=False,
576+
)
577+
shutil.copy(path, tmp_file.name)
578+
os.replace(tmp_file.name, target_path)
560579
target_path.chmod(0o744)
561580
return "OK"
562581

@@ -573,9 +592,11 @@ def copy_libraries():
573592
)
574593
if not target_path.exists():
575594
target_path.parent.mkdir(parents=True, exist_ok=True)
576-
tmp_file = f"{target_path}.tmp"
577-
shutil.copy(path, tmp_file)
578-
os.replace(tmp_file, target_path)
595+
tmp_file = tempfile.NamedTemporaryFile(
596+
mode="w+b", dir=target_path.parent, delete=False
597+
)
598+
shutil.copy(path, tmp_file.name)
599+
os.replace(tmp_file.name, target_path)
579600
return "OK"
580601

581602

@@ -591,13 +612,16 @@ def copy_monitor_conf():
591612
"$" + variable, config.substitutions[variable]
592613
)
593614

594-
tmp_file = os.path.join(config.output_dir, "fdbmonitor.conf.tmp")
615+
tmp_file = tempfile.NamedTemporaryFile(
616+
mode="w+b", dir=config.output_dir, delete=False
617+
)
595618
target_file = os.path.join(config.output_dir, "fdbmonitor.conf")
596619

597-
with open(tmp_file, "w") as output_conf_file:
620+
with open(tmp_file.name, "w") as output_conf_file:
598621
output_conf_file.write(monitor_conf)
599622

600-
os.replace(tmp_file, target_file)
623+
os.replace(tmp_file.name, target_file)
624+
601625
return "OK"
602626

603627

@@ -629,5 +653,7 @@ def __init__(self, message):
629653
copy_libraries()
630654
copy_monitor_conf()
631655

632-
if not Config.shared().init_mode:
633-
Server.start()
656+
if Config.shared().init_mode:
657+
sys.exit(0)
658+
659+
Server.start()

0 commit comments

Comments
 (0)