Search code examples
rhelrpm-specsystemctl

systemctl start service does not work in SPEC file


I met a problem that the command "sudo systemctl start xxx.service" in my SPEC file does not work when upgrading my RPM package, following is my %post script in SPEC file,

%post
echo "---------------------------- post $1 -------------------------------"
# refresh installation
if [ $1 == 1 ]; then
  sudo echo "Installation finished."
# upgrade installation
elif [ $1 -gt 1 ]; then
  sudo echo "Starting service xxx.service..."
  sudo /usr/bin/systemctl enable xxx.service > /dev/null 2>&1
  sudo /usr/bin/systemctl start xxx.service
  sleep 10
  sudo echo "Finished."
fi
exit 0

I'm sure that the service file already exists in directory /usr/lib/systemd/system, and I can start it manually using the command "sudo systemctl start xxx.service".

And I found that the "sleep 10" command does not work too.

Very appreciated if there is any suggestion about this issue, thanks.


Solution

  • Few issues:

    • You're not supposed to use sudo in scriplets, because 1) it may not be installed 2) rpm installation runs as superuser anyway
    • You should use the standard RPM macros for SystemD as opposed to reinventing the wheel.

    Essentially that simply goes down to:

    %{?systemd_requires}
    BuildRequires: systemd
    
    # ...
    
    %post
    %systemd_post %{name}.service
    
    %preun
    %systemd_preun %{name}.service
    
    %postun
    %systemd_postun_with_restart %{name}.service
    
    # ...
    

    Take note that the SystemD macros for CentOS/RHEL are within systemd package, while in Fedora they are now in systemd-rpm-macros.