Skip to content

Commit

Permalink
log.Fatal calls os.Exit(1) which will not let deferred func to run
Browse files Browse the repository at this point in the history
  • Loading branch information
quantonganh committed Mar 15, 2023
1 parent 220cffe commit 8b3e8bd
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 20 deletions.
48 changes: 31 additions & 17 deletions cmd/formula.go
Expand Up @@ -7,7 +7,6 @@ import (
"context"
_ "embed"
"fmt"
"log"
"net"
"os"
"os/exec"
Expand Down Expand Up @@ -52,7 +51,7 @@ to quickly create a Cobra application.`,
chromedp.ListenTarget(ctx, func(v interface{}) {
switch ev := v.(type) {
case *browser.EventDownloadWillBegin:
log.Println("EventDownloadWillBegin: ", ev.SuggestedFilename)
log.Info().Msgf("EventDownloadWillBegin: %s", ev.SuggestedFilename)
templateName := strings.Split(ev.SuggestedFilename, "_")[0]
_, ok := m[templateName]
if !ok {
Expand All @@ -68,57 +67,71 @@ to quickly create a Cobra application.`,

daysBefore, err := cmd.Flags().GetUint("days-before")
if err != nil {
log.Fatal(err)
log.Err(err).Msg("failed to get the value of days-before")
return
}

tasks, m := genReport(ctx, daysBefore)
if err := chromedp.Run(ctx, tasks); err != nil {
log.Fatal(err)
log.Err(err).Msg("failed to run chromedp")
return
}

home, err := homedir.Dir()
if err != nil {
log.Fatal(err)
log.Err(err).Msg("failed to get home dir")
return
}

targetFiles := make([]string, 0, len(m))
for _, r := range m {
if err := os.Rename(filepath.Join(home, "Downloads", r.SourceFile), filepath.Join(conf.OutDir, r.TargetFile)); err != nil {
log.Fatal(err)
log.Err(err).Msg("")
return
}
targetFiles = append(targetFiles, filepath.Join(conf.OutDir, r.TargetFile))
}

if err := importData(targetFiles); err != nil {
log.Fatal(err)
log.Err(err).Msg("failed to import data")
return
}

sendMail, err := cmd.Flags().GetBool("send-mail")
if err != nil {
log.Fatal(err)
log.Err(err).Msg("")
return
}
if sendMail {
winCmd := exec.Command("cmd.exe", "/c", "netsh", "wlan", "connect", fmt.Sprintf("ssid=%s", conf.Wifi.SendMail), fmt.Sprintf("name=%s", conf.Wifi.SendMail))
if err := winCmd.Run(); err != nil {
log.Fatal(err)
output, err := winCmd.CombinedOutput()
if err != nil {
log.Err(err).Msg("")
return
}
log.Printf("%s: %s", conf.Wifi.SendMail, output)
defer func() {
winCmd = exec.Command("cmd.exe", "/c", "netsh", "wlan", "connect", fmt.Sprintf("ssid=%s", conf.Wifi.ExportReport), fmt.Sprintf("name=%s", conf.Wifi.ExportReport))
if err := winCmd.Run(); err != nil {
log.Fatal(err)
output, err := winCmd.CombinedOutput()
if err != nil {
log.Err(err).Msg("")
}
log.Printf("%s: %s", conf.Wifi.ExportReport, output)
}()

retry(30*time.Second, func() bool {
_, err := net.Dial("tcp", net.JoinHostPort(conf.SMTP.Host, strconv.Itoa(conf.SMTP.Port)))
address := net.JoinHostPort(conf.SMTP.Host, strconv.Itoa(conf.SMTP.Port))
log.Printf("connecting to the %s", address)
_, err := net.Dial("tcp", address)
if err == nil {
return true
}
return false
})

if err := sendEmail(conf.Formula.Email.Subject, conf.Formula.Email.Body); err != nil {
log.Fatal(err)
log.Err(err).Msg("failed to send email")
return
}
}
},
Expand Down Expand Up @@ -223,10 +236,10 @@ func importData(targetFiles []string) error {
args = append(args, filepath.Join(conf.OutDir, conf.Formula.File))
winCmd := exec.Command(`C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`, args...)
output, err := winCmd.CombinedOutput()
log.Printf("output: %s", string(output))
if err != nil {
return errors.Wrap(err, "failed to run the command")
}
log.Printf("output: %s", string(output))
return nil
}

Expand All @@ -237,12 +250,13 @@ func retry(timeout time.Duration, f func() bool) {
defer to.Stop()
for {
select {
case <-to.C:
return
case <-ticker.C:
if f() {
return
}
case <-to.C:
log.Info().Msgf("timed out after %s", timeout.String())
return
}
}
}
Expand Down
32 changes: 29 additions & 3 deletions cmd/root.go
Expand Up @@ -5,17 +5,21 @@ package cmd

import (
"fmt"
"log"
"io"
"os"
"time"

"github.com/mitchellh/go-homedir"
"github.com/rs/zerolog"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var (
cfgFile string
conf *config
log zerolog.Logger
f *os.File
)

// rootCmd represents the base command when called without any subcommands
Expand All @@ -28,9 +32,29 @@ examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
var err error
f, err = os.OpenFile(
fmt.Sprintf("ims_%s.txt", time.Now().Format(time.RFC3339)),
os.O_APPEND|os.O_CREATE|os.O_WRONLY,
0664,
)
if err != nil {
return err
}

mw := io.MultiWriter(os.Stdout, f)
log = zerolog.New(mw).With().Timestamp().Logger()
return nil
},
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
PostRun: func(cmd *cobra.Command, args []string) {
if err := f.Close(); err != nil {
log.Err(err).Msg("failed to close file")
}
},
}

// Execute adds all child commands to the root command and sets flags appropriately.
Expand Down Expand Up @@ -120,10 +144,12 @@ func initConfig() {

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err != nil {
log.Fatal(err)
log.Err(err).Msg("failed to load the config file")
return
}

if err := viper.Unmarshal(&conf); err != nil {
log.Fatal(err)
log.Err(err).Msg("failed to unmarshal the config into a struct")
return
}
}
3 changes: 3 additions & 0 deletions go.mod
Expand Up @@ -7,6 +7,7 @@ require (
github.com/chromedp/chromedp v0.8.6
github.com/mitchellh/go-homedir v1.1.0
github.com/pkg/errors v0.9.1
github.com/rs/zerolog v1.29.0
github.com/spf13/cobra v1.6.1
github.com/spf13/viper v1.14.0
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
Expand All @@ -23,6 +24,8 @@ require (
github.com/josharian/intern v1.0.0 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-colorable v0.1.12 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.5 // indirect
Expand Down
11 changes: 11 additions & 0 deletions go.sum
Expand Up @@ -52,6 +52,7 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
Expand All @@ -74,6 +75,7 @@ github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.1.0 h1:7RFti/xnNkMJnrK7D1yQ/iCIB5OrrY/54/H930kIbHA=
github.com/gobwas/ws v1.1.0/go.mod h1:nzvNcVha5eUziGrbxFCo6qFIojQHjJV5cLYIbezhfL0=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
Expand Down Expand Up @@ -153,6 +155,10 @@ github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamh
github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40=
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
Expand All @@ -170,6 +176,9 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w=
github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/afero v1.9.2 h1:j49Hj62F0n+DaZ1dDCvhABaPNSGNkt32oRFxI33IEMw=
github.com/spf13/afero v1.9.2/go.mod h1:iUV7ddyEEZPO5gA3zD4fJt6iStLlL+Lg4m2cihcDf8Y=
Expand Down Expand Up @@ -329,6 +338,8 @@ golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec h1:BkDtF2Ih9xZ7le9ndzTA7KJow28VbQW3odyk/8drmuI=
golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
Expand Down

0 comments on commit 8b3e8bd

Please sign in to comment.