All Projects → takama → Daemon

takama / Daemon

Licence: mit
A daemon package for use with Go (golang) services

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to Daemon

service-systemd
Setup a node.js app as systemd service.
Stars: ✭ 35 (-97.97%)
Mutual labels:  service, daemon
Logmonitor
Monitoring log files on windows systems.
Stars: ✭ 23 (-98.66%)
Mutual labels:  service, daemon
Ipmonitor
IP Monitor is a simple application which monitors your public IP address for changes and lets you set different kinds of notifications such as email, audio, pop up or executing a command
Stars: ✭ 28 (-98.37%)
Mutual labels:  service, daemon
Nginx Haskell Module
Nginx module for binding Haskell code in configuration files for great good!
Stars: ✭ 99 (-94.24%)
Mutual labels:  service
Ehealth.api
Index page and integration layer for projects that related to Ukrainian Health Services government institution
Stars: ✭ 103 (-94.01%)
Mutual labels:  service
Cli
Get a programmable email address. Automate what happens when you receive emails. It's like Zapier for devs who hate emails.
Stars: ✭ 105 (-93.9%)
Mutual labels:  daemon
Tinypart
TinyPart is an iOS modularization framework implemented by Ojective-C. It also supports URL-routing and inter-module communication. TinyPart是一个由Objective-C编写的面向协议的iOS模块化框架,同时它还支持URL路由和模块间通信机制。
Stars: ✭ 120 (-93.02%)
Mutual labels:  service
Flying Pigeon
flying-pigeon 是一个IPC 跨进程通信组件,底层是匿名内存+Binder , 突破1MB大小限制,无需写AIDL文件,让实现跨进程通信就像写一个接口一样简单
Stars: ✭ 97 (-94.36%)
Mutual labels:  service
Bitwrk
Bitcoin-fueled Peer-to-Peer Blender Rendering (and more)
Stars: ✭ 114 (-93.37%)
Mutual labels:  service
Now Go
Create tinyurl/redirection service with ease.
Stars: ✭ 107 (-93.78%)
Mutual labels:  service
Pwa Cookbook
personally website
Stars: ✭ 107 (-93.78%)
Mutual labels:  service
Rabbitmq Supervisor Bundle
Symfony bundle to automatically create and update supervisor configurations for RabbitMQ consumer daemons
Stars: ✭ 103 (-94.01%)
Mutual labels:  daemon
Samples
Community driven repository for Dapr samples
Stars: ✭ 104 (-93.95%)
Mutual labels:  service
Freeradius Server
FreeRADIUS - A multi-protocol policy server.
Stars: ✭ 1,379 (-19.83%)
Mutual labels:  daemon
Chaos
Proof of concept, general purpose pastejacker for GNU/Linux
Stars: ✭ 115 (-93.31%)
Mutual labels:  daemon
Voipussd
📞 IMEI (USSD) Library on Android Devices by @romellfudi
Stars: ✭ 97 (-94.36%)
Mutual labels:  service
Dapr Demos
Collection of personal Dapr demos (bindings, state, pub/sub, service-to-service invocation)
Stars: ✭ 109 (-93.66%)
Mutual labels:  service
Murano
Application Catalog for OpenStack. Mirror of code maintained at opendev.org.
Stars: ✭ 106 (-93.84%)
Mutual labels:  service
Bolt
⚡🐧 - Thunderbolt 3 device manager | This is a MIRROR of bolt from fd.o
Stars: ✭ 106 (-93.84%)
Mutual labels:  daemon
Httpbin
HTTP Request & Response Service, written in Python + Flask.
Stars: ✭ 10,423 (+505.99%)
Mutual labels:  service

Go Daemon

A daemon package for use with Go (golang) services

GoDoc

Examples

Simplest example (just install self as daemon)

package main

import (
    "fmt"
    "log"

    "github.com/takama/daemon"
)

func main() {
    service, err := daemon.New("name", "description", daemon.SystemDaemon)
    if err != nil {
        log.Fatal("Error: ", err)
    }
    status, err := service.Install()
    if err != nil {
        log.Fatal(status, "\nError: ", err)
    }
    fmt.Println(status)
}

Real example

// Example of a daemon with echo service
package main

