github.com/ethanhsieh/snapd@v0.0.0-20210615102523-3db9b8e4edc5/cmd/snap/cmd_debug_state.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2019 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 main
    21  
    22  import (
    23  	"fmt"
    24  	"os"
    25  	"sort"
    26  	"strconv"
    27  	"strings"
    28  	"text/tabwriter"
    29  
    30  	"github.com/jessevdk/go-flags"
    31  
    32  	"github.com/snapcore/snapd/i18n"
    33  	"github.com/snapcore/snapd/overlord/state"
    34  )
    35  
    36  type cmdDebugState struct {
    37  	timeMixin
    38  
    39  	Changes  bool   `long:"changes"`
    40  	TaskID   string `long:"task"`
    41  	ChangeID string `long:"change"`
    42  
    43  	IsSeeded bool `long:"is-seeded"`
    44  
    45  	// flags for --change=N output
    46  	DotOutput bool `long:"dot"` // XXX: mildly useful (too crowded in many cases), but let's have it just in case
    47  	// When inspecting errors/undone tasks, those in Hold state are usually irrelevant, make it possible to ignore them
    48  	NoHoldState bool `long:"no-hold"`
    49  
    50  	Positional struct {
    51  		StateFilePath string `positional-args:"yes" positional-arg-name:"<state-file>"`
    52  	} `positional-args:"yes"`
    53  }
    54  
    55  var cmdDebugStateShortHelp = i18n.G("Inspect a snapd state file.")
    56  var cmdDebugStateLongHelp = i18n.G("Inspect a snapd state file, bypassing snapd API.")
    57  
    58  type byChangeID []*state.Change
    59  
    60  func (c byChangeID) Len() int           { return len(c) }
    61  func (c byChangeID) Swap(i, j int)      { c[i], c[j] = c[j], c[i] }
    62  func (c byChangeID) Less(i, j int) bool { return c[i].ID() < c[j].ID() }
    63  
    64  func loadState(path string) (*state.State, error) {
    65  	if path == "" {
    66  		path = "state.json"
    67  	}
    68  	r, err := os.Open(path)
    69  	if err != nil {
    70  		return nil, fmt.Errorf("cannot read the state file: %s", err)
    71  	}
    72  	defer r.Close()
    73  
    74  	return state.ReadState(nil, r)
    75  }
    76  
    77  func init() {
    78  	addDebugCommand("state", cmdDebugStateShortHelp, cmdDebugStateLongHelp, func() flags.Commander {
    79  		return &cmdDebugState{}
    80  	}, timeDescs.also(map[string]string{
    81  		// TRANSLATORS: This should not start with a lowercase letter.
    82  		"change":    i18n.G("ID of the change to inspect"),
    83  		"task":      i18n.G("ID of the task to inspect"),
    84  		"dot":       i18n.G("Dot (graphviz) output"),
    85  		"no-hold":   i18n.G("Omit tasks in 'Hold' state in the change output"),
    86  		"changes":   i18n.G("List all changes"),
    87  		"is-seeded": i18n.G("Output seeding status (true or false)"),
    88  	}), nil)
    89  }
    90  
    91  type byLaneAndWaitTaskChain []*state.Task
    92  
    93  func (t byLaneAndWaitTaskChain) Len() int      { return len(t) }
    94  func (t byLaneAndWaitTaskChain) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
    95  func (t byLaneAndWaitTaskChain) Less(i, j int) bool {
    96  	// cover the typical case (just one lane), and order by first lane
    97  	if t[i].Lanes()[0] == t[j].Lanes()[0] {
    98  		return waitChainSearch(t[i], t[j])
    99  	}
   100  	return t[i].Lanes()[0] < t[j].Lanes()[0]
   101  }
   102  
   103  func waitChainSearch(startT, searchT *state.Task) bool {
   104  	for _, cand := range startT.HaltTasks() {
   105  		if cand == searchT {
   106  			return true
   107  		}
   108  		if waitChainSearch(cand, searchT) {
   109  			return true
   110  		}
   111  	}
   112  
   113  	return false
   114  }
   115  
   116  func (c *cmdDebugState) writeDotOutput(st *state.State, changeID string) error {
   117  	st.Lock()
   118  	defer st.Unlock()
   119  
   120  	chg := st.Change(changeID)
   121  	if chg == nil {
   122  		return fmt.Errorf("no such change: %s", changeID)
   123  	}
   124  
   125  	fmt.Fprintf(Stdout, "digraph D{\n")
   126  	tasks := chg.Tasks()
   127  	for _, t := range tasks {
   128  		if c.NoHoldState && t.Status() == state.HoldStatus {
   129  			continue
   130  		}
   131  		fmt.Fprintf(Stdout, "  %s [label=%q];\n", t.ID(), t.Kind())
   132  		for _, wt := range t.WaitTasks() {
   133  			if c.NoHoldState && wt.Status() == state.HoldStatus {
   134  				continue
   135  			}
   136  			fmt.Fprintf(Stdout, "  %s -> %s;\n", t.ID(), wt.ID())
   137  		}
   138  	}
   139  	fmt.Fprintf(Stdout, "}\n")
   140  
   141  	return nil
   142  }
   143  
   144  func (c *cmdDebugState) showTasks(st *state.State, changeID string) error {
   145  	st.Lock()
   146  	defer st.Unlock()
   147  
   148  	chg := st.Change(changeID)
   149  	if chg == nil {
   150  		return fmt.Errorf("no such change: %s", changeID)
   151  	}
   152  
   153  	tasks := chg.Tasks()
   154  	sort.Sort(byLaneAndWaitTaskChain(tasks))
   155  
   156  	w := tabwriter.NewWriter(Stdout, 5, 3, 2, ' ', 0)
   157  	fmt.Fprintf(w, "Lanes\tID\tStatus\tSpawn\tReady\tKind\tSummary\n")
   158  	for _, t := range tasks {
   159  		if c.NoHoldState && t.Status() == state.HoldStatus {
   160  			continue
   161  		}
   162  		var lanes []string
   163  		for _, lane := range t.Lanes() {
   164  			lanes = append(lanes, fmt.Sprintf("%d", lane))
   165  		}
   166  		fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
   167  			strings.Join(lanes, ","),
   168  			t.ID(),
   169  			t.Status().String(),
   170  			c.fmtTime(t.SpawnTime()),
   171  			c.fmtTime(t.ReadyTime()),
   172  			t.Kind(),
   173  			t.Summary())
   174  	}
   175  
   176  	w.Flush()
   177  
   178  	for _, t := range tasks {
   179  		logs := t.Log()
   180  		if len(logs) > 0 {
   181  			fmt.Fprintf(Stdout, "---\n")
   182  			fmt.Fprintf(Stdout, "%s %s\n", t.ID(), t.Summary())
   183  			for _, log := range logs {
   184  				fmt.Fprintf(Stdout, "  %s\n", log)
   185  			}
   186  		}
   187  	}
   188  
   189  	return nil
   190  }
   191  
   192  func (c *cmdDebugState) showChanges(st *state.State) error {
   193  	st.Lock()
   194  	defer st.Unlock()
   195  
   196  	changes := st.Changes()
   197  	sort.Sort(byChangeID(changes))
   198  
   199  	w := tabwriter.NewWriter(Stdout, 5, 3, 2, ' ', 0)
   200  	fmt.Fprintf(w, "ID\tStatus\tSpawn\tReady\tLabel\tSummary\n")
   201  	for _, chg := range changes {
   202  		fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n",
   203  			chg.ID(),
   204  			chg.Status().String(),
   205  			c.fmtTime(chg.SpawnTime()),
   206  			c.fmtTime(chg.ReadyTime()),
   207  			chg.Kind(),
   208  			chg.Summary())
   209  	}
   210  	w.Flush()
   211  
   212  	return nil
   213  }
   214  
   215  func (c *cmdDebugState) showIsSeeded(st *state.State) error {
   216  	st.Lock()
   217  	defer st.Unlock()
   218  
   219  	var isSeeded bool
   220  	err := st.Get("seeded", &isSeeded)
   221  	if err != nil && err != state.ErrNoState {
   222  		return err
   223  	}
   224  	fmt.Fprintf(Stdout, "%v\n", isSeeded)
   225  
   226  	return nil
   227  }
   228  
   229  func (c *cmdDebugState) showTask(st *state.State, taskID string) error {
   230  	st.Lock()
   231  	defer st.Unlock()
   232  
   233  	task := st.Task(taskID)
   234  	if task == nil {
   235  		return fmt.Errorf("no such task: %s", taskID)
   236  	}
   237  
   238  	termWidth, _ := termSize()
   239  	termWidth -= 3
   240  	if termWidth > 100 {
   241  		// any wider than this and it gets hard to read
   242  		termWidth = 100
   243  	}
   244  
   245  	// the output of 'debug task' is yaml'ish
   246  	fmt.Fprintf(Stdout, "id: %s\nkind: %s\nsummary: %s\nstatus: %s\n",
   247  		taskID, task.Kind(),
   248  		task.Summary(),
   249  		task.Status().String())
   250  	log := task.Log()
   251  	if len(log) > 0 {
   252  		fmt.Fprintf(Stdout, "log: |\n")
   253  		for _, msg := range log {
   254  			if err := wrapLine(Stdout, []rune(msg), "  ", termWidth); err != nil {
   255  				break
   256  			}
   257  		}
   258  		fmt.Fprintln(Stdout)
   259  	}
   260  
   261  	fmt.Fprintf(Stdout, "halt-tasks:")
   262  	if len(task.HaltTasks()) == 0 {
   263  		fmt.Fprintln(Stdout, " []")
   264  	} else {
   265  		fmt.Fprintln(Stdout)
   266  		for _, ht := range task.HaltTasks() {
   267  			fmt.Fprintf(Stdout, " - %s (%s)\n", ht.Kind(), ht.ID())
   268  		}
   269  	}
   270  
   271  	return nil
   272  }
   273  
   274  func (c *cmdDebugState) Execute(args []string) error {
   275  	st, err := loadState(c.Positional.StateFilePath)
   276  	if err != nil {
   277  		return err
   278  	}
   279  
   280  	// check valid combinations of args
   281  	var cmds []string
   282  	if c.Changes {
   283  		cmds = append(cmds, "--changes")
   284  	}
   285  	if c.ChangeID != "" {
   286  		cmds = append(cmds, "--change=")
   287  	}
   288  	if c.TaskID != "" {
   289  		cmds = append(cmds, "--task=")
   290  	}
   291  	if c.IsSeeded {
   292  		cmds = append(cmds, "--is-seeded")
   293  	}
   294  	if len(cmds) > 1 {
   295  		return fmt.Errorf("cannot use %s and %s together", cmds[0], cmds[1])
   296  	}
   297  
   298  	if c.IsSeeded {
   299  		return c.showIsSeeded(st)
   300  	}
   301  
   302  	if c.DotOutput && c.ChangeID == "" {
   303  		return fmt.Errorf("--dot can only be used with --change=")
   304  	}
   305  	if c.NoHoldState && c.ChangeID == "" {
   306  		return fmt.Errorf("--no-hold can only be used with --change=")
   307  	}
   308  
   309  	if c.Changes {
   310  		return c.showChanges(st)
   311  	}
   312  
   313  	if c.ChangeID != "" {
   314  		_, err := strconv.ParseInt(c.ChangeID, 0, 64)
   315  		if err != nil {
   316  			return fmt.Errorf("invalid change: %s", c.ChangeID)
   317  		}
   318  		if c.DotOutput {
   319  			return c.writeDotOutput(st, c.ChangeID)
   320  		}
   321  		return c.showTasks(st, c.ChangeID)
   322  	}
   323  
   324  	if c.TaskID != "" {
   325  		_, err := strconv.ParseInt(c.TaskID, 0, 64)
   326  		if err != nil {
   327  			return fmt.Errorf("invalid task: %s", c.TaskID)
   328  		}
   329  		return c.showTask(st, c.TaskID)
   330  	}
   331  
   332  	// show changes by default
   333  	return c.showChanges(st)
   334  }