Skip to content

Commit 143bc9e

Browse files
authored
feat: Single process optimization (#5489)
Python interpreter initialization and module import time contributes a significant amount of wall clock time to cloud-init's runtime (and therefore to total boot time). Cloud-init has four stages. Each stage starts its own Python interpreter and loads the same libraries. To eliminate the redundant work of starting an interpreter and loading libraries, this changes cloud-init to run as a single process. Systemd service ordering is retained by using the existing cloud-init services as shims which use a synchronization protocol to start each cloud-init stage and to communicate that each stage is complete to the init system. Since multiple cloud-init processes sit in the critical chain of starting the system, this reduces boot time (including time to ssh login and time to cloud-init completion). Currently only systemd is supported, but the synchronization protocol should be capable of supporting other init systems as well with minor changes. Note: This enables many additional follow-on improvements that eliminate redundant work. However, these potential improvements are temporarily ignored. This commit has been structured to minimize the changes required to capture the majority of primary performance savings while preserving correctness and the ability to preserve backwards compatibility. Since this changes the semantics of the existing cloud-init unit files, this change takes the opportunity to rename one of its systemd units which causes frequent user confusion. The unit named cloud-init.service is often mistaken by users for being the only cloud-init service, when it is simply one of four stages. This stage is documented as the "network" stage, so this service will be renamed to "cloud-init-network.service". A new notify service is added as part of this implementation which contains the cloud-init process. This unit is named "cloud-init-main.service". Synchronization protocol ======================== - create one Unix socket for each systemd service stage - send sd_notify() - For each of the four stages (local, network, config, final): - when init system sends "start" to the Unix socket, start the stage - when running stage is complete, send "done" to Unix socket File changes ============ socket.py (new) --------------- - define a systemd-notify helper function - define a context manager which implements a multi-socket synchronization protocol cloud-init.service -> cloud-init-network.service (renamed) ---------------------------------------------------------- - renamed to cloud-network.service cloud-{init-local,init-network,config,final}.services ------------------------------------------- - change ExecStart to use netcat to connect to Unix socket and: - send a start message - wait for completion response - note: a pure Python equivalent is possible for any downstreams which do not package openbsd's netcat cloud-init-main.service (new) ----------------------------- - use service type to 'notify' - invoke cloud-init in single process mode - adopt systemd ordering requirements from cloud-init-local.service - adopt KillMode from cloud-final.service main.py ------- - Add command line flag to indicate "all stages" mode - In this mode run each stage followed by an IPC synchronization protocol step cloud-final.services -------------------- - drop KillMode cloud-init-local.services ------------------------- - drop dependencies made redundant by ordering after cloud-init-main.service Performance Impact ================== On Ubuntu 24.04, Python's wall clock start up time as measured with `time python3 -c 'import cloudinit.cmd.main' on a few cloud types: lxc container: 0.256s QEMU machine: 0.300s gce instance: 0.367s ec2 instance: 0.491s This change eliminates x1 this start up time from time to ssh. This change eliminates x3 this start up time from cloud-init's total completion. Total benefit varies based on the platform that the instance is hosted by, but all platforms will measurably benefit from this change. BREAKING_CHANGE: Run all four cloud-init services as a single systemd service.
1 parent ca3e6bc commit 143bc9e

25 files changed

Lines changed: 601 additions & 47 deletions

‎cloudinit/cmd/main.py‎

Lines changed: 105 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from cloudinit import netinfo
2525
from cloudinit import signal_handler
2626
from cloudinit import sources
27+
from cloudinit import socket
2728
from cloudinit import stages
2829
from cloudinit import url_helper
2930
from cloudinit import util
@@ -38,7 +39,12 @@
3839
from cloudinit.config.schema import validate_cloudconfig_schema
3940
from cloudinit import log
4041
from cloudinit.reporting import events
41-
from cloudinit.settings import PER_INSTANCE, PER_ALWAYS, PER_ONCE, CLOUD_CONFIG
42+
from cloudinit.settings import (
43+
PER_INSTANCE,
44+
PER_ALWAYS,
45+
PER_ONCE,
46+
CLOUD_CONFIG,
47+
)
4248

4349
# Welcome message template
4450
WELCOME_MSG_TPL = (
@@ -362,8 +368,11 @@ def main_init(name, args):
362368
outfmt = None
363369
errfmt = None
364370
try:
365-
close_stdin(lambda msg: early_logs.append((logging.DEBUG, msg)))
366-
outfmt, errfmt = util.fixup_output(init.cfg, name)
371+
if not args.skip_log_setup:
372+
close_stdin(lambda msg: early_logs.append((logging.DEBUG, msg)))
373+
outfmt, errfmt = util.fixup_output(init.cfg, name)
374+
else:
375+
outfmt, errfmt = util.get_output_cfg(init.cfg, name)
367376
except Exception:
368377
msg = "Failed to setup output redirection!"
369378
util.logexc(LOG, msg)
@@ -375,8 +384,9 @@ def main_init(name, args):
375384
"Logging being reset, this logger may no longer be active shortly"
376385
)
377386
log.reset_logging()
378-
log.setup_logging(init.cfg)
379-
apply_reporting_cfg(init.cfg)
387+
if not args.skip_log_setup:
388+
log.setup_logging(init.cfg)
389+
apply_reporting_cfg(init.cfg)
380390

381391
# Any log usage prior to setup_logging above did not have local user log
382392
# config applied. We send the welcome message now, as stderr/out have
@@ -633,8 +643,9 @@ def main_modules(action_name, args):
633643
mods = Modules(init, extract_fns(args), reporter=args.reporter)
634644
# Stage 4
635645
try:
636-
close_stdin()
637-
util.fixup_output(mods.cfg, name)
646+
if not args.skip_log_setup:
647+
close_stdin()
648+
util.fixup_output(mods.cfg, name)
638649
except Exception:
639650
util.logexc(LOG, "Failed to setup output redirection!")
640651
if args.debug:
@@ -643,8 +654,9 @@ def main_modules(action_name, args):
643654
"Logging being reset, this logger may no longer be active shortly"
644655
)
645656
log.reset_logging()
646-
log.setup_logging(mods.cfg)
647-
apply_reporting_cfg(init.cfg)
657+
if not args.skip_log_setup:
658+
log.setup_logging(mods.cfg)
659+
apply_reporting_cfg(init.cfg)
648660

