Hi,

rebased, updated package dependencies, and verified against 
Fedora 16+updates-testing.

This patch is for ipa-2-1 branch. I need to do few cosmetic changes in 
freeipa.spec.in to accomodate it to 3.0 (master branch) as ipa_kpasswd 
is gone there.

-- 
/ Alexander Bokovoy
>From f71e9d5f59de43293b4162c933502fd80e5d3aa3 Mon Sep 17 00:00:00 2001
From: Alexander Bokovoy <aboko...@redhat.com>
Date: Mon, 10 Oct 2011 15:25:15 +0300
Subject: [PATCH] Add support for systemd environments and use it to support
 Fedora 16

https://fedorahosted.org/freeipa/ticket/1192
---
 Makefile                          |    2 +-
 freeipa.spec.in                   |   77 ++++++++++++++-
 ipa.init => init/SystemV/ipa.init |    0
 init/systemd/ipa.service          |   14 +++
 init/systemd/ipa_kpasswd.service  |   10 ++
 install/tools/ipactl              |   12 ++-
 ipapython/config.py               |    2 +-
 ipapython/ipautil.py              |   90 ++++++++++++++++
 ipapython/platform/base.py        |   14 ++--
 ipapython/platform/fedora16.py    |  113 ++++++++++++++++++++
 ipapython/platform/redhat.py      |   61 ++---------
 ipapython/platform/systemd.py     |  204 +++++++++++++++++++++++++++++++++++++
 ipaserver/install/cainstance.py   |    4 +-
 ipaserver/install/dsinstance.py   |    6 +-
 ipaserver/install/krbinstance.py  |   30 ++----
 15 files changed, 552 insertions(+), 87 deletions(-)
 rename ipa.init => init/SystemV/ipa.init (100%)
 create mode 100644 init/systemd/ipa.service
 create mode 100644 init/systemd/ipa_kpasswd.service
 create mode 100644 ipapython/platform/fedora16.py
 create mode 100644 ipapython/platform/systemd.py

diff --git a/Makefile b/Makefile
index 
9d8802587f9fa1130271d3824667d83b637ac9ee..3cd08e2e9dd6b65ae9ad82af08cc68979048b6cd
 100644
--- a/Makefile
+++ b/Makefile
@@ -8,7 +8,7 @@ PRJ_PREFIX=freeipa
 RPMBUILD ?= $(PWD)/rpmbuild
 TARGET ?= master
 
-SUPPORTED_PLATFORM=redhat
+SUPPORTED_PLATFORM ?= redhat
 
 # After updating the version in VERSION you should run the version-update
 # target.
diff --git a/freeipa.spec.in b/freeipa.spec.in
index 
ed88e445aeb1783ea2011dc6ad62b5e3bf05db8e..927ec1cd839b1a2b2947f28ce754e98c2600b70d
 100644
--- a/freeipa.spec.in
+++ b/freeipa.spec.in
@@ -24,10 +24,17 @@ Source0:        freeipa-%{version}.tar.gz
 BuildRoot:      %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n)
 
 %if ! %{ONLY_CLIENT}
+%if 0%{?fedora} >= 16
+BuildRequires: 389-ds-base-devel >= 1.2.10
+%else
 BuildRequires:  389-ds-base-devel >= 1.2.9
+%endif
 BuildRequires:  svrcore-devel
 BuildRequires:  /usr/share/selinux/devel/Makefile
 BuildRequires:  policycoreutils >= %{POLICYCOREUTILSVER}
+%if 0%{?fedora} >= 16
+BuildRequires:  systemd-units 
+%endif
 %endif
 BuildRequires:  nspr-devel
 BuildRequires:  nss-devel
@@ -85,11 +92,19 @@ Requires: %{name}-python = %{version}-%{release}
 Requires: %{name}-client = %{version}-%{release}
 Requires: %{name}-admintools = %{version}-%{release}
 Requires: %{name}-server-selinux = %{version}-%{release}
+%if 0%{?fedora} >= 16
+Requires(pre): 389-ds-base >= 1.2.10-0.1.a1
+%else
 Requires(pre): 389-ds-base >= 1.2.9.7-1
+%endif
 Requires: openldap-clients
 Requires: nss
 Requires: nss-tools
+%if 0%{?fedora} >= 16
+Requires: krb5-server >= 1.9.1-15
+%else
 Requires: krb5-server
+%endif
 Requires: krb5-server-ldap
 Requires: krb5-pkinit-openssl
 Requires: cyrus-sasl-gssapi%{?_isa}
@@ -102,6 +117,11 @@ Requires: python-ldap
 Requires: python-krbV
 Requires: acl
 Requires: python-pyasn1 >= 0.0.9a
+%if 0%{?fedora} >= 16
+Requires: systemd-units >= 36-3
+Requires(pre): systemd-units
+Requires(post): systemd-units
+%endif
 %if 0%{?fedora} >= 15
 Requires: selinux-policy >= 3.9.16-18
 %else
@@ -109,6 +129,12 @@ Requires: selinux-policy >= 3.9.7-27
 %endif
 Requires(post): selinux-policy-base
 Requires: slapi-nis >= 0.21
+%if 0%{?fedora} >= 16
+Requires: pki-ca >= 9.0.15
+Requires: pki-silent >= 9.0.15
+# Only tomcat6 greater than this version provides proper systemd support
+Requires: tomcat6 >= 6.0.32-17
+%else
 %if 0%{?fedora} >= 15
 Requires: pki-ca >= 9.0.15
 Requires: pki-silent >= 9.0.15
