Metadata-Version: 2.4
Name: systemd-dbus
Version: 0.4
Summary: Thin Python bindings for a minimal set of systemd service management commands, using sd-bus. Also includes functionality for creating unit files, as well as polkit rules.
Author: Jeffrey Smith
Author-email: Jeffrey Smith <jeffrey.smith@acceldata.io>
Maintainer-email: Jeffrey Smith <jeffrey.smith@acceldata.io>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [2026] [Acceldata]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Classifier: Operating System :: POSIX :: Linux
Requires-Python: >=2.7
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: LICENSES/LICENSE.LGPL2.1
Provides-Extra: dev
Requires-Dist: pytest<10,>=9.0; python_version >= "3.9" and extra == "dev"
Requires-Dist: pytest<7,>=6.0; (python_version >= "3.6" and python_version < "3.9") and extra == "dev"
Requires-Dist: pytest==4.6.11; python_version == "2.7" and extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Provides-Extra: jinja
Requires-Dist: jinja2==2.11.3; python_version <= "3.8" and extra == "jinja"
Requires-Dist: jinja2==3.1.6; python_version >= "3.11" and extra == "jinja"
Dynamic: author
Dynamic: license-file
Dynamic: requires-python

# Manage Systemd over DBus

This library can be used to Start/Stop/Restart services through Systemd, first
using DBus, then falling back to either use Python's `subproccess` module, or
if running through Ambari, using its functionality to do that instead.

If Ambari is detected, you can also write out Polkit rules, to allow specific
users to manage a specific service without needing root access, and also Systemd
unit file generation, which allows you to create Systemd unit files programatically.

This library works with both Python 2.7 and Python 3. It has only been tested
with 2.7 and 3.11, but will likely work with at least Python 3.8 or later.

## Installation

You must have `systemd-devel` or `libsystemd-dev` installed, as well as a c compiler.

Then run `pip install .` from the source directory.

Or you can run `pip install git+https://github.com/JeffreySmith/systemd_dbus` to
install directly from main.

## Basic Usage

```python
from systemd_dbus import SystemdManager

manager = SystemdManager()
print(manager.pid("sshd.service"))
print(manager.version())
# '.service' will be appended if not provided
manager.start("kudu-master.service")
manager.stop("kudu-master")
manager.restart("kudu-master.service")

manager.active("kudu-master") # returns True or False

manager.enable("kudu-master") # enables the service to start on boot
manager.timezone() # get's the timezone of the system
manager.container() # Will tell you the type of container the system is running
#in, or None if it's not running in a container
manager.virtualization() # Will tell you the type of virtualization the system is
#running on

pid = manager.pid("sshd.service") # Gives you the pid of the specified service

manager.daemon_reload() # Reload the Systemd Daemon, needed if you make changes
# to a unit file 

manager.log("Your message here") # Log a message to syslog/journald.
# You can override the default level (INFO) by passing log_level,
# Which can be any log level from Python's syslog.syslog.LOG_*
```

It can also act as a context manager, so you can write something like the following
if there's only one place you want it enabled:

```python
def some_function():
  with SystemdManager() as manager:
    manager.stop("my_service")
    manager.start("my_service.service")
    timezone = manager.timezone()
```

At the end of the above block, the resources (D-Bus connection and memory
allocated with malloc) will be cleaned up.

## Usage in Ambari

There are two ways to initialize SystemdManager in Ambari, depending on if you
can be sure the package is installed before the script is initialized.

If the library is already installed:

