phoenix

package module
v0.0.0-...-8c65e16 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2016 License: BSD-3-Clause Imports: 19 Imported by: 1

README

Phoenix

GoDoc Build Status

Introduction

Package phoenix provides runtime support for long running server processes.

In particular, it provides standardized mechanisms for handling logging, configuration, and HTTP server startup, as well as profiling support.

Additionally, lifecycle management facilities for application services which should respond to server state changes are provided, as are a full suite of signal handling functionality, including configuration reload on SIGHUP.

Usage

Import into your workspace via go get:

go get github.com/strukturag/phoenix

And then use in your application as follows:

package main

import (
    "flag"
	"fmt"
    "net/http"
    "os"

    "github.com/strukturag/phoenix"
)

var version = "unreleased"
var defaultConfig = "./server.conf"

func boot() error {
	configPath := flag.String("c", defaultConfig, "Configuration file.")
	logPath := flag.String("l", "", "Log file, defaults to stderr.")
	showVersion := flag.Bool("v", false, "Display version number and exit.")
    memprofile := flag.String("memprofile", "", "Write memory profile to this file.")
    cpuprofile := flag.String("cpuprofile", "", "Write cpu profile to file.")
	showHelp := flag.Bool("h", false, "Show this usage information and exit.")
	flag.Parse()

	if *showHelp {
		flag.Usage()
		return nil
	} else if *showVersion {
		fmt.Printf("Version %s\n", version)
		return nil
	}

	return phoenix.NewServer("myapp", version).
		Config(configPath).
		Log(logPath).
		CpuProfile(cpuprofile).
		MemProfile(memprofile).
		Run(func(runtime phoenix.Runtime) error {
            runtime.DefaultHTTPHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				w.Header().Set("Content-Type", "text/plain")
                if _, err := w.Write([]byte("Hello again, phoenix!\n")); err != nil {
					runtime.Printf("Failed to write response: %v", err)
				}
            }))

            return runtime.Start()
        })
}

func main() {
   if err := boot(); err != nil {
       os.Exit(-1)
   }
}

License

This package is licensed by struktur AG under the 3-clause BSD license, see LICENSE for more details.

Documentation

Overview

Package phoenix provides runtime support for long running server processes.

In particular, it provides standardized mechanisms for handling logging, configuration, and HTTP server startup, as well as profiling support.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config interface {
	HasSection(section string) bool
	GetSections() []string
	GetOptions(section string) ([]string, error)
	HasOption(section, option string) bool
	GetBool(section, option string) (bool, error)
	GetBoolDefault(section, option string, dflt bool) bool
	GetInt(section, option string) (int, error)
	GetIntDefault(section, option string, dflt int) int
	GetFloat64(section, option string) (float64, error)
	GetFloat64Default(section, option string, dflt float64) float64
	GetString(section, option string) (string, error)
	GetStringDefault(section, option, dflt string) string
}

Config provides read access to the application's configuration.

GetXXXDefault methods return dflt if the named option in section has no value. Use HasOption to determine the status of an option thus defaulted.

type ConfigUpdater

type ConfigUpdater interface {
	Config
	Update(map[string]map[string]string) error
}

ConfigUpdater provides access to the applications's configuration and allows to update it.

Update method takes a string mapping like [section][option]=value. Sections are automatically created as needed and existing values are overwritten.

type Container

type Container interface {
	ConfigUpdater
	Logger
	Metadata
}

Container provides access to system data, configuration, and logging.

Typically subinterfaces should be used when possible.

type Logger

type Logger interface {
	Print(...interface{})
	Printf(string, ...interface{})
}

Logger provides a log-only interface to the application Logger.

Presently only methods for logging at the default (debug) level are provided, this may change in the future.

type Metadata

type Metadata interface {
	// Name returns the the configured application name,
	// or "app" if none was set.
	Name() string

	// Version returns the configured version string,
	// or "unreleased" if no version string was provided.
	Version() string
}

