github.com/safing/portbase@v0.19.5/api/main.go (about)

     1  package api
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"flag"
     7  	"os"
     8  	"time"
     9  
    10  	"github.com/safing/portbase/modules"
    11  )
    12  
    13  var (
    14  	module *modules.Module
    15  
    16  	exportEndpoints bool
    17  )
    18  
    19  // API Errors.
    20  var (
    21  	ErrAuthenticationAlreadySet = errors.New("the authentication function has already been set")
    22  	ErrAuthenticationImmutable  = errors.New("the authentication function can only be set before the api has started")
    23  )
    24  
    25  func init() {
    26  	module = modules.Register("api", prep, start, stop, "database", "config")
    27  
    28  	flag.BoolVar(&exportEndpoints, "export-api-endpoints", false, "export api endpoint registry and exit")
    29  }
    30  
    31  func prep() error {
    32  	if exportEndpoints {
    33  		modules.SetCmdLineOperation(exportEndpointsCmd)
    34  	}
    35  
    36  	if getDefaultListenAddress() == "" {
    37  		return errors.New("no default listen address for api available")
    38  	}
    39  
    40  	if err := registerConfig(); err != nil {
    41  		return err
    42  	}
    43  
    44  	if err := registerDebugEndpoints(); err != nil {
    45  		return err
    46  	}
    47  
    48  	if err := registerConfigEndpoints(); err != nil {
    49  		return err
    50  	}
    51  
    52  	if err := registerModulesEndpoints(); err != nil {
    53  		return err
    54  	}
    55  
    56  	return registerMetaEndpoints()
    57  }
    58  
    59  func start() error {
    60  	startServer()
    61  
    62  	_ = updateAPIKeys(module.Ctx, nil)
    63  	err := module.RegisterEventHook("config", "config change", "update API keys", updateAPIKeys)
    64  	if err != nil {
    65  		return err
    66  	}
    67  
    68  	// start api auth token cleaner
    69  	if authFnSet.IsSet() {
    70  		module.NewTask("clean api sessions", cleanSessions).Repeat(5 * time.Minute)
    71  	}
    72  
    73  	return registerEndpointBridgeDB()
    74  }
    75  
    76  func stop() error {
    77  	return stopServer()
    78  }
    79  
    80  func exportEndpointsCmd() error {
    81  	data, err := json.MarshalIndent(ExportEndpoints(), "", "  ")
    82  	if err != nil {
    83  		return err
    84  	}
    85  
    86  	_, err = os.Stdout.Write(data)
    87  	return err
    88  }