```python
from systemd_dbus import PolkitRule, SystemdManager, UnitFile
from resource_management.core.exceptions import ComponentIsNotRunning
class SomeMpack(Script)

  def __init__(self):
    super(SomeMpack, self).__init__()
    self.manager = SystemdManager() 
    self.my_service_name = "my_service"
    self.user = "my_user"
    self.group = "my_group"
  def install(self,env):
    pass

  def configure(self, env):
    unit_file = UnitFile(
      service_name=self.my_service_name,
      user=self.my_user,
      group=self.my_group,
    )
    # set_options is used to set many options at once,
    # but each key can be set individually as well
    unit_file.set_options(
      service=[
        # Systemd Property, value, comment.
        # Any other args after those 3 will be ignored
        ("ExecStart", start_command),
        ("EnvironmentFile", "-/my_env_file", "My Env file"),
      ],
      unit=[
        ("Description", "Description of my service"),
      ],
    )
    # Make sure you pass unit_file. This should be
    # name_of_service with ".service" at the end
    polkit_rule = PolkitRule(
      unit_file_name,
      users=[list_of_users_allowed_to_manage_this_service],
      ambari_user=ambari_user,
      unit_file=self.my_service_name + ".service",
    )
    
    unit_file.write()
    polkit_rule.write()
    self.manager.daemon_reload()
  
  def start(self, env):
    self.manager.start(self.my_service_name)

  def stop(self, env):
    self.manager.stop(self.my_service_name)

  def restart(self, env):
    self.stop(env)
    self.start(env)
  
  def status(self, env):
    if not self.manager.active(self.my_service_name):
      raise ComponentIsNotRunning
```

If the library is not guaranteed to be installed before the script is initialized:

```python
class SomeMpack(Script)

  def __init__(self):
    super(SomeMpack, self).__init__()
    self.manager = None


  def install(self,env):
    # Things get installed here
    pass

  @property
  def manager(self):
    """Lazy load the manager. The systemd library may not be installed
    until after self.install()"""
    if self._manager is None:
      from systemd_dbus import SystemdManager
      self._manager = SystemdManager()
    return self._manager

  def configure(self, env):
    # Now import UnitFile and PolkitRule
    from systemd_dbus import UnitFile, PolkitRule
    # Same as the first example

```

