github.com/observiq/bindplane-agent@v1.51.0/internal/service/service.go (about)

     1  // Copyright  observIQ, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package service
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"time"
    21  
    22  	"go.uber.org/zap"
    23  )
    24  
    25  const (
    26  	startTimeout = 10 * time.Second
    27  	stopTimeout  = 10 * time.Second
    28  )
    29  
    30  // RunnableService may be run as a service.
    31  //
    32  //go:generate mockery --name RunnableService --filename mock_runnable_service.go --structname MockRunnableService
    33  type RunnableService interface {
    34  	// Start asynchronously starts the underlying service. The service may not necessarily be "ready"
    35  	// once this returns, but could be asynchronously starting up.
    36  	Start(ctx context.Context) error
    37  	// Stop synchronously shuts down the service. After this function returns, the underlying service should be completely stopped.
    38  	Stop(ctx context.Context) error
    39  	// Error returns an error channel that should emit an error when the service must unexpectedly quit.
    40  	Error() <-chan error
    41  }
    42  
    43  // runServiceInteractive runs the service in an "interactive" mode (responds to SIGINT and SIGTERM).
    44  // This mode is always used in linux, and is used in Windows when the collector
    45  // is not running as a service.
    46  func runServiceInteractive(ctx context.Context, logger *zap.Logger, svc RunnableService) error {
    47  	if err := svc.Start(ctx); err != nil {
    48  		return fmt.Errorf("failed to start service: %w", err)
    49  	}
    50  
    51  	var svcErr error
    52  	// Service is started; Wait for a stop signal.
    53  	select {
    54  	case <-ctx.Done():
    55  	case svcErr = <-svc.Error():
    56  		logger.Error("Unexpected error while running service", zap.Error(svcErr))
    57  	}
    58  
    59  	stopTimeoutCtx, stopCancel := context.WithTimeout(context.Background(), stopTimeout)
    60  	defer stopCancel()
    61  
    62  	if err := svc.Stop(stopTimeoutCtx); err != nil {
    63  		return fmt.Errorf("failed to stop service: %w", err)
    64  	}
    65  
    66  	return svcErr
    67  }