import (
    "fmt"
    "log"
    "net"
    "os"
    "os/signal"
    "syscall"

    "github.com/takama/daemon"
)

const (

    // name of the service
    name        = "myservice"
    description = "My Echo Service"

    // port which daemon should be listen
    port = ":9977"
)

//    dependencies that are NOT required by the service, but might be used
var dependencies = []string{"dummy.service"}

var stdlog, errlog *log.Logger

// Service has embedded daemon
type Service struct {
    daemon.Daemon
}

// Manage by daemon commands or run the daemon
func (service *Service) Manage() (string, error) {

    usage := "Usage: myservice install | remove | start | stop | status"

    // if received any kind of command, do it
    if len(os.Args) > 1 {
        command := os.Args[1]
        switch command {
        case "install":
            return service.Install()
        case "remove":
            return service.Remove()
        case "start":
            return service.Start()
        case "stop":
            return service.Stop()
        case "status":
            return service.Status()
        default:
            return usage, nil
        }
    }

    // Do something, call your goroutines, etc

    // Set up channel on which to send signal notifications.
    // We must use a buffered channel or risk missing the signal
    // if we're not ready to receive when the signal is sent.
    interrupt := make(chan os.Signal, 1)
    signal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM)

    // Set up listener for defined host and port
    listener, err := net.Listen("tcp", port)
    if err != nil {
        return "Possibly was a problem with the port binding", err
    }

    // set up channel on which to send accepted connections
    listen := make(chan net.Conn, 100)
    go acceptConnection(listener, listen)

    // loop work cycle with accept connections or interrupt
    // by system signal
    for {
        select {
        case conn := <-listen:
            go handleClient(conn)
        case killSignal := <-interrupt:
            stdlog.Println("Got signal:", killSignal)
            stdlog.Println("Stoping listening on ", listener.Addr())
            listener.Close()
            if killSignal == os.Interrupt {
                return "Daemon was interruped by system signal", nil
            }
            return "Daemon was killed", nil
        }
    }

    // never happen, but need to complete code
    return usage, nil
}

// Accept a client connection and collect it in a channel
func acceptConnection(listener net.Listener, listen chan<- net.Conn) {
    for {
        conn, err := listener.Accept()
        if err != nil {
            continue
        }
        listen <- conn
    }
}

func handleClient(client net.Conn) {
    for {
        buf := make([]byte, 4096)
        numbytes, err := client.Read(buf)
        if numbytes == 0 || err != nil {
            return
        }
        client.Write(buf[:numbytes])
    }
}

func init() {
    stdlog = log.New(os.Stdout, "", log.Ldate|log.Ltime)
    errlog = log.New(os.Stderr, "", log.Ldate|log.Ltime)
}

func main() {
    srv, err := daemon.New(name, description, daemon.SystemDaemon, dependencies...)
    if err != nil {
        errlog.Println("Error: ", err)
        os.Exit(1)
    }
    service := &Service{srv}
    status, err := service.Manage()
    if err != nil {
        errlog.Println(status, "\nError: ", err)
        os.Exit(1)
    }
    fmt.Println(status)
}

Service config file

Optionally, service config file can be retrieved or updated by calling GetTemplate() string and SetTemplate(string) methods(except MS Windows). Template will be a default Go Template("text/template").

If SetTemplate is not called, default template content will be used while creating service.

Variable Description
Description Description for service
Dependencies Service dependencies
Name Service name
Path Path of service executable
Args Arguments for service executable

Example template(for linux systemv)

[Unit]
Description={{.Description}}
Requires={{.Dependencies}}
After={{.Dependencies}}

[Service]
PIDFile=/var/run/{{.Name}}.pid
ExecStartPre=/bin/rm -f /var/run/{{.Name}}.pid
ExecStart={{.Path}} {{.Args}}
Restart=on-failure

[Install]
WantedBy=multi-user.target

Cron example

See examples/cron/cron_job.go

Contributors (unsorted)

All the contributors are welcome. If you would like to be the contributor please accept some rules.

  • The pull requests will be accepted only in develop branch
  • All modifications or additions should be tested
  • Sorry, We will not accept code with any dependency, only standard library

Thank you for your understanding!

License

MIT Public License

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].