github.com/Cloud-Foundations/Dominator@v0.3.4/imagebuilder/builder/api.go (about)

     1  package builder
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"sync"
     7  	"syscall"
     8  	"time"
     9  
    10  	"github.com/Cloud-Foundations/Dominator/imagebuilder/logarchiver"
    11  	"github.com/Cloud-Foundations/Dominator/lib/filesystem/util"
    12  	"github.com/Cloud-Foundations/Dominator/lib/filter"
    13  	"github.com/Cloud-Foundations/Dominator/lib/hash"
    14  	"github.com/Cloud-Foundations/Dominator/lib/image"
    15  	"github.com/Cloud-Foundations/Dominator/lib/log"
    16  	"github.com/Cloud-Foundations/Dominator/lib/slavedriver"
    17  	"github.com/Cloud-Foundations/Dominator/lib/srpc"
    18  	"github.com/Cloud-Foundations/Dominator/lib/tags"
    19  	"github.com/Cloud-Foundations/Dominator/lib/triggers"
    20  	proto "github.com/Cloud-Foundations/Dominator/proto/imaginator"
    21  )
    22  
    23  // Private interface types.
    24  
    25  type buildLogger interface {
    26  	Bytes() []byte
    27  	io.Writer
    28  }
    29  
    30  type environmentGetter interface {
    31  	getenv() map[string]string
    32  }
    33  
    34  type imageBuilder interface {
    35  	build(b *Builder, client srpc.ClientI, request proto.BuildImageRequest,
    36  		buildLog buildLogger) (*image.Image, error)
    37  }
    38  
    39  // Other private types.
    40  
    41  type argList []string
    42  
    43  type bootstrapStream struct {
    44  	builder          *Builder
    45  	name             string
    46  	BootstrapCommand []string
    47  	*filter.Filter
    48  	imageFilter      *filter.Filter
    49  	ImageFilterUrl   string
    50  	ImageTagsUrl     string
    51  	imageTags        tags.Tags
    52  	imageTriggers    *triggers.Triggers
    53  	ImageTriggersUrl string
    54  	PackagerType     string
    55  }
    56  
    57  type buildResultType struct {
    58  	imageName  string
    59  	startTime  time.Time
    60  	finishTime time.Time
    61  	buildLog   []byte
    62  	error      error
    63  }
    64  
    65  type currentBuildInfo struct {
    66  	buffer       *bytes.Buffer
    67  	slaveAddress string
    68  	startedAt    time.Time
    69  }
    70  
    71  type dependencyDataType struct {
    72  	generatedAt         time.Time
    73  	lastAttemptError    error
    74  	lastAttemptFetchLog []byte
    75  	lastAttemptTime     time.Time
    76  	streamToSource      map[string]string // K: stream name, V: source stream.
    77  	unbuildableSources  map[string]struct{}
    78  }
    79  
    80  type imageStreamsConfigurationType struct {
    81  	Streams map[string]*imageStreamType `json:",omitempty"`
    82  }
    83  
    84  type imageStreamType struct {
    85  	builder           *Builder
    86  	builderUsers      map[string]struct{}
    87  	name              string
    88  	BuilderGroups     []string
    89  	BuilderUsers      []string
    90  	ManifestUrl       string
    91  	ManifestDirectory string
    92  	Variables         map[string]string
    93  }
    94  
    95  type inodeData struct {
    96  	ctime syscall.Timespec
    97  	hash  hash.Hash
    98  	size  uint64
    99  }
   100  
   101  type listCommandType struct {
   102  	ArgList        argList
   103  	SizeMultiplier uint64
   104  }
   105  
   106  type manifestConfigType struct {
   107  	*filter.Filter
   108  	MtimesCopyAddFilterLines  []string `json:",omitempty"`
   109  	MtimesCopyFilterLines     []string `json:",omitempty"`
   110  	SourceImage               string
   111  	SourceImageBuildVariables map[string]string `json:",omitempty"`
   112  	SourceImageGitCommitId    string            `json:",omitempty"`
   113  	SourceImageTagsToMatch    tags.MatchTags    `json:",omitempty"`
   114  }
   115  
   116  type masterConfigurationType struct {
   117  	BindMounts                []string                    `json:",omitempty"`
   118  	BootstrapStreams          map[string]*bootstrapStream `json:",omitempty"`
   119  	ImageStreamsCheckInterval uint                        `json:",omitempty"`
   120  	ImageStreamsToAutoRebuild []string                    `json:",omitempty"`
   121  	ImageStreamsUrl           string                      `json:",omitempty"`
   122  	MtimesCopyFilterLines     []string                    `json:",omitempty"`
   123  	PackagerTypes             map[string]packagerType     `json:",omitempty"`
   124  	RelationshipsQuickLinks   []WebLink                   `json:",omitempty"`
   125  }
   126  
   127  // manifestLocationType contains the expanded location of a manifest. These
   128  // data may include secrets (i.e. username and password).
   129  type manifestLocationType struct {
   130  	directory string
   131  	url       string
   132  }
   133  
   134  type manifestType struct {
   135  	filter              *filter.Filter
   136  	mtimesCopyAddFilter *filter.Filter
   137  	mtimesCopyFilter    *filter.Filter
   138  	sourceImageInfo     *sourceImageInfoType
   139  }
   140  
   141  type packagerType struct {
   142  	CleanCommand   argList
   143  	InstallCommand argList
   144  	ListCommand    listCommandType
   145  	RemoveCommand  argList
   146  	UpdateCommand  argList
   147  	UpgradeCommand argList
   148  	Verbatim       []string
   149  }
   150  
   151  type sourceImageInfoType struct {
   152  	computedFiles []util.ComputedFile
   153  	filter        *filter.Filter
   154  	imageName     string
   155  	treeCache     *treeCache
   156  	triggers      *triggers.Triggers
   157  }
   158  
   159  type testResultType struct {
   160  	buffer   chan byte
   161  	duration time.Duration
   162  	err      error
   163  	prog     string
   164  }
   165  
   166  type treeCache struct {
   167  	hitBytes    uint64
   168  	inodeTable  map[uint64]inodeData
   169  	numHits     uint64
   170  	pathToInode map[string]uint64
   171  }
   172  
   173  type WebLink struct {
   174  	Name string
   175  	URL  string
   176  }
   177  
   178  type BuildLocalOptions struct {
   179  	BindMounts        []string
   180  	ManifestDirectory string
   181  	MtimesCopyFilter  *filter.Filter
   182  	Variables         map[string]string
   183  }
   184  
   185  type Builder struct {
   186  	buildLogArchiver            logarchiver.BuildLogArchiver
   187  	bindMounts                  []string
   188  	createSlaveTimeout          time.Duration
   189  	disableLock                 sync.RWMutex
   190  	disableAutoBuildsUntil      time.Time
   191  	disableBuildRequestsUntil   time.Time
   192  	generateDependencyTrigger   chan<- chan<- struct{}
   193  	stateDir                    string
   194  	imageRebuildInterval        time.Duration
   195  	imageServerAddress          string
   196  	linksImageServerAddress     string
   197  	logger                      log.DebugLogger
   198  	imageStreamsUrl             string
   199  	initialNamespace            string // For catching golang bugs.
   200  	maximumExpiration           time.Duration
   201  	maximumExpirationPrivileged time.Duration
   202  	minimumExpiration           time.Duration
   203  	mtimesCopyFilter            *filter.Filter
   204  	streamsLoadedChannel        <-chan struct{} // Closed when streams loaded.
   205  	streamsLock                 sync.RWMutex
   206  	bootstrapStreams            map[string]*bootstrapStream
   207  	imageStreams                map[string]*imageStreamType
   208  	imageStreamsToAutoRebuild   []string
   209  	relationshipsQuickLinks     []WebLink
   210  	slaveDriver                 *slavedriver.SlaveDriver
   211  	buildResultsLock            sync.RWMutex
   212  	currentBuildInfos           map[string]*currentBuildInfo // Key: stream name.
   213  	lastBuildResults            map[string]buildResultType   // Key: stream name.
   214  	packagerTypes               map[string]packagerType
   215  	variables                   map[string]string
   216  	dependencyDataLock          sync.RWMutex
   217  	dependencyData              *dependencyDataType
   218  }
   219  
   220  type BuilderOptions struct {
   221  	ConfigurationURL                    string
   222  	CreateSlaveTimeout                  time.Duration
   223  	ImageRebuildInterval                time.Duration
   224  	ImageServerAddress                  string
   225  	MaximumExpirationDuration           time.Duration // Default: 1 day.
   226  	MaximumExpirationDurationPrivileged time.Duration // Default: 1 month.
   227  	MinimumExpirationDuration           time.Duration // Def: 15 min. Min: 5 min
   228  	PresentationImageServerAddress      string
   229  	StateDirectory                      string
   230  	VariablesFile                       string
   231  }
   232  
   233  type BuilderParams struct {
   234  	BuildLogArchiver logarchiver.BuildLogArchiver
   235  	Logger           log.DebugLogger
   236  	SlaveDriver      *slavedriver.SlaveDriver
   237  }
   238  
   239  func Load(confUrl, variablesFile, stateDir, imageServerAddress string,
   240  	imageRebuildInterval time.Duration, slaveDriver *slavedriver.SlaveDriver,
   241  	logger log.DebugLogger) (*Builder, error) {
   242  	return LoadWithOptionsAndParams(
   243  		BuilderOptions{
   244  			ConfigurationURL:     confUrl,
   245  			ImageRebuildInterval: imageRebuildInterval,
   246  			ImageServerAddress:   imageServerAddress,
   247  			StateDirectory:       stateDir,
   248  			VariablesFile:        variablesFile,
   249  		},
   250  		BuilderParams{
   251  			Logger:      logger,
   252  			SlaveDriver: slaveDriver,
   253  		})
   254  }
   255  
   256  func LoadWithOptionsAndParams(options BuilderOptions,
   257  	params BuilderParams) (*Builder, error) {
   258  	return load(options, params)
   259  }
   260  
   261  func (b *Builder) BuildImage(request proto.BuildImageRequest,
   262  	authInfo *srpc.AuthInformation,
   263  	logWriter io.Writer) (*image.Image, string, error) {
   264  	return b.buildImage(request, authInfo, logWriter)
   265  }
   266  
   267  func (b *Builder) DisableAutoBuilds(disableFor time.Duration) (
   268  	time.Time, error) {
   269  	return b.disableAutoBuilds(disableFor)
   270  }
   271  
   272  func (b *Builder) DisableBuildRequests(disableFor time.Duration) (
   273  	time.Time, error) {
   274  	return b.disableBuildRequests(disableFor)
   275  }
   276  
   277  func (b *Builder) GetCurrentBuildLog(streamName string) ([]byte, error) {
   278  	return b.getCurrentBuildLog(streamName)
   279  }
   280  
   281  func (b *Builder) GetDirectedGraph(request proto.GetDirectedGraphRequest) (
   282  	proto.GetDirectedGraphResult, error) {
   283  	return b.getDirectedGraph(request)
   284  }
   285  
   286  func (b *Builder) GetDependencies(request proto.GetDependenciesRequest) (
   287  	proto.GetDependenciesResult, error) {
   288  	return b.getDependencies(request)
   289  }
   290  
   291  func (b *Builder) GetLatestBuildLog(streamName string) ([]byte, error) {
   292  	return b.getLatestBuildLog(streamName)
   293  }
   294  
   295  func (b *Builder) GetRelationshipsQuickLinks() ([]WebLink, error) {
   296  	return b.relationshipsQuickLinks, nil
   297  }
   298  
   299  func (b *Builder) ReplaceIdleSlaves(immediateGetNew bool) error {
   300  	return b.replaceIdleSlaves(immediateGetNew)
   301  }
   302  
   303  func (b *Builder) ShowImageStream(writer io.Writer, streamName string) {
   304  	b.showImageStream(writer, streamName)
   305  }
   306  
   307  func (b *Builder) ShowImageStreams(writer io.Writer) {
   308  	b.showImageStreams(writer)
   309  }
   310  
   311  func (b *Builder) WaitForStreamsLoaded(timeout time.Duration) error {
   312  	return b.waitForStreamsLoaded(timeout)
   313  }
   314  
   315  func (b *Builder) WriteHtml(writer io.Writer) {
   316  	b.writeHtml(writer)
   317  }
   318  
   319  func BuildImageFromManifest(client *srpc.Client, manifestDir, streamName string,
   320  	expiresIn time.Duration, bindMounts []string, buildLog buildLogger,
   321  	logger log.Logger) (
   322  	string, error) {
   323  	return BuildImageFromManifestWithOptions(
   324  		client,
   325  		BuildLocalOptions{
   326  			BindMounts:        bindMounts,
   327  			ManifestDirectory: manifestDir,
   328  		},
   329  		streamName,
   330  		expiresIn,
   331  		buildLog)
   332  }
   333  
   334  func BuildImageFromManifestWithOptions(client *srpc.Client,
   335  	options BuildLocalOptions, streamName string, expiresIn time.Duration,
   336  	buildLog buildLogger) (string, error) {
   337  	_, name, err := buildImageFromManifestAndUpload(client, options, streamName,
   338  		expiresIn, buildLog)
   339  	return name, err
   340  }
   341  
   342  func BuildTreeFromManifest(client *srpc.Client, manifestDir string,
   343  	bindMounts []string, buildLog io.Writer,
   344  	logger log.Logger) (string, error) {
   345  	return BuildTreeFromManifestWithOptions(
   346  		client,
   347  		BuildLocalOptions{
   348  			BindMounts:        bindMounts,
   349  			ManifestDirectory: manifestDir,
   350  		},
   351  		buildLog)
   352  }
   353  
   354  func BuildTreeFromManifestWithOptions(client *srpc.Client,
   355  	options BuildLocalOptions, buildLog io.Writer) (string, error) {
   356  	return buildTreeFromManifest(client, options, buildLog)
   357  }
   358  
   359  func ProcessManifest(manifestDir, rootDir string, bindMounts []string,
   360  	buildLog io.Writer) error {
   361  	return processManifest(manifestDir, rootDir, bindMounts, nil, buildLog)
   362  }
   363  
   364  func ProcessManifestWithOptions(options BuildLocalOptions,
   365  	rootDir string, buildLog io.Writer) error {
   366  	return processManifest(options.ManifestDirectory, rootDir,
   367  		options.BindMounts, variablesGetter(options.Variables), buildLog)
   368  }
   369  
   370  func UnpackImageAndProcessManifest(client *srpc.Client, manifestDir string,
   371  	rootDir string, bindMounts []string, buildLog io.Writer) error {
   372  	_, err := unpackImageAndProcessManifest(client, manifestDir, 0, rootDir,
   373  		bindMounts, true, nil, buildLog)
   374  	return err
   375  }
   376  
   377  func UnpackImageAndProcessManifestWithOptions(client *srpc.Client,
   378  	options BuildLocalOptions, rootDir string, buildLog io.Writer) error {
   379  	_, err := unpackImageAndProcessManifest(client,
   380  		options.ManifestDirectory, 0, rootDir, options.BindMounts, true,
   381  		variablesGetter(options.Variables), buildLog)
   382  	return err
   383  }