github.com/ubuntu-core/snappy@v0.0.0-20210827154228-9e584df982bb/systemd/sdnotify.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2017 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package systemd
    21  
    22  import (
    23  	"fmt"
    24  	"net"
    25  	"os"
    26  	"strings"
    27  )
    28  
    29  var osGetenv = os.Getenv
    30  
    31  // SdNotify sends the given state string notification to systemd.
    32  //
    33  // inspired by libsystemd/sd-daemon/sd-daemon.c from the systemd source
    34  func SdNotify(notifyState string) error {
    35  	if notifyState == "" {
    36  		return fmt.Errorf("cannot use empty notify state")
    37  	}
    38  
    39  	notifySocket := osGetenv("NOTIFY_SOCKET")
    40  	if notifySocket == "" {
    41  		return fmt.Errorf("cannot find NOTIFY_SOCKET environment")
    42  	}
    43  	if !strings.HasPrefix(notifySocket, "@") && !strings.HasPrefix(notifySocket, "/") {
    44  		return fmt.Errorf("cannot use NOTIFY_SOCKET %q", notifySocket)
    45  	}
    46  
    47  	raddr := &net.UnixAddr{
    48  		Name: notifySocket,
    49  		Net:  "unixgram",
    50  	}
    51  	conn, err := net.DialUnix("unixgram", nil, raddr)
    52  	if err != nil {
    53  		return err
    54  	}
    55  	defer conn.Close()
    56  
    57  	_, err = conn.Write([]byte(notifyState))
    58  	return err
    59  }