@@ -117,13 +143,19 @@ Requires: pki-setup  >= 9.0.15
 Requires: pki-ca >= 9.0.5
 Requires: pki-silent >= 9.0.5
 %endif
+%endif
 Requires: dogtag-pki-common-theme
 Requires: dogtag-pki-ca-theme
 %if 0%{?rhel}
 Requires: subscription-manager
 %endif
+%if 0%{?fedora} >= 16
+Requires(preun): python systemd-units
+Requires(postun): python systemd-units
+%else
 Requires(preun):  python initscripts chkconfig
 Requires(postun): python initscripts chkconfig
+%endif
 
 # We have a soft-requires on bind. It is an optional part of
 # IPA but if it is configured we need a way to require versions
@@ -252,6 +284,9 @@ package.
 %build
 export CFLAGS="$CFLAGS %{optflags}"
 export CPPFLAGS="$CPPFLAGS %{optflags}"
+%if 0%{?fedora} >= 16
+export SUPPORTED_PLATFORM=fedora16
+%endif
 make version-update
 cd ipa-client; ../autogen.sh --prefix=%{_usr} --sysconfdir=%{_sysconfdir} 
--localstatedir=%{_localstatedir} --libdir=%{_libdir} --mandir=%{_mandir}; cd ..
 %if ! %{ONLY_CLIENT}
@@ -313,7 +348,16 @@ mkdir -p %{buildroot}%{_sysconfdir}/httpd/conf.d/
 /bin/touch %{buildroot}%{_sysconfdir}/httpd/conf.d/ipa.conf
 /bin/touch %{buildroot}%{_sysconfdir}/httpd/conf.d/ipa-pki-proxy.conf
 /bin/touch %{buildroot}%{_sysconfdir}/httpd/conf.d/ipa-rewrite.conf
-install -m755 ipa.init %{buildroot}%{_initrddir}/ipa
+%if 0%{?fedora} >= 16
+# Default to systemd initscripts for F16 and above
+mkdir -p %{buildroot}%{_unitdir}
+for i in ipa.service ipa_kpasswd.service ; do
+       install -m 644 init/systemd/$i %{buildroot}%{_unitdir}/$i
+done
+rm -f %{buildroot}%{_initrddir}/ipa_kpasswd
+%else
+install -m755 init/SystemV/ipa.init %{buildroot}%{_initrddir}/ipa
+%endif
 %endif
 
 mkdir -p %{buildroot}%{_sysconfdir}/ipa/
@@ -333,8 +377,14 @@ rm -rf %{buildroot}
 %if ! %{ONLY_CLIENT}
 %post server
 if [ $1 = 1 ]; then
+%if 0%{?fedora} >= 16
+# Use systemd scheme
+    /bin/systemctl --system daemon-reload 2>&1 || :
+%else
+# Use SystemV scheme only before F16
     /sbin/chkconfig --add ipa
     /sbin/chkconfig --add ipa_kpasswd
+%endif
 fi
 if [ $1 -gt 1 ] ; then
     /usr/sbin/ipa-upgradeconfig || :
@@ -343,14 +393,28 @@ fi
 
 %preun server
 if [ $1 = 0 ]; then
+%if 0%{?fedora} >= 16
+# Use systemd scheme
+    /bin/systemctl --quiet stop ipa.service || :
+    /bin/systemctl --quiet disable ipa.service || :
+%else
+# Use SystemV scheme only before F16
     /sbin/chkconfig --del ipa
     /sbin/chkconfig --del ipa_kpasswd
     /sbin/service ipa stop >/dev/null 2>&1 || :
+%endif
 fi
 
 %postun server
 if [ "$1" -ge "1" ]; then
+%if 0%{?fedora} >= 16
+# Use systemd scheme
+    /bin/systemctl --quiet is-active ipa.service >/dev/null && \
+    /bin/systemctl try-restart ipa.service >/dev/null 2>&1 || :
+%else
+# Use SystemV scheme only before F16
     /sbin/service ipa condrestart >/dev/null 2>&1 || :
+%endif
 fi
 
 %pre server-selinux
@@ -419,8 +483,15 @@ fi
 %{_sbindir}/ipa-upgradeconfig
 %{_sbindir}/ipa-compliance
 %{_sysconfdir}/cron.d/ipa-compliance
+%if 0%{?fedora} >= 16
+# Use systemd scheme
+%attr(644,root,root) %{_unitdir}/ipa.service
+%attr(644,root,root) %{_unitdir}/ipa_kpasswd.service
+%else
+# Use SystemV scheme only before F16
 %attr(755,root,root) %{_initrddir}/ipa
 %attr(755,root,root) %{_initrddir}/ipa_kpasswd