Metadata provides access to application information such as name and version.

type Reloadable

type Reloadable interface {
	// Reload will be called when the server's configuration has been reloaded.
	//
	// If any reloadable service returns an error, the server will be stopped.
	Reload() error
}

Reloadable should be implemented by services which wish to respond to configuration reload requests.

type RunFunc

type RunFunc func(Runtime) error

RunFunc is the completion callback for server setup.

type Runtime

type Runtime interface {
	Container

	// Service specifies a Service to be managed by this runtime.
	Service(Service)

	// DefaultHTTPHandler specifies a handler which will be run
	// using the default HTTP server configuration.
	//
	// The results of calling this method after Start() has been
	// called are undefined.
	DefaultHTTPHandler(http.Handler)

	// DefaultHTTPSHandler specifies a handler which will be run
	// using the default HTTPS server configuration.
	//
	// The results of calling this method after Start() has been
	// called are undefined.
	DefaultHTTPSHandler(http.Handler)

	// TLSConfig returns the current tls.Config used with HTTPS servers
	// If no tls.Config is set, it is created using the options provided in
	// configuration. Modifications to the tls.Config the tls.Config are
	// propagated to existing HTTPS servers.
	//
	// Results of modifying the tls.Config after Start() has been called are
	// undefined.
	TLSConfig() (*tls.Config, error)

	// SetTLSConfig applies a given tls.Config to the runtime. It
	// will be used with all HTTPS servers created after SetTLSConfig
	// was called.
	SetTLSConfig(*tls.Config)

	// Start runs all registered servers and blocks until they terminate.
	Start() error
}

Runtime provides application runtime support and server process launch functionality.

type Server

type Server interface {
	// DefaultOption sets the default value of the named option in the given
	// section.
	DefaultOption(section, option, value string) Server

	// OverrideOption forces the named option in the given section
	// to have the given value regardless of it's state in the
	// config file.
	OverrideOption(section, option, value string) Server

	// Config sets the path to the application's main config file.
	Config(path *string) Server

	// DefaultConfig sets the path to the application's default config file.
	DefaultConfig(path *string) Server

	// OverrideConfig sets the path to the application's override config file.
	OverrideConfig(path *string) Server

	// Log sets the path to the application's logfile. Defaults to stderr if unset.
	Log(path *string) Server

	// CpuProfile runs the application with CPU profiling enabled,
	// writing the results to path.
	CpuProfile(path *string) Server

	// MemProfile runs the application with memory profiling enabled,
	// writing the results to path.
	MemProfile(path *string) Server

	// Run initializes a Runtime instance and provides it to the runner callback,
	// returning any errors produced by the callback.
	//
	// Any errors resulting from loading the configuration or opening the log
	// will be returned without calling runner.
	Run(runner RunFunc) error

	// Stop forcibly halts the running instance.
	Stop() error
}

Server provides pre-startup configuration and application boot functionality.

func NewServer

func NewServer(name, version string) Server

NewServer creates a Server instance with the given name and version string.

type Service

type Service interface {
	// Start runs the main loop of the Service. It is expected to block until
	// Stop is called or the execution of the service is complete.
	//
	// Undefined behavior will result if errors are returned during shutdown,
	// such errors shall be returned by Stop.
	Start() error

	// Stop shall terminate execution of Start and may return any errors
	// reported by cleanup of resources used by the Service.
	Stop() error
}

Service represents a resource whose lifecycle should be managed by a Runtime.

Typically this would be an exclusive resource such as a socket, database file, or shared memory segment.

type StartHandler

type StartHandler interface {
	// OnStart receives the current container, and may return an error to cancel
	// startup.
	OnStart(Container) error
}

StartHandler may be implemented by services which wish to be notified prior to being started.

type StopHandler

type StopHandler interface {
	OnStop(Container)
}

StopHandler may be implemented by services which wish to be notified after they stop.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL