github.com/rigado/snapd@v2.42.5-go-mod+incompatible/overlord/cmdstate/cmdmgr.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 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 cmdstate
    21  
    22  import (
    23  	"strings"
    24  	"time"
    25  
    26  	"gopkg.in/tomb.v2"
    27  
    28  	"github.com/snapcore/snapd/osutil"
    29  	"github.com/snapcore/snapd/overlord/state"
    30  )
    31  
    32  // CommandManager helps running arbitrary commands as tasks.
    33  type CommandManager struct{}
    34  
    35  // Manager returns a new CommandManager.
    36  func Manager(st *state.State, runner *state.TaskRunner) *CommandManager {
    37  	runner.AddHandler("exec-command", doExec, nil)
    38  	return &CommandManager{}
    39  }
    40  
    41  // Ensure is part of the overlord.StateManager interface.
    42  func (m *CommandManager) Ensure() error {
    43  	return nil
    44  }
    45  
    46  var defaultExecTimeout = 5 * time.Second
    47  
    48  func doExec(t *state.Task, tomb *tomb.Tomb) error {
    49  	var argv []string
    50  	var tout time.Duration
    51  
    52  	st := t.State()
    53  	st.Lock()
    54  	err1 := t.Get("argv", &argv)
    55  	err2 := t.Get("timeout", &tout)
    56  	st.Unlock()
    57  	if err1 != nil {
    58  		return err1
    59  	}
    60  	if err2 != nil && err2 != state.ErrNoState {
    61  		return err2
    62  	}
    63  	if err2 == state.ErrNoState {
    64  		tout = defaultExecTimeout
    65  	}
    66  
    67  	if buf, err := osutil.RunAndWait(argv, nil, tout, tomb); err != nil {
    68  		st.Lock()
    69  		t.Errorf("# %s\n%s", strings.Join(argv, " "), buf)
    70  		st.Unlock()
    71  		return err
    72  	}
    73  
    74  	return nil
    75  }