github.com/uber/kraken@v0.1.4/lib/torrent/scheduler/reload.go (about)

     1  // Copyright (c) 2016-2019 Uber Technologies, 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  package scheduler
    15  
    16  import (
    17  	"fmt"
    18  	"sync"
    19  
    20  	"github.com/uber/kraken/lib/torrent/scheduler/announcequeue"
    21  	"github.com/uber/kraken/utils/log"
    22  )
    23  
    24  // ReloadableScheduler is a Scheduler which supports reloadable configuration.
    25  type ReloadableScheduler interface {
    26  	Scheduler
    27  	Reload(config Config)
    28  }
    29  
    30  type reloadableScheduler struct {
    31  	*scheduler
    32  	mu sync.Mutex // Protects reloading Scheduler.
    33  	aq func() announcequeue.Queue
    34  }
    35  
    36  func makeReloadable(s *scheduler, aq func() announcequeue.Queue) *reloadableScheduler {
    37  	return &reloadableScheduler{scheduler: s, aq: aq}
    38  }
    39  
    40  // Reload restarts the Scheduler with new configuration. Panics if the Scheduler
    41  // fails to restart.
    42  func (rs *reloadableScheduler) Reload(config Config) {
    43  	if err := rs.reload(config); err != nil {
    44  		// Totally unrecoverable error -- rs.scheduler is now stopped and unusable,
    45  		// so let process die and restart with original config.
    46  		log.Fatalf("Failed to reload scheduler config: %s", err)
    47  	}
    48  }
    49  
    50  func (rs *reloadableScheduler) reload(config Config) error {
    51  	rs.mu.Lock()
    52  	defer rs.mu.Unlock()
    53  
    54  	s := rs.scheduler
    55  	s.Stop()
    56  
    57  	n, err := newScheduler(
    58  		config, s.torrentArchive, s.stats, s.pctx, s.announceClient, s.netevents)
    59  	if err != nil {
    60  		return fmt.Errorf("create new scheduler: %s", err)
    61  	}
    62  	rs.scheduler = n
    63  
    64  	if err := rs.scheduler.start(rs.aq()); err != nil {
    65  		return fmt.Errorf("start new scheduler: %s", err)
    66  	}
    67  	return nil
    68  }