This is essentially doing a lazy import of systemd_dbus,
which will be unnecessary in python3.15 and later once [pep-0810](https://peps.python.org/pep-0810/)
is implemented.

Any resources will be cleaned up when the `SystemdManager` instance is garbage collected.

## Fallback

When using this library, it will first attempt to access everything through
DBus, but if that fails, it will attempt to fallback to using Ambari's
functionality (if available), and if not, the subprocess module from Python's
standard library.

Not all functionality is available through the fallback methods, so some
functions may not work if DBus is not available, but the most common ones
should work.

## Default Options

There are a number of options that will be set by default, some of which
are to make usage simpler, some of which are to improve security.

The most important options to verify work with your service are the following:

1. ReadWritePaths - Controls which paths the service can write to.
2. RuntimeDirectory (If needed)
3. ProtectHome - Prevents writing to the user's home directory.
4. PrivateTmp - Prevents other services from reading tmp files made by this service

`ReadWritePaths` is the option that is most likely to cause issues with your service,
since it controls where the service can write to.
In a Unit file, many keys can be specified multiple times, and the values
will not override each other. So if you need multiple directories to be writable,
you can specify `ReadWritePaths` as many times as needed.

## Systemd Unit File Options

The best place to find information about Systemd unit files is the [official docs](https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html).

At a bare minimum, you should have the following options defined:

```config
[Unit]
    Description=Description of your service
    After=network.target
[Service]
    User=<The user the service should be run as>
    Group=<Optional group the service should be run as>
    ExecStart=<start command for your service>
    ExecStop=<Optional stop command for your service>
[Install]
    WantedBy=multi-user.target

```

## Useful Functionality

If your component has more than one service (ie 'master', 'worker', 'namenode', etc),
you can define at initialization:

```python
nn_unit_file = UnitFile(service_name="hadoop", user="hdfs", component_name="namenode",)
nn_unit_file.set_start_command(my_start_command)
nn_unit_file.set_stop_command(my_stop_command)
nn_unit_file.write()
self.manager.daemon_reload()
```

This will create a unit file called `hadoop-namenode.service`.

You can manage individual keys for the Unit File:

```python
# Deletes all keys that match "EnvironmentFile"
UnitFile.delete_key("EnvironmentFile")
# Delete only the keys that match 'value'
UnitFile.delete_key("ExecStart", value="command_I_want_to_remove")
# Update some key
UnitFile.update_key(key, new_value, match="optional_value_to_match")
```

## Polkit Support

[Polkit](https://en.wikipedia.org/wiki/Polkit) is component for controlling privileges in Linux.
It can be used to allow/deny users, groups, etc, without using sudo.
These rules can be written and used without breaking the system, unlike sudo, which can do quite a lot of damage.
These rules are also easily reloadable at runtime, making using them very simple.

The only caveat is that not all Linux distributions support Polkit - For Ubuntu,
you must be running Ubuntu 23.04 or later, and for RHEL/CentOS, you must be
running RHEL/CentOS 8 or later.

Essentially, this can be used to automatically grant users the permissions
required to manage a service, without needing root access.

These rules are written in Javascript and will be written to `/usr/share/polkit-1/rules.d/`.

A basic example of automatically creating a polkit rules for a service is the following:

```python

def configure(self, env):
  # Same as above
  unit_file = UnitFile(
    service_name=self.my_service_name,
    user=self.my_user,
    group=self.my_group,
  )
  unit_file.set_options(
    service=[
      ("ExecStart", start_command),
      ("EnvironmentFile", "-/my_env_file", "My Env file"),
    ],
    unit=[
      ("Description", "Description of my service"),
    ],
  )

  polkit_rule = PolkitRule(
    "my_service", # This will become the name of the rule
    users=[params.my_user, params.my_hadoop_user],
    group=params.hadoop_group # 'group' is optional
    ambari_user=[pwd.getpwuid(os.getuid())[0]]
    ambari_group="group_that_ambari_user_belongs_to", # Also optional
  )

```

PolkitRule() has two additional specified parameters, `manual_rules`, in which
you can pass a Jinja template that you specifiy yourself, and `prefix`, which
by default is `40`, and controls the order in which files will be loaded.

Aside from that, it can take any other arguments that you might need in your template.
The args that the default template supports are:

1. users: list\[str\]
2. group: str
3. ambari_user: str
4. ambari_group: str

For your own manual Polkit rules, add any additional keywords to the instantiation
of the class:

```python
rule =PolkitRule(
  "name",
  users=["bob"],
  ambari_user="ambari"),
  my_dynamic_lib_dir=params.my_lib_dir,
)
rule.write()
```

If Polkit support is not available on the system, `.write()` is `noop`.

For full documentation on Polkit rules, see the [official documentation](https://www.freedesktop.org/software/polkit/docs/latest/polkit.8.html)

## Building a Debian package

To build the Debian package, make sure that you have all the needed Debian
package tools installed, and then run

```bash
chmod +x build_deb.sh
./build_deb.sh
```

By default, this will build a package for Python 3.11, but you can override
this by overriding the Python version:

```bash
PYTHON_VERSION=3.9 ./build_deb.sh
```

## Building an RPM package

To build an RPM package, make sure you have `rpmdevtools` installed, then run

```bash
./build_rpm.sh
```

You can change the version of Python used by doing the following:

```bash
PYTHON_VERSION=3.9 ./build_rpm.sh
```

## Static Checking the C Code

Much of this library is written in C. If you install
[cppcheck](https://github.com/danmar/cppcheck), you can run

```bash
./cppcheck_script.sh
```

to check the c code for any errors.

The following is an expected warning, and can be safely ignored.

```
src/systemd_dbus/c/systemd_dbus.c:687:16: style: The function 'PyInit__sdbus' is never used. [unusedFunction]
PyMODINIT_FUNC PyInit__sdbus(void) { return _init_module(); }
               ^
*systemd_dbus.c:0:0: information: Unmatched suppression: unusedFunction [unmatchedSuppression]

^
nofile:0:0: information: Active checkers: 113/186 (use --checkers-report=<filename> to see details) [checkersReport]
```
