github.com/hugh712/snapd@v0.0.0-20200910133618-1a99902bd583/overlord/configstate/configmgr.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2016-2017 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package configstate
    21  
    22  import (
    23  	"fmt"
    24  	"regexp"
    25  
    26  	"github.com/snapcore/snapd/overlord/configstate/config"
    27  	"github.com/snapcore/snapd/overlord/configstate/configcore"
    28  	"github.com/snapcore/snapd/overlord/hookstate"
    29  	"github.com/snapcore/snapd/overlord/state"
    30  )
    31  
    32  var configcoreRun = configcore.Run
    33  var configcoreExportExperimentalFlags = configcore.ExportExperimentalFlags
    34  
    35  func MockConfigcoreRun(f func(config.Conf) error) (restore func()) {
    36  	origConfigcoreRun := configcoreRun
    37  	configcoreRun = f
    38  	return func() {
    39  		configcoreRun = origConfigcoreRun
    40  	}
    41  }
    42  
    43  func MockConfigcoreExportExperimentalFlags(mock func(tr config.ConfGetter) error) (restore func()) {
    44  	old := configcoreExportExperimentalFlags
    45  	configcoreExportExperimentalFlags = mock
    46  	return func() {
    47  		configcoreExportExperimentalFlags = old
    48  	}
    49  }
    50  
    51  func Init(st *state.State, hookManager *hookstate.HookManager) error {
    52  	// Most configuration is handled via the "configure" hook of the
    53  	// snaps. However some configuration is internally handled
    54  	hookManager.Register(regexp.MustCompile("^configure$"), newConfigureHandler)
    55  	// Ensure that we run configure for the core snap internally.
    56  	// Note that we use the func() indirection so that mocking configcoreRun
    57  	// in tests works correctly.
    58  	hookManager.RegisterHijack("configure", "core", func(ctx *hookstate.Context) error {
    59  		ctx.Lock()
    60  		tr := ContextTransaction(ctx)
    61  		ctx.Unlock()
    62  		return configcoreRun(tr)
    63  	})
    64  
    65  	st.Lock()
    66  	defer st.Unlock()
    67  	tr := config.NewTransaction(st)
    68  	if err := configcoreExportExperimentalFlags(tr); err != nil {
    69  		return fmt.Errorf("cannot export experimental config flags: %v", err)
    70  	}
    71  	return nil
    72  }