1/*
2Copyright (c) 2015-2016 VMware, Inc. All Rights Reserved.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package logs
18
19import (
20	"context"
21	"flag"
22	"time"
23
24	"github.com/vmware/govmomi/govc/cli"
25	"github.com/vmware/govmomi/govc/flags"
26	"github.com/vmware/govmomi/object"
27)
28
29type logs struct {
30	*flags.HostSystemFlag
31
32	Max int32
33	Key string
34
35	follow bool
36}
37
38func init() {
39	cli.Register("logs", &logs{})
40}
41
42func (cmd *logs) Register(ctx context.Context, f *flag.FlagSet) {
43	cmd.HostSystemFlag, ctx = flags.NewHostSystemFlag(ctx)
44	cmd.HostSystemFlag.Register(ctx, f)
45
46	cmd.Max = 25 // default
47	f.Var(flags.NewInt32(&cmd.Max), "n", "Output the last N log lines")
48	f.StringVar(&cmd.Key, "log", "", "Log file key")
49	f.BoolVar(&cmd.follow, "f", false, "Follow log file changes")
50}
51
52func (cmd *logs) Process(ctx context.Context) error {
53	if err := cmd.HostSystemFlag.Process(ctx); err != nil {
54		return err
55	}
56	return nil
57}
58
59func (cmd *logs) Description() string {
60	return `View VPX and ESX logs.
61
62The '-log' option defaults to "hostd" when connected directly to a host or
63when connected to VirtualCenter and a '-host' option is given.  Otherwise,
64the '-log' option defaults to "vpxd:vpxd.log".  The '-host' option is ignored
65when connected directly to a host.  See 'govc logs.ls' for other '-log' options.
66
67Examples:
68  govc logs -n 1000 -f
69  govc logs -host esx1
70  govc logs -host esx1 -log vmkernel`
71}
72
73func (cmd *logs) Run(ctx context.Context, f *flag.FlagSet) error {
74	c, err := cmd.Client()
75	if err != nil {
76		return err
77	}
78
79	defaultKey := "hostd"
80	var host *object.HostSystem
81
82	if c.IsVC() {
83		host, err = cmd.HostSystemIfSpecified()
84		if err != nil {
85			return err
86		}
87
88		if host == nil {
89			defaultKey = "vpxd:vpxd.log"
90		}
91	}
92
93	m := object.NewDiagnosticManager(c)
94
95	key := cmd.Key
96	if key == "" {
97		key = defaultKey
98	}
99
100	l := m.Log(ctx, host, key)
101
102	err = l.Seek(ctx, cmd.Max)
103	if err != nil {
104		return err
105	}
106
107	for {
108		_, err = l.Copy(ctx, cmd.Out)
109		if err != nil {
110			return nil
111		}
112
113		if !cmd.follow {
114			break
115		}
116
117		<-time.After(time.Second)
118	}
119
120	return nil
121}
122