summaryrefslogtreecommitdiff
path: root/src/core/unit.h
AgeCommit message (Collapse)Author
2016-11-02Merge pull request #4481 from poettering/perpetualZbigniew Jędrzejewski-Szmek
Add "perpetual" unit concept, sysctl fixes, networkd fixes, systemctl color fixes, nspawn discard.
2016-11-02unit: unify some code with new unit_new_for_name() callLennart Poettering
2016-11-02core: rework the "no_gc" unit flag to become a more generic "perpetual" flagLennart Poettering
So far "no_gc" was set on -.slice and init.scope, to units that are always running, cannot be stopped and never exist in an "inactive" state. Since these units are the only users of this flag, let's remodel it and rename it "perpetual" and let's derive more funcitonality off it. Specifically, refuse enqueing stop jobs for these units, and report that they are "unstoppable" in the CanStop bus property.
2016-11-01core: when restarting services, don't close fdsZbigniew Jędrzejewski-Szmek
We would close all the stored fds in service_release_resources(), which of course broke the whole concept of storing fds over service restart. Fixes #4408.
2016-10-21failure-action: generalize failure action to emergency actionLukas Nykryn
2016-10-07core: add "invocation ID" concept to service managerLennart Poettering
This adds a new invocation ID concept to the service manager. The invocation ID identifies each runtime cycle of a unit uniquely. A new randomized 128bit ID is generated each time a unit moves from and inactive to an activating or active state. The primary usecase for this concept is to connect the runtime data PID 1 maintains about a service with the offline data the journal stores about it. Previously we'd use the unit name plus start/stop times, which however is highly racy since the journal will generally process log data after the service already ended. The "invocation ID" kinda matches the "boot ID" concept of the Linux kernel, except that it applies to an individual unit instead of the whole system. The invocation ID is passed to the activated processes as environment variable. It is additionally stored as extended attribute on the cgroup of the unit. The latter is used by journald to automatically retrieve it for each log logged message and attach it to the log entry. The environment variable is very easily accessible, even for unprivileged services. OTOH the extended attribute is only accessible to privileged processes (this is because cgroupfs only supports the "trusted." xattr namespace, not "user."). The environment variable may be altered by services, the extended attribute may not be, hence is the better choice for the journal. Note that reading the invocation ID off the extended attribute from journald is racy, similar to the way reading the unit name for a logging process is. This patch adds APIs to read the invocation ID to sd-id128: sd_id128_get_invocation() may be used in a similar fashion to sd_id128_get_boot(). PID1's own logging is updated to always include the invocation ID when it logs information about a unit. A new bus call GetUnitByInvocationID() is added that allows retrieving a bus path to a unit by its invocation ID. The bus path is built using the invocation ID, thus providing a path for referring to a unit that is valid only for the current runtime cycleof it. Outlook for the future: should the kernel eventually allow passing of cgroup information along AF_UNIX/SOCK_DGRAM messages via a unique cgroup id, then we can alter the invocation ID to be generated as hash from that rather than entirely randomly. This way we can derive the invocation race-freely from the messages.
2016-08-26Merge pull request #3984 from poettering/refcntEvgeny Vereshchagin
permit bus clients to pin units to avoid automatic GC
2016-08-23core,network: Use const qualifiers for block-local variables in macro ↵Felipe Sateler
functions (#4019) Prevents discard-qualifiers warnings when the passed variable was const
2016-08-22core: cache last CPU usage counter, before destorying a cgroupLennart Poettering
It is useful for clients to be able to read the last CPU usage counter value of a unit even if the unit is already terminated. Hence, before destroying a cgroup's cgroup cache the last CPU usage counter and return it if the cgroup is gone.
2016-08-22core: add Ref()/Unref() bus calls for unitsLennart Poettering
This adds two (privileged) bus calls Ref() and Unref() to the Unit interface. The two calls may be used by clients to pin a unit into memory, so that various runtime properties aren't flushed out by the automatic GC. This is necessary to permit clients to race-freely acquire runtime results (such as process exit status/code or accumulated CPU time) on successful service termination. Ref() and Unref() are fully recursive, hence act like the usual reference counting concept in C. Taking a reference is a privileged operation, as this allows pinning units into memory which consumes resources. Transient units may also gain a reference at the time of creation, via the new AddRef property (that is only defined for transient units at the time of creation).
2016-08-19core: add RemoveIPC= settingLennart Poettering
This adds the boolean RemoveIPC= setting to service, socket, mount and swap units (i.e. all unit types that may invoke processes). if turned on, and the unit's user/group is not root, all IPC objects of the user/group are removed when the service is shut down. The life-cycle of the IPC objects is hence bound to the unit life-cycle. This is particularly relevant for units with dynamic users, as it is essential that no objects owned by the dynamic users survive the service exiting. In fact, this patch adds code to imply RemoveIPC= if DynamicUser= is set. In order to communicate the UID/GID of an executed process back to PID 1 this adds a new "user lookup" socket pair, that is inherited into the forked processes, and closed before the exec(). This is needed since we cannot do NSS from PID 1 due to deadlock risks, However need to know the used UID/GID in order to clean up IPC owned by it if the unit shuts down.
2016-08-18unit: remove orphaned cgroup_netclass_id fieldLennart Poettering
2016-08-07core: add cgroup CPU controller support on the unified hierarchyTejun Heo
Unfortunately, due to the disagreements in the kernel development community, CPU controller cgroup v2 support has not been merged and enabling it requires applying two small out-of-tree kernel patches. The situation is explained in the following documentation. https://git.kernel.org/cgit/linux/kernel/git/tj/cgroup.git/tree/Documentation/cgroup-v2-cpu.txt?h=cgroup-v2-cpu While it isn't clear what will happen with CPU controller cgroup v2 support, there are critical features which are possible only on cgroup v2 such as buffered write control making cgroup v2 essential for a lot of workloads. This commit implements systemd CPU controller support on the unified hierarchy so that users who choose to deploy CPU controller cgroup v2 support can easily take advantage of it. On the unified hierarchy, "cpu.weight" knob replaces "cpu.shares" and "cpu.max" replaces "cpu.cfs_period_us" and "cpu.cfs_quota_us". [Startup]CPUWeight config options are added with the usual compat translation. CPU quota settings remain unchanged and apply to both legacy and unified hierarchies. v2: - Error in man page corrected. - CPU config application in cgroup_context_apply() refactored. - CPU accounting now works on unified hierarchy.
2016-07-22core: add a concept of "dynamic" user ids, that are allocated as long as a ↵Lennart Poettering
service is running This adds a new boolean setting DynamicUser= to service files. If set, a new user will be allocated dynamically when the unit is started, and released when it is stopped. The user ID is allocated from the range 61184..65519. The user will not be added to /etc/passwd (but an NSS module to be added later should make it show up in getent passwd). For now, care should be taken that the service writes no files to disk, since this might result in files owned by UIDs that might get assigned dynamically to a different service later on. Later patches will tighten sandboxing in order to ensure that this cannot happen, except for a few selected directories. A simple way to test this is: systemd-run -p DynamicUser=1 /bin/sleep 99999
2016-07-20core: when forcibly killing/aborting left-over unit processes log about itLennart Poettering
Let's lot at LOG_NOTICE about any processes that we are going to SIGKILL/SIGABRT because clean termination of them didn't work. This turns the various boolean flag parameters to cg_kill(), cg_migrate() and related calls into a single binary flags parameter, simply because the function now gained even more parameters and the parameter listed shouldn't get too long. Logging for killing processes is done either when the kill signal is SIGABRT or SIGKILL, or on explicit request if KILL_TERMINATE_AND_LOG instead of LOG_TERMINATE is passed. This isn't used yet in this patch, but is made use of in a later patch.
2016-06-30manager: Only invoke a single sigchld per unit within a cleanup cycleKyle Walker
By default, each iteration of manager_dispatch_sigchld() results in a unit level sigchld event being invoked. For scope units, this results in a scope_sigchld_event() which can seemingly stall for workloads that have a large number of PIDs within the scope. The stall exhibits itself as a SIG_0 being initiated for each u->pids entry as a result of pid_is_unwaited(). v2: This patch resolves this condition by only paying to cost of a sigchld in the underlying scope unit once per sigchld iteration. A new "sigchldgen" member resides within the Unit struct. The Manager is incremented via the sd event loop, accessed via sd_event_get_iteration, and the Unit member is set to the same value as the manager each time that a sigchld event is invoked. If the Manager iteration value and Unit member match, the sigchld event is not invoked for that iteration.
2016-05-07Merge pull request #3160 from htejun/cgroup-fixes-rev2Zbigniew Jędrzejewski-Szmek
Cgroup fixes.
2016-05-04Merge pull request #3170 from poettering/v230-preparation-fixesLennart Poettering
make virtualization detection quieter, rework unit start limit logic, detect unit file drop-in changes correctly, fix autofs state propagation
2016-05-02core: move enforcement of the start limit into per-unit-type code againLennart Poettering
Let's move the enforcement of the per-unit start limit from unit.c into the type-specific files again. For unit types that know a concept of "result" codes this allows us to hook up the start limit condition to it with an explicit result code. Also, this makes sure that the state checks in clal like service_start() may be done before the start limit is checked, as the start limit really should be checked last, right before everything has been verified to be in order. The generic start limit logic is left in unit.c, but the invocation of it is moved into the per-type files, in the various xyz_start() functions, so that they may place the check at the right location. Note that this change drops the enforcement entirely from device, slice, target and scope units, since these unit types generally may not fail activation, or may only be activated a single time. This is also documented now. Note that restores the "start-limit-hit" result code that existed before 6bf0f408e4833152197fb38fb10a9989c89f3a59 already in the service code. However, it's not introduced for all units that have a result code concept. Fixes #3166.
2016-05-01Move no_instances information to shared/Zbigniew Jędrzejewski-Szmek
This way it can be used in install.c in subsequent commit.
2016-05-01Move no_alias information to shared/Zbigniew Jędrzejewski-Szmek
This way it can be used in install.c in subsequent commit.
2016-04-30core: make unit_has_mask_realized() consider controller enable stateTejun Heo
unit_has_mask_realized() determines whether the specified unit has its cgroups set up properly given the desired target_mask; however, on the unified hierarchy, controllers need to be enabled explicitly for children and the mask of enabled controllers can deviate from target_mask. Only considering target_mask in unit_has_mask_realized() can lead to false positives and skipping enabling the requested controllers. This patch adds unit->cgroup_enabled_mask to track which controllers are enabled and updates unit_has_mask_realized() to also consider enable_mask. Signed-off-by: Tejun Heo <htejun@fb.com>
2016-04-22core,systemctl: add bus API to retrieve processes of a unitLennart Poettering
This adds a new GetProcesses() bus call to the Unit object which returns an array consisting of all PIDs, their process names, as well as their full cgroup paths. This is then used by "systemctl status" to show the per-unit process tree. This has the benefit that the client-side no longer needs to access the cgroupfs directly to show the process tree of a unit. Instead, it now uses this new API, which means it also works if -H or -M are used correctly, as the information from the specific host is used, and not the one from the local system. Fixes: #2945
2016-04-12core: rework how transient unit files and property drop-ins workLennart Poettering
With this change the logic for placing transient unit files and drop-ins generated via "systemctl set-property" is reworked. The latter are now placed in the newly introduced "control" unit file directory. The fomer are now placed in the "transient" unit file directory. Note that the properties originally set when a transient unit was created will be written to and stay in the transient unit file directory, while later changes are done via drop-ins. This is preparation for a later "systemctl revert" addition, where existing drop-ins are flushed out, but the original transient definition is restored.
2016-02-10Merge pull request #2569 from zonque/removalsMartin Pitt
Remove some old cruft
2016-02-10tree-wide: remove Emacs lines from all filesDaniel Mack
This should be handled fine now by .dir-locals.el, so need to carry that stuff in every file.
2016-02-10core: make the StartLimitXYZ= settings generic and apply to any kind of ↵Lennart Poettering
unit, not just services This moves the StartLimitBurst=, StartLimitInterval=, StartLimitAction=, RebootArgument= from the [Service] section into the [Unit] section of unit files, and thus support it in all unit types, not just in services. This way we can enforce the start limit much earlier, in particular before testing the unit conditions, so that repeated start-up failure due to failed conditions is also considered for the start limit logic. For compatibility the four options may also be configured in the [Service] section still, but we only document them in their new section [Unit]. This also renamed the socket unit failure code "service-failed-permanent" into "service-start-limit-hit" to express more clearly what it is about, after all it's only triggered through the start limit being hit. Finally, the code in busname_trigger_notify() and socket_trigger_notify() is altered to become more alike. Fixes: #2467
2016-02-04core: rework job_get_timeout() to use usec_t and handle USEC_INFINITY time ↵Lennart Poettering
events correctly
2016-02-01core: store for each unit when the last low-level unit state change took placeLennart Poettering
This adds a new timestamp field to the Unit struct, storing when the last low-level state change took place, and make sure this is restored after a daemon reload. This new field is useful to allow restarting of per-state timers exactly where they originally started.
2015-11-24core: Do not bind a mount unit to a device, if it was from mountinfoHarald Hoyer
If a mount unit is bound to a device, systemd tries to umount the mount point, if it thinks the device has gone away. Due to the uevent queue and inotify of /proc/self/mountinfo being two different sources, systemd can never get the ordering reliably correct. It can happen, that in the uevent queue ADD,REMOVE,ADD is queued and an inotify of mountinfo (or libmount event) happend with the device in question. systemd cannot know, at which point of time the mount happend in the ADD,REMOVE,ADD sequence. The real ordering might have been ADD,REMOVE,ADD,mount and systemd might think ADD,mount,REMOVE,ADD and would umount the mountpoint. A test script which triggered this behaviour is: rm -f test-efi-disk.img dd if=/dev/null of=test-efi-disk.img bs=1M seek=512 count=1 parted --script test-efi-disk.img \ "mklabel gpt" \ "mkpart ESP fat32 1MiB 511MiB" \ "set 1 boot on" LOOP=$(losetup --show -f -P test-efi-disk.img) udevadm settle mkfs.vfat -F32 ${LOOP}p1 mkdir -p mnt mount ${LOOP}p1 mnt ... <dostuffwith mnt> Without the "udevadm settle" systemd unmounted mnt while the script was operating on mnt. Of course the question is, why there was a REMOVE in the first place, but this is not part of this patch.
2015-11-18tree-wide: sort includes in *.hThomas Hindoe Paaboel Andersen
This is a continuation of the previous include sort patch, which only sorted for .c files.
2015-11-17core: move check whether a unit is suitable to become transient into unit.cLennart Poettering
Lets introduce unit_is_pristine() that verifies whether a unit is suitable to become a transient unit, by checking that it is no referenced yet and has no data on disk assigned.
2015-11-13core: now that .snapshot unit are gone, we don't need the per-type .no_gc ↵Lennart Poettering
bool anymore
2015-11-11Merge pull request #1837 from poettering/grabbag2Tom Gundersen
variety of fixes
2015-11-10Remove snapshot unit typeZbigniew Jędrzejewski-Szmek
Snapshots were never useful or used for anything. Many systemd developers that I spoke to at systemd.conf2015, didn't even know they existed, so it is fairly safe to assume that this type can be deleted without harm. The fundamental problem with snapshots is that the state of the system is dynamic, devices come and go, users log in and out, timers fire... and restoring all units to some state from the past would "undo" those changes, which isn't really possible. Tested by creating a snapshot, running the new binary, and checking that the transition did not cause errors, and the snapshot is gone, and snapshots cannot be created anymore. New systemctl says: Unknown operation snapshot. Old systemctl says: Failed to create snapshot: Support for snapshots has been removed. IgnoreOnSnaphost settings are warned about and ignored: Support for option IgnoreOnSnapshot= has been removed and it is ignored http://lists.freedesktop.org/archives/systemd-devel/2015-November/034872.html
2015-11-10core: change type of distribute_fds() prototype to return voidLennart Poettering
We can't handle errors of thisc all sanely anyway, and we never actually return any errors from the unit type that implements the call. Hence, let's make this void, in order to simplify things.
2015-11-10core: change return value of the unit's enumerate() call to voidLennart Poettering
We cannot handle enumeration failures in a sensible way, hence let's try hard to continue without making such failures fatal, and log about it with precise error messages.
2015-10-19tree-wide: remove unused functionsThomas Hindoe Paaboel Andersen
2015-10-17unit: allocate bus name match string on the stackLennart Poettering
Let's use strjoina() rather than strjoin() for construct dbus match strings. Also, while we are at it, fix parameter ordering, so that our functions always put the object first, like it is customary for OO-like programming.
2015-10-08core: add support for setting stdin/stdout/stderr for transient servicesLennart Poettering
When starting a transient service, allow setting stdin/stdout/stderr fds for it, by passing them in via the bus. This also simplifies some of the serialization code for units.
2015-09-28Move UnitActiveState to basic/Zbigniew Jędrzejewski-Szmek
Preparation to allow systemctl to query the list of unit states.
2015-09-16cgroup: add support for net_cls controllersDaniel Mack
Add a new config directive called NetClass= to CGroup enabled units. Allowed values are positive numbers for fix assignments and "auto" for picking a free value automatically, for which we need to keep track of dynamically assigned net class IDs of units. Introduce a hash table for this, and also record the last ID that was given out, so the allocator can start its search for the next 'hole' from there. This could eventually be optimized with something like an irb. The class IDs up to 65536 are considered reserved and won't be assigned automatically by systemd. This barrier can be made a config directive in the future. Values set in unit files are stored in the CGroupContext of the unit and considered read-only. The actually assigned number (which may have been chosen dynamically) is stored in the unit itself and is guaranteed to remain stable as long as the unit is active. In the CGroup controller, set the configured CGroup net class to net_cls.classid. Multiple unit may share the same net class ID, and those which do are linked together.
2015-09-01core: unified cgroup hierarchy supportLennart Poettering
This patch set adds full support the new unified cgroup hierarchy logic of modern kernels. A new kernel command line option "systemd.unified_cgroup_hierarchy=1" is added. If specified the unified hierarchy is mounted to /sys/fs/cgroup instead of a tmpfs. No further hierarchies are mounted. The kernel command line option defaults to off. We can turn it on by default as soon as the kernel's APIs regarding this are stabilized (but even then downstream distros might want to turn this off, as this will break any tools that access cgroupfs directly). It is possibly to choose for each boot individually whether the unified or the legacy hierarchy is used. nspawn will by default provide the legacy hierarchy to containers if the host is using it, and the unified otherwise. However it is possible to run containers with the unified hierarchy on a legacy host and vice versa, by setting the $UNIFIED_CGROUP_HIERARCHY environment variable for nspawn to 1 or 0, respectively. The unified hierarchy provides reliable cgroup empty notifications for the first time, via inotify. To make use of this we maintain one manager-wide inotify fd, and each cgroup to it. This patch also removes cg_delete() which is unused now. On kernel 4.2 only the "memory" controller is compatible with the unified hierarchy, hence that's the only controller systemd exposes when booted in unified heirarchy mode. This introduces a new enum for enumerating supported controllers, plus a related enum for the mask bits mapping to it. The core is changed to make use of this everywhere. This moves PID 1 into a new "init.scope" implicit scope unit in the root slice. This is necessary since on the unified hierarchy cgroups may either contain subgroups or processes but not both. PID 1 hence has to move out of the root cgroup (strictly speaking the root cgroup is the only one where processes and subgroups are still allowed, but in order to support containers nicey, we move PID 1 into the new scope in all cases.) This new unit is also used on legacy hierarchy setups. It's actually pretty useful on all systems, as it can then be used to filter journal messages coming from PID 1, and so on. The root slice ("-.slice") is now implicitly created and started (and does not require a unit file on disk anymore), since that's where "init.scope" is located and the slice needs to be started before the scope can. To check whether we are in unified or legacy hierarchy mode we use statfs() on /sys/fs/cgroup. If the .f_type field reports tmpfs we are in legacy mode, if it reports cgroupfs we are in unified mode. This patch set carefuly makes sure that cgls and cgtop continue to work as desired. When invoking nspawn as a service it will implicitly create two subcgroups in the cgroup it is using, one to move the nspawn process into, the other to move the actual container processes into. This is done because of the requirement that cgroups may either contain processes or other subgroups.
2015-08-31unit: unify how we assing slices to unitsLennart Poettering
This adds a new call unit_set_slice(), and simplifies unit_add_default_slice(). THis should make our code a bit more robust and simpler.
2015-08-31unit: add new macros to test for unit contextsLennart Poettering
2015-08-28core: add unit_dbus_interface_from_type() to unit-name.hLennart Poettering
Let's add a way to get the type-specific D-Bus interface of a unit from either its type or name to src/basic/unit-name.[ch]. That way we can share it with the client side, where it is useful in tools like cgls or machinectl. Also ports over machinectl to make use of this.
2015-08-06core: dbus: track bus names per unitDaniel Mack
Currently, PID1 installs an unfiltered NameOwnerChanged signal match, and dispatches the signals itself. This does not scale, as right now, PID1 wakes up every time a bus client connects. To fix this, install individual matches once they are requested by unit_watch_bus_name(), and remove the watches again through their slot in unit_unwatch_bus_name(). If the bus is not available during unit_watch_bus_name(), just store name in the 'watch_bus' hashmap, and let bus_setup_api() do the installing later.
2015-07-21core: fix confusing logging of instantaneous jobsMichal Schmidt
For instantaneous jobs (e.g. starting of targets, sockets, slices, or Type=simple services) the log shows the job completion before starting: systemd[1]: Created slice -.slice. systemd[1]: Starting -.slice. systemd[1]: Created slice System Slice. systemd[1]: Starting System Slice. systemd[1]: Listening on Journal Audit Socket. systemd[1]: Starting Journal Audit Socket. systemd[1]: Reached target Timers. systemd[1]: Starting Timers. ... The reason is that the job completes before the ->start() method returns and only then does unit_start() print the "Starting ..." message. The same thing happens when stopping units. Rather than fixing the order of the messages, let's just not emit the Starting/Stopping message at all when the job completes instantaneously. The job completion message is sufficient in this case.
2015-05-19unit: drop support for pre-v44 job serializationLennart Poettering
No distro ships that old systemd versions anyway, hence let's drop support for live-upgrades for them. Offline updates are still supported. And live-upgrades will only lose the job queue, hence basically still work...
2015-05-19core: also enforce ratelimiter if we stop a unit due to BindsTo=Lennart Poettering
This extends on bea355dac94e82697aa98e25d80ee4248263bf92, and extends the ratelimiter to not only be used for StopWhenUnneeded=1 units but also for units that have BindsTo= on a unit that is dead. http://lists.freedesktop.org/archives/systemd-devel/2015-April/030224.html