649661
# now that logging is setup and stdout redirected, send welcome
650662
welcome(name, msg=w_msg)
@@ -804,9 +816,10 @@ def status_wrapper(name, args):
804816
)
805817

806818
v1[mode]["start"] = float(util.uptime())
807-
preexisting_recoverable_errors = next(
819+
handler = next(
808820
filter(lambda h: isinstance(h, log.LogExporter), root_logger.handlers)
809-
).export_logs()
821+
)
822+
preexisting_recoverable_errors = handler.export_logs()
810823

811824
# Write status.json prior to running init / module code
812825
atomic_helper.write_json(status_path, status)
@@ -847,11 +860,8 @@ def status_wrapper(name, args):
847860
v1["stage"] = None
848861

849862
# merge new recoverable errors into existing recoverable error list
850-
new_recoverable_errors = next(
851-
filter(
852-
lambda h: isinstance(h, log.LogExporter), root_logger.handlers
853-
)
854-
).export_logs()
863+
new_recoverable_errors = handler.export_logs()
864+
handler.clean_logs()
855865
for key in new_recoverable_errors.keys():
856866
if key in preexisting_recoverable_errors:
857867
v1[mode]["recoverable_errors"][key] = list(
@@ -953,9 +963,19 @@ def main(sysv_args=None):
953963
default=False,
954964
)
955965

966+
parser.add_argument(
967+
"--all-stages",
968+
dest="all_stages",
969+
action="store_true",
970+
help=(
971+
"Run cloud-init's stages under a single process using a "
972+
"syncronization protocol. This is not intended for CLI usage."
973+
),
974+
default=False,
975+
)
976+
956977
parser.set_defaults(reporter=None)
957978
subparsers = parser.add_subparsers(title="Subcommands", dest="subcommand")
958-
subparsers.required = True
959979