+%endif
 %dir %{python_sitelib}/ipaserver
 %{python_sitelib}/ipaserver/*
 %dir %{_usr}/share/ipa
@@ -551,10 +622,12 @@ fi
 %ghost %attr(0644,root,apache) %config(noreplace) 
%{_sysconfdir}/ipa/default.conf
 
 %changelog
+* Mon Oct 10 2011 Alexander Bokovoy <aboko...@redhat.com> - 2.1.1-3
+- Default to systemd for Fedora 16 and onwards
+
 * Fri Oct 7 2011 Adam Young <ayo...@redhat.com> - 2.1.1-2
 - Add explicit dependency on pki-setup.
 
-
 * Mon Sep 12 2011 Alexander Bokovoy <aboko...@redhat.com> - 2.1.1-1
 - Make sure platform adaptation is packaged in -python sub-package
 
diff --git a/ipa.init b/init/SystemV/ipa.init
similarity index 100%
rename from ipa.init
rename to init/SystemV/ipa.init
diff --git a/init/systemd/ipa.service b/init/systemd/ipa.service
new file mode 100644
index 
0000000000000000000000000000000000000000..ba27d1dfd2db24389fc14163a77b262d54d5b5e6
--- /dev/null
+++ b/init/systemd/ipa.service
@@ -0,0 +1,14 @@
+[Unit]
+Description=Identity, Policy, Audit
+Requires=syslog.target network.target
+After=syslog.target network.target
+
+[Service]
+Type=oneshot
+ExecStart=/usr/sbin/ipactl start
+ExecStop=/usr/sbin/ipactl stop
+RemainAfterExit=yes
+TimeoutSec=0
+
+[Install]
+WantedBy=multi-user.target
diff --git a/init/systemd/ipa_kpasswd.service b/init/systemd/ipa_kpasswd.service
new file mode 100644
index 
0000000000000000000000000000000000000000..17aa4633be2e50608909b4fa6091d28a13e57616
--- /dev/null
+++ b/init/systemd/ipa_kpasswd.service
@@ -0,0 +1,10 @@
+[Unit]
+Description=IPA Kerberos password service
+Requires=krb5kdc.service
+Wants=krb5kdc.service
+
+[Service]
+Type=forking
+PIDFile=/var/run/ipa_kpasswd.pid
+ExecStart=/usr/sbin/ipa_kpasswd
+
diff --git a/install/tools/ipactl b/install/tools/ipactl
index 
4055cf91bd6ec6b5a91c0e677ec4c7765c3bff6f..13e4b007ab4081f9d55db40a1471107e02b558d7
 100755
--- a/install/tools/ipactl
+++ b/install/tools/ipactl
@@ -24,7 +24,7 @@ try:
     from ipaserver.install import service
     from ipapython import services as ipaservices
     from ipaserver.install.dsinstance import config_dirname, realm_to_serverid
-    from ipaserver.install.installutils import is_ipa_configured
+    from ipaserver.install.installutils import is_ipa_configured, 
wait_for_open_ports, wait_for_open_socket
     from ipapython import sysrestore
     from ipapython import config
     from ipalib import api, errors
@@ -32,6 +32,7 @@ try:
     import logging
     import ldap
     import ldap.sasl
+    import ldapurl
     import socket
 except ImportError:
     print >> sys.stderr, """\
@@ -117,6 +118,15 @@ def get_config():
     attrs = ['cn', 'ipaConfigString']
 
     try:
+        # systemd services are so fast that we come here before
+        # Directory Server actually starts listening. Wait for
+        # the socket/port be really available.
+        lurl = ldapurl.LDAPUrl(api.env.ldap_uri)
+        if lurl.urlscheme == 'ldapi':
+            wait_for_open_socket(lurl.hostport, timeout=6)
+        else:
+            (host,port) = lurl.hostport.split(':')
+            wait_for_open_ports(host, [port], timeout=6)
         con = ldap.initialize(api.env.ldap_uri)
         con.sasl_interactive_bind_s('', SASL_EXTERNAL)
         res = con.search_st(base,
diff --git a/ipapython/config.py b/ipapython/config.py
index 
051e39f92c8c0a8289c0bfdf8a53ad761c0457f6..4e0fb11b8fac6ed3ce88e0b70eacc3b30046abf5
 100644
--- a/ipapython/config.py
+++ b/ipapython/config.py
@@ -178,7 +178,7 @@ def __discover_config(discover_server = True):
 
         if not config.default_domain:
             #try once with REALM -> domain
-            dom_name = config.default_realm.lower()
+            dom_name = config.default_realm.lower() #pylint: disable=E1103
             name = "_ldap._tcp."+dom_name+"."
             rs = ipapython.dnsclient.query(name, ipapython.dnsclient.DNS_C_IN, 
ipapython.dnsclient.DNS_T_SRV)
             rl = len(rs)
diff --git a/ipapython/ipautil.py b/ipapython/ipautil.py
index 
6e037926ce678557d9273be6ff1e9a6c65d0f80e..49fc64cea7c48d7aaf7e44de3c26d395fddbaa28
 100644
--- a/ipapython/ipautil.py
+++ b/ipapython/ipautil.py
@@ -1185,3 +1185,93 @@ def get_ipa_basedn(conn):
 
     return None
 
+def config_replace_variables(filepath, replacevars=dict(), appendvars=dict()):
+    """
+    Take a key=value based configuration file, and write new version 
+    with certain values replaced or appended 
+
+    All (key,value) pairs from replacevars and appendvars that were not found 
+    in the configuration file, will be added there.
+
+    It is responsibility of a caller to ensure that replacevars and
+    appendvars do not overlap.
+
+    It is responsibility of a caller to back up file.
+
+    returns dictionary of affected keys and their previous values
+
+    One have to run restore_context(filepath) afterwards or
+    security context of the file will not be correct after modification
+    """
+    pattern = re.compile('''
+(^
+                        \s*
+        (?P<option>     [^\#;]+?)
+                        (\s*=\s*)
+        (?P<value>      .+?)?
+                        (\s*((\#|;).*)?)?
+$)''', re.VERBOSE)
+    orig_stat = os.stat(filepath)
+    old_values = dict()
+    temp_filename = None
+    with tempfile.NamedTemporaryFile(delete=False) as new_config:
+        temp_filename = new_config.name
+        with open(filepath, 'r') as f:
+            for line in f:
+                new_line = line
+                m = pattern.match(line)
+                if m:
+                    option, value = m.group('option', 'value')
+                    if option is not None:
+                        if replacevars and option in replacevars:
+                            # replace value completely
+                            new_line = u"%s=%s\n" % (option, 
replacevars[option])
+                            old_values[option] = value
+                        if appendvars and option in appendvars:
+                            # append new value unless it is already existing 
in the original one
+                            if value.find(appendvars[option]) == -1:
+                                new_line = u"%s=%s %s\n" % (option, value, 
appendvars[option])
+                            old_values[option] = value
+                new_config.write(new_line)
+        # Now add all options from replacevars and appendvars that were not 
found in the file
+        new_vars = replacevars.copy()
+        new_vars.update(appendvars)
+        newvars_view = new_vars.viewkeys() - old_values.viewkeys()
+        append_view = (appendvars.viewkeys() - replacevars.viewkeys()) - 
old_values.viewkeys()
+        for item in newvars_view:
+            new_config.write("%s=%s\n" % (item,new_vars[item]))
+        for item in append_view:
+            new_config.write("%s=%s\n" % (item,appendvars[item]))
+        new_config.flush()
+        # Make sure the resulting file is readable by others before installing 
it
+        os.fchmod(new_config.fileno(), orig_stat.st_mode)
+        os.fchown(new_config.fileno(), orig_stat.st_uid, orig_stat.st_gid)
+
+    # At this point new_config is closed but not removed due to 'delete=False' 
above
+    # Now, install the temporary file as configuration and ensure old version 
is available as .orig
+    # While .orig file is not used during uninstall, it is left there for 
administrator.
+    install_file(temp_filename, filepath)
+
+    return old_values
+
+def backup_config_and_replace_variables(fstore, filepath, replacevars=dict(), 
appendvars=dict()):
+    """
+    Take a key=value based configuration file, back up it, and
+    write new version with certain values replaced or appended 
+
+    All (key,value) pairs from replacevars and appendvars that
+    were not found in the configuration file, will be added there.
+
+    It is responsibility of a caller to ensure that replacevars and
+    appendvars do not overlap.
+
+    returns dictionary of affected keys and their previous values
+
+    One have to run restore_context(filepath) afterwards or
+    security context of the file will not be correct after modification
+    """
+    # Backup original filepath
+    fstore.backup_file(filepath)
+    old_values = config_replace_variables(filepath, replacevars, appendvars)
+
+    return old_values
diff --git a/ipapython/platform/base.py b/ipapython/platform/base.py
index 
f9d409972a61ffc730f1313470fb8c09dc90ed97..7e03f4892da8ee7b7c602c83d1eb9cc9aa9bf159
 100644
--- a/ipapython/platform/base.py
+++ b/ipapython/platform/base.py
@@ -22,7 +22,7 @@ from ipalib.plugable import MagicDict
 # set them as in Red Hat distributions. Actual implementation should make them 
available
 # through knownservices.<name> and take care of remapping internally, if needed
 wellknownservices = ['certmonger', 'dirsrv', 'httpd', 'ipa', 'krb5kdc', 
'messagebus',
-                     'nslcd', 'nscd', 'ntpd', 'portmap', 'rpcbind']
+                     'nslcd', 'nscd', 'ntpd', 'portmap', 'rpcbind', 
'ipa_kpasswd']
 
 class AuthConfig(object):
     """
@@ -120,25 +120,25 @@ class PlatformService(object):
     def restart(self, instance_name="", capture_output=True):
         return
 
-    def is_running(self):
+    def is_running(self, instance_name=""):
         return False
 
     def is_installed(self):
         return False
 
-    def is_enabled(self):
+    def is_enabled(self, instance_name=""):
         return False
 
-    def enable(self):
+    def enable(self, instance_name=""):
         return
 
-    def disable(self):
+    def disable(self, instance_name=""):
         return
 
-    def install(self):
+    def install(self, instance_name=""):
         return
 
-    def remove(self):
+    def remove(self, instance_name=""):
         return
 
 class KnownServices(MagicDict):
diff --git a/ipapython/platform/fedora16.py b/ipapython/platform/fedora16.py
new file mode 100644
index 
0000000000000000000000000000000000000000..bad1fac69f589a9786b98fc554d5ba7a114513ee
--- /dev/null
+++ b/ipapython/platform/fedora16.py
@@ -0,0 +1,113 @@
+# Author: Alexander Bokovoy <aboko...@redhat.com>
+#
+# Copyright (C) 2011   Red Hat
+# see file 'COPYING' for use and warranty information
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.    See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+
+from ipapython import ipautil
+from ipapython.platform import base, redhat, systemd
+import os
+
+# All what we allow exporting directly from this module
+# Everything else is made available through these symbols when they directly 
imported into ipapython.services:
+# authconfig -- class reference for platform-specific implementation of 
authconfig(8)
+# service    -- class reference for platform-specific implementation of a 
PlatformService class
+# knownservices -- factory instance to access named services IPA cares about, 
names are ipapython.services.wellknownservices
+# backup_and_replace_hostname -- platform-specific way to set hostname and 
make it persistent over reboots
+# restore_context -- platform-sepcific way to restore security context, if 
applicable
+__all__ = ['authconfig', 'service', 'knownservices', 
'backup_and_replace_hostname', 'restore_context']
+
+# For beginning just remap names to add .service
+# As more services will migrate to systemd, unit names will deviate and
+# mapping will be kept in this dictionary
+system_units = dict(map(lambda x: (x, "%s.service" % (x)), 
base.wellknownservices))
+
+# Rewrite dirsrv and pki-cad services as they support instances via separate 
service generator
+# To make this working, one needs to have both foo@.service and foo.target -- 
the latter is used
+# when request should be coming for all instances (like stop). systemd, 
unfortunately, does not allow
+# to request action for all service instances at once if only foo@.service 
unit is available.
+# To add more, if any of those services need to be started/stopped 
automagically, one needs to manually
+# create symlinks in /etc/systemd/system/foo.target.wants/ (look into 
systemd.py's enable() code).
+system_units['dirsrv'] = 'dirsrv@.service'
+# Our directory server instance for PKI is dirsrv@PKI-IPA.service
+system_units['pkids'] = 'dirsrv@PKI-IPA.service'
+# Our PKI instance is pki-cad@pki-ca.service
+system_units['pki-cad'] = 'pki-cad@pki-ca.service'
+
+class Fedora16Service(systemd.SystemdService):
+    def __init__(self, service_name):
+        if service_name in system_units:
+            service_name = system_units[service_name]
+        else:
+            if len(service_name.split('.')) == 1:
+                # if service_name does not have a dot, it is not foo.service 
and not a foo.target
+                # Thus, not correct service name for systemd, default to 
foo.service style then
+                service_name = "%s.service" % (service_name)
+        super(Fedora16Service, self).__init__(service_name)
+
+# Special handling of directory server service
+# LimitNOFILE needs to be increased or any value set in the directory for this 
value will fail
+# Read /lib/systemd/system/dirsrv@.service for details.
+# We do modification of LimitNOFILE on service.enable() but we also need to 
explicitly enable instances
+# to install proper symlinks as dirsrv.target.wants/ dependencies. 
Unfortunately, ipa-server-install
+# does not do explicit dirsrv.enable() because the service startup is handled 
by ipactl.
+# If we wouldn't do this, our instances will not be started as systemd would 
not have any clue
+# about instances (PKI-IPA and the domain we serve) at all. Thus, hook into 
dirsrv.restart().
+class Fedora16DirectoryService(Fedora16Service):
+    def enable(self, instance_name=""):
+        super(Fedora16DirectoryService, self).enable(instance_name)
+        srv_etc = os.path.join(self.SYSTEMD_ETC_PATH, self.service_name)
+        if os.path.exists(srv_etc):
+            # We need to enable LimitNOFILE=8192 in the dirsrv@.service
+            # We rely on the fact that [Service] section is the last one
+            # and if variable is not there, it will be added as the last line
+            replacevars = {'LimitNOFILE':'8192'}
+            ipautil.config_replace_variables(srv_etc, replacevars=replacevars)
+            redhat.restore_context(srv_etc)
+            ipautil.run(["/bin/systemctl", "--system", 
"daemon-reload"],raiseonerr=False)
+
+    def restart(self, instance_name="", capture_output=True):
+        if len(instance_name) > 0:
+            elements = self.service_name.split("@")
+            srv_etc = os.path.join(self.SYSTEMD_ETC_PATH, self.service_name)
+            srv_tgt = os.path.join(self.SYSTEMD_ETC_PATH, 
self.SYSTEMD_SRV_TARGET % (elements[0]))
+            srv_lnk = os.path.join(srv_tgt, 
self.service_instance(instance_name))
+            if not os.path.exists(srv_etc):
+                self.enable(instance_name)
+            elif not os.path.samefile(srv_etc, srv_lnk):
+                os.unlink(srv_lnk)
+                os.symlink(srv_etc, srv_lnk)
+        super(Fedora16DirectoryService, self).restart(instance_name, 
capture_output=capture_output)
+
+# Redirect directory server service through special sub-class due to its 
special handling of instances
+def f16_service(name):
+    if name == 'dirsrv':
+        return Fedora16DirectoryService(name)
+    return Fedora16Service(name)
+
+class Fedora16Services(base.KnownServices):
+    def __init__(self):
+        services = dict()
+        for s in base.wellknownservices:
+            services[s] = f16_service(s)
+        # Call base class constructor. This will lock services to read-only
+        super(Fedora16Services, self).__init__(services)
+
+authconfig = redhat.authconfig
+service = f16_service
+knownservices = Fedora16Services()
+restore_context = redhat.restore_context
+backup_and_replace_hostname = redhat.backup_and_replace_hostname
diff --git a/ipapython/platform/redhat.py b/ipapython/platform/redhat.py
index 
6bf8bf348a4c30c79ad29d8b2b30a088bd28372d..d9de3abca0c3281850143c0fe23070b89a29a8f1
 100644
--- a/ipapython/platform/redhat.py
+++ b/ipapython/platform/redhat.py
@@ -65,20 +65,20 @@ class RedHatService(base.PlatformService):
                 installed = False
         return installed
 
-    def is_enabled(self):
+    def is_enabled(self, instance_name=""):
         (stdout, stderr, returncode) = ipautil.run(["/sbin/chkconfig", 
self.service_name],raiseonerr=False)
         return (returncode == 0)
 
-    def enable(self):
+    def enable(self, instance_name=""):
         ipautil.run(["/sbin/chkconfig", self.service_name, "on"])
 
-    def disable(self):
+    def disable(self, instance_name=""):
         ipautil.run(["/sbin/chkconfig", self.service_name, "off"])
 
-    def install(self):
+    def install(self, instance_name=""):
         ipautil.run(["/sbin/chkconfig", "--add", self.service_name])
 
-    def remove(self):
+    def remove(self, instance_name=""):
         ipautil.run(["/sbin/chkconfig", "--del", self.service_name])
 
 class RedHatAuthConfig(base.AuthConfig):
@@ -133,48 +133,11 @@ def restore_context(filepath):
     ipautil.run(["/sbin/restorecon", filepath], raiseonerr=False)
 
 def backup_and_replace_hostname(fstore, statestore, hostname):
-    network_filename = "/etc/sysconfig/network"
-    # Backup original /etc/sysconfig/network
-    fstore.backup_file(network_filename)
-    hostname_pattern = re.compile('''
-(^
-                        \s*
-        (?P<option>     [^\#;]+?)
-                        (\s*=\s*)
-        (?P<value>      .+?)?
-                        (\s*((\#|;).*)?)?
-$)''', re.VERBOSE)
-    temp_filename = None
-    with tempfile.NamedTemporaryFile(delete=False) as new_config:
-        temp_filename = new_config.name
-        with open(network_filename, 'r') as f:
-            for line in f:
-                new_line = line
-                m = hostname_pattern.match(line)
-                if m:
-                    option, value = m.group('option', 'value')
-                    if option is not None and option == 'HOSTNAME':
-                        if value is not None and hostname != value:
-                            new_line = u"HOSTNAME=%s\n" % (hostname)
-                            statestore.backup_state('network', 'hostname', 
value)
-                new_config.write(new_line)
-        new_config.flush()
-        # Make sure the resulting file is readable by others before installing 
it
-        os.fchmod(new_config.fileno(), stat.S_IRUSR | stat.S_IWUSR | 
stat.S_IRGRP | stat.S_IROTH)
-        os.fchown(new_config.fileno(), 0, 0)
-
-    # At this point new_config is closed but not removed due to 'delete=False' 
above
-    # Now, install the temporary file as configuration and ensure old version 
is available as .orig
-    # While .orig file is not used during uninstall, it is left there for 
administrator.
-    ipautil.install_file(temp_filename, network_filename)
-    try:
-        ipautil.run(['/bin/hostname', hostname])
-    except ipautil.CalledProcessError, e:
-        print >>sys.stderr, "Failed to set this machine hostname to %s (%s)." 
% (hostname, str(e))
-
-    # For SE Linux environments it is important to reset SE labels to the 
expected ones
-    try:
-        restore_context(network_filename)
-    except ipautil.CalledProcessError, e:
-        print >>sys.stderr, "Failed to set permissions for %s (%s)." % 
(network_filename, str(e))
+    replacevars = {'HOSTNAME':hostname}
+    old_values = ipautil.backup_config_and_replace_variables(fstore,
+                                                          
"/etc/sysconfig/network", 
+                                                          
replacevars=replacevars)
+    restore_context("/etc/sysconfig/network")
+    if old_values['HOSTNAME']:
+        statestore.backup_state('network', 'hostname', old_values['HOSTNAME'])
 
diff --git a/ipapython/platform/systemd.py b/ipapython/platform/systemd.py
new file mode 100644
index 
0000000000000000000000000000000000000000..e9990ab38fc764fd2a09d07335d86a9e4e981358
--- /dev/null
+++ b/ipapython/platform/systemd.py
@@ -0,0 +1,204 @@
+# Author: Alexander Bokovoy <aboko...@redhat.com>
+#
+# Copyright (C) 2011   Red Hat
+# see file 'COPYING' for use and warranty information
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.    See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+
+from ipapython import ipautil
+from ipapython.platform import base
+import sys, os, shutil
+
+class SystemdService(base.PlatformService):
+    SYSTEMD_ETC_PATH = "/etc/systemd/system/"
+    SYSTEMD_LIB_PATH = "/lib/systemd/system/"
+    SYSTEMD_SRV_TARGET = "%s.target.wants"
+
+    def __init__(self, service_name):
+        super(SystemdService, self).__init__(service_name)
+        self.lib_path = os.path.join(self.SYSTEMD_LIB_PATH, self.service_name)
+        self.lib_path_exists = None
+
+    def service_instance(self, instance_name):
+        if self.lib_path_exists is None:
+            self.lib_path_exists = os.path.exists(self.lib_path)
+
+        elements = self.service_name.split("@")
+
+        # Short-cut: if there is already exact service name, return it
+        if self.lib_path_exists and len(instance_name) == 0:
+            if len(elements) == 1:
+                # service name is like pki-cad.target or krb5kdc.service
+                return self.service_name
+            if len(elements) > 1 and elements[1][0] != '.':
+                # Service name is like pki-cad@pki-ca.service and that file 
exists
+                return self.service_name
+
+        if len(elements) > 1:
+            # We have dynamic service
+            if len(instance_name) > 0:
+                # Instanciate dynamic service
+                return "%s@%s.service" % (elements[0], instance_name)
+            else:
+                # No instance name, try with target
+                tgt_name = "%s.target" % (elements[0])
+                srv_lib = os.path.join(self.SYSTEMD_LIB_PATH, tgt_name)
+                if os.path.exists(srv_lib):
+                    return tgt_name
+
+        return self.service_name
+
+    def parse_variables(self, text, separator=None):
+        """
+        Parses 'systemctl show' output and returns a dict[variable]=value
+        Arguments: text -- 'systemctl show' output as string
+                   separator -- optional (defaults to None), what separates 
the key/value pairs in the text
+        """
+        def splitter(x, separator=None):
+            if len(x) > 1:
+                y = x.split(separator)
+                return (y[0], y[-1])
+            return (None,None)
+        return dict(map(lambda x: splitter(x, separator=separator), 
text.split("\n")))
+
+    def stop(self, instance_name="", capture_output=True):
+        ipautil.run(["/bin/systemctl", "stop", 
self.service_instance(instance_name)], capture_output=capture_output)
+
+    def start(self, instance_name="", capture_output=True):
+        ipautil.run(["/bin/systemctl", "start", 
self.service_instance(instance_name)], capture_output=capture_output)
+
+    def restart(self, instance_name="", capture_output=True):
+        # Restart command is broken before systemd-36-3.fc16
+        # If you have older systemd version, restart of dependent services 
will hang systemd indefinetly
+        ipautil.run(["/bin/systemctl", "restart", 
self.service_instance(instance_name)], capture_output=capture_output)
+
+    def is_running(self, instance_name=""):
+        ret = True
+        try:
+            (sout, serr, rcode) = ipautil.run(["/bin/systemctl", "is-active", 
self.service_instance(instance_name)],capture_output=True)
+            if rcode != 0:
+                ret = False
+        except ipautil.CalledProcessError:
+                ret = False
+        return ret
+
+    def is_installed(self):
+        installed = True
+        try:
+            (sout,serr,rcode) = ipautil.run(["/bin/systemctl", 
"list-unit-files", "--full"])
+            if rcode != 0:
+                installed = False
+            else:
+                svar = self.parse_variables(sout)
+                if not self.service_instance("") in svar:
+                    # systemd doesn't show the service
+                    installed = False
+        except ipautil.CalledProcessError, e:
+                installed = False
+        return installed
+
+    def is_enabled(self, instance_name=""):
+        enabled = True
+        try:
+            (sout,serr,rcode) = ipautil.run(["/bin/systemctl", "is-enabled", 
self.service_instance(instance_name)])
+            if rcode != 0:
+                enabled = False
+        except ipautil.CalledProcessError, e:
+                enabled = False
+        return enabled
+
+    def enable(self, instance_name=""):
+        if self.lib_path_exists is None:
+            self.lib_path_exists = os.path.exists(self.lib_path)
+        elements = self.service_name.split("@")
+        l = len(elements)
+
+        if self.lib_path_exists and (l > 1 and elements[1][0] != '.'):
+            # There is explicit service unit supporting this instance, follow 
normal systemd enabler
+            self.__enable(instance_name)
+            return
+
+        if self.lib_path_exists and (l == 1):
+            # There is explicit service unit which does not support the 
instances, ignore instance
+            self.__enable()
+            return
+
+        if len(instance_name) > 0 and l > 1:
+            # New instance, we need to do following:
+            # 1. Copy <service>@.service to /etc/systemd/system/ if it is not 
there
+            # 2. Make /etc/systemd/system/<service>.target.wants/ if it is not 
there
+            # 3. Link 
/etc/systemd/system/<service>.target.wants/<service>@<instance_name>.service to
+            #    /etc/systemd/system/<service>@.service
+            srv_etc = os.path.join(self.SYSTEMD_ETC_PATH, self.service_name)
+            srv_tgt = os.path.join(self.SYSTEMD_ETC_PATH, 
self.SYSTEMD_SRV_TARGET % (elements[0]))
+            srv_lnk = os.path.join(srv_tgt, 
self.service_instance(instance_name))
+            try:
+                if not ipautil.file_exists(srv_etc):
+                    shutil.copy(self.lib_path, srv_etc)
+                if not ipautil.dir_exists(srv_tgt):
+                    os.mkdir(srv_tgt)
+                if os.path.exists(srv_lnk):
+                    # Remove old link
+                    os.unlink(srv_lnk)
+                if not os.path.exists(srv_lnk):
+                    # object does not exist _or_ is a broken link
+                    if not os.path.islink(srv_lnk):
+                        # if it truly does not exist, make a link
+                        os.symlink(srv_etc, srv_lnk)
+                    else:
+                        # Link exists and it is broken, make new one
+                        os.unlink(srv_lnk)
+                        os.symlink(srv_etc, srv_lnk)
+                ipautil.run(["/bin/systemctl", "--system", "daemon-reload"])
+            except:
+                pass
+        else:
+            self.__enable(instance_name)
+
+    def disable(self, instance_name=""):
+        elements = self.service_name.split("@")
+        if instance_name != "" and len(elements) > 1:
+            # Remove instance, we need to do following:
+            #  Remove link from 
/etc/systemd/system/<service>.target.wants/<service>@<instance_name>.service 
+            #  to /etc/systemd/system/<service>@.service
+            srv_tgt = os.path.join(self.SYSTEMD_ETC_PATH, 
self.SYSTEMD_SRV_TARGET % (elements[0]))
+            srv_lnk = os.path.join(srv_tgt, 
self.service_instance(instance_name))
+            try:
+                if ipautil.dir_exists(srv_tgt):
+                    if os.path.islink(srv_lnk):
+                        os.unlink(srv_lnk)
+                ipautil.run(["/bin/systemctl", "--system", "daemon-reload"])
+            except:
+                pass
+        else:
+            self.__disable(instance_name)
+
+    def __enable(self, instance_name=""):
+        try:
+            ipautil.run(["/bin/systemctl", "enable", 
self.service_instance(instance_name)])
+        except ipautil.CalledProcessError, e:
+            pass
+
+    def __disable(self, instance_name=""):
+        try:
+            ipautil.run(["/bin/systemctl", "disable", 
self.service_instance(instance_name)])
+        except ipautil.CalledProcessError, e:
+            pass
+
+    def install(self):
+        self.enable()
+
+    def remove(self):
+        self.disable()
diff --git a/ipaserver/install/cainstance.py b/ipaserver/install/cainstance.py
index 
c819957a6dc225e1fd1b08642ca90a614e9d09c1..fed4b2cdf373aa2266cf730de0dc622b0c25ba0c
 100644
--- a/ipaserver/install/cainstance.py
+++ b/ipaserver/install/cainstance.py
@@ -375,7 +375,7 @@ class CADSInstance(service.Service):
     def restart_instance(self):
         try:
             ipaservices.knownservices.dirsrv.restart(self.serverid)
-            if not dsinstance.is_ds_running():
+            if not dsinstance.is_ds_running(self.serverid):
                 logging.critical("Failed to restart the directory server. See 
the installation log for details.")
                 sys.exit(1)
         except Exception:
@@ -693,7 +693,7 @@ class CAInstance(service.Service):
 
     def __restart_instance(self):
         try:
-            self.restart()
+            self.restart(PKI_INSTANCE_NAME)
             installutils.wait_for_open_ports('localhost', 9180, 300)
         except Exception:
             # TODO: roll back here?
diff --git a/ipaserver/install/dsinstance.py b/ipaserver/install/dsinstance.py
index 
cd2a216555c735f484303a9cfb49105287f017a1..e71de62260d5320fe3d9eeb306c4393169370250
 100644
--- a/ipaserver/install/dsinstance.py
+++ b/ipaserver/install/dsinstance.py
@@ -107,8 +107,8 @@ def check_ports():
     ds_secure = installutils.port_available(636)
     return (ds_unsecure, ds_secure)
 
-def is_ds_running():
-    return ipaservices.knownservices.dirsrv.is_running()
+def is_ds_running(server_id=''):
+    return ipaservices.knownservices.dirsrv.is_running(instance_name=server_id)
 
 def has_managed_entries(host_name, dm_password):
     """Check to see if the Managed Entries plugin is available"""
@@ -411,7 +411,7 @@ class DsInstance(service.Service):
     def restart(self, instance=''):
         try:
             super(DsInstance, self).restart(instance)
-            if not is_ds_running():
+            if not is_ds_running(instance):
                 logging.critical("Failed to restart the directory server. See 
the installation log for details.")
                 sys.exit(1)
             installutils.wait_for_open_ports('localhost', self.open_ports, 300)
diff --git a/ipaserver/install/krbinstance.py b/ipaserver/install/krbinstance.py
index 
513dc5523589341cbcebbe1a80694e7eae6c4308..ad89e87d67c2f581836bd8dbbef530492325e394
 100644
--- a/ipaserver/install/krbinstance.py
+++ b/ipaserver/install/krbinstance.py
@@ -352,28 +352,16 @@ class KrbInstance(service.Service):
             min = version.LooseVersion(MIN_KRB5KDC_WITH_WORKERS)
             if ver >= min:
                 workers = True
+        # Write down config file
+        # We write realm and also number of workers (for multi-CPU systems)
+        replacevars = {'KRB5REALM':self.realm}
+        appendvars = {}
         if workers and cpus > 1:
-            #read in memory, find KRB5KDC_ARGS, check/change it, then 
overwrite file
-            self.fstore.backup_file("/etc/sysconfig/krb5kdc")
-
-            need_w = True
-            fd = open("/etc/sysconfig/krb5kdc", "r")
-            lines = fd.readlines()
-            fd.close()
-            for line in lines:
-                sline = line.strip()
-                if not sline.startswith('KRB5KDC_ARGS'):
-                    continue
-                sline = sline.replace('"', '')
-                if sline.find("-w") != -1:
-                    need_w = False
-
-            if need_w:
-                fd = open("/etc/sysconfig/krb5kdc", "w")
-                for line in lines:
-                    fd.write(line)
-                fd.write('KRB5KDC_ARGS="${KRB5KDC_ARGS} -w %s"\n' % str(cpus))
-                fd.close()
+            appendvars = {'KRB5KDC_ARGS': "-w %s" % str(cpus)}
+        ipautil.backup_config_and_replace_variables(self.fstore, 
"/etc/sysconfig/krb5kdc",
+                                                    replacevars=replacevars,
+                                                    appendvars=appendvars)
+        ipaservices.restore_context("/etc/sysconfig/krb5kdc")
 
     def __write_stash_from_ds(self):
         try:
-- 
1.7.6.4

_______________________________________________
Freeipa-devel mailing list
Freeipa-devel@redhat.com
https://www.redhat.com/mailman/listinfo/freeipa-devel

Reply via email to