960980
# Each action and its sub-options (if any)
961981
parser_init = subparsers.add_parser(
@@ -1143,8 +1163,76 @@ def main(sysv_args=None):
11431163

11441164
status_parser(parser_status)
11451165
parser_status.set_defaults(action=("status", handle_status_args))
1166+
else:
1167+
parser.error("a subcommand is required")
11461168

11471169
args = parser.parse_args(args=sysv_args)
1170+
setattr(args, "skip_log_setup", False)
1171+
if not args.all_stages:
1172+
return sub_main(args)
1173+
return all_stages(parser)
1174+
1175+
1176+
def all_stages(parser):
1177+
"""Run all stages in a single process using an ordering protocol."""
1178+
LOG.info("Running cloud-init in single process mode.")
1179+
1180+
# this _must_ be called before sd_notify is called otherwise netcat may
1181+
# attempt to send "start" before a socket exists
1182+
sync = socket.SocketSync("local", "network", "config", "final")
1183+
1184+
# notify systemd that this stage has completed
1185+
socket.sd_notify("READY=1")
1186+
# wait for cloud-init-local.service to start
1187+
with sync("local"):
1188+
# set up logger
1189+
args = parser.parse_args(args=["init", "--local"])
1190+
args.skip_log_setup = False
1191+
# run local stage
1192+
sync.systemd_exit_code = sub_main(args)
1193+
1194+
# wait for cloud-init-network.service to start
1195+
with sync("network"):
1196+
# skip re-setting up logger
1197+
args = parser.parse_args(args=["init"])
1198+
args.skip_log_setup = True
1199+
# run init stage
1200+
sync.systemd_exit_code = sub_main(args)
1201+
1202+
# wait for cloud-config.service to start
1203+
with sync("config"):
1204+
# skip re-setting up logger
1205+
args = parser.parse_args(args=["modules", "--mode=config"])
1206+
args.skip_log_setup = True
1207+
# run config stage
1208+
sync.systemd_exit_code = sub_main(args)
1209+
1210+
# wait for cloud-final.service to start
1211+
with sync("final"):
1212+
# skip re-setting up logger
1213+
args = parser.parse_args(args=["modules", "--mode=final"])
1214+
args.skip_log_setup = True
1215+
# run final stage
1216+
sync.systemd_exit_code = sub_main(args)
1217+
1218+
# signal completion to cloud-init-main.service
1219+
if sync.experienced_any_error:
1220+
message = "a stage of cloud-init exited non-zero"
1221+
if sync.first_exception:
1222+
message = f"first exception received: {sync.first_exception}"
1223+
socket.sd_notify(
1224+
f"STATUS=Completed with failure, {message}. Run 'cloud-init status"
1225+
" --long' for more details."
1226+
)
1227+
socket.sd_notify("STOPPING=1")
1228+
# exit 1 for a fatal failure in any stage
1229+
return 1
1230+
else:
1231+
socket.sd_notify("STATUS=Completed")
1232+
socket.sd_notify("STOPPING=1")
1233+
1234+
1235+
def sub_main(args):
11481236

11491237
# Subparsers.required = True and each subparser sets action=(name, functor)
11501238
(name, functor) = args.action

‎cloudinit/cmd/status.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,8 +318,9 @@ def systemd_failed(wait: bool) -> bool:
318318
for service in [
319319
"cloud-final.service",
320320
"cloud-config.service",
321-
"cloud-init.service",
321+
"cloud-init-network.service",
322322
"cloud-init-local.service",
323+
"cloud-init-main.service",
323324
]:
324325
try:
325326
stdout = query_systemctl(

‎cloudinit/config/cc_mounts.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -524,7 +524,7 @@ def handle(name: str, cfg: Config, cloud: Cloud, args: list) -> None:
524524
# fs_spec, fs_file, fs_vfstype, fs_mntops, fs-freq, fs_passno
525525
uses_systemd = cloud.distro.uses_systemd()
526526
default_mount_options = (
527-
"defaults,nofail,x-systemd.after=cloud-init.service,_netdev"
527+
"defaults,nofail,x-systemd.after=cloud-init-network.service,_netdev"
528528
if uses_systemd
529529
else "defaults,nobootwait"
530530
)

‎cloudinit/config/schemas/schema-cloud-config-v1.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2022,12 +2022,12 @@
20222022
},
20232023
"mount_default_fields": {
20242024
"type": "array",
2025-
"description": "Default mount configuration for any mount entry with less than 6 options provided. When specified, 6 items are required and represent ``/etc/fstab`` entries. Default: ``defaults,nofail,x-systemd.after=cloud-init.service,_netdev``",
2025+
"description": "Default mount configuration for any mount entry with less than 6 options provided. When specified, 6 items are required and represent ``/etc/fstab`` entries. Default: ``defaults,nofail,x-systemd.after=cloud-init-network.service,_netdev``",
20262026
"default": [
20272027
null,
20282028
null,
20292029
"auto",
2030-
"defaults,nofail,x-systemd.after=cloud-init.service",
2030+
"defaults,nofail,x-systemd.after=cloud-init-network.service",
20312031
"0",
20322032
"2"
20332033
],

‎cloudinit/log.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,9 @@ def emit(self, record: logging.LogRecord):
152152
def export_logs(self):
153153
return copy.deepcopy(self.holder)
154154

155+
def clean_logs(self):
156+
self.holder = defaultdict(list)
157+
155158
def flush(self):
156159
pass
157160

0 commit comments

Comments
 (0)