Skip to content

Commit

Permalink
[wip] log file handler
Browse files Browse the repository at this point in the history
  • Loading branch information
xzyaoi committed Dec 3, 2018
1 parent f51e9c6 commit 76120c9
Show file tree
Hide file tree
Showing 9 changed files with 215 additions and 13 deletions.
15 changes: 15 additions & 0 deletions cli/config.go
Expand Up @@ -103,4 +103,19 @@ func validateConfig() {
log.Fatal(err)
}
}
// check if system log file exists
cvpmLogPath := filepath.Join(cvpmPath, "system.log")
exist, err := isPathExists(cvpmLogPath)
if err != nil {
raven.CaptureErrorAndWait(err, nil)
log.Fatal(err)
}
if !exist {
f, err := os.Create(cvpmLogPath)
if err != nil {
raven.CaptureErrorAndWait(err, nil)
log.Fatal(err)
}
defer f.Close()
}
}
168 changes: 160 additions & 8 deletions cli/shell.go
@@ -1,16 +1,37 @@
package main

import (
"bufio"
"fmt"
"github.com/getsentry/raven-go"
"io"
"log"
"os"
"os/exec"
"sync"
"time"
)

func pip(args []string) {
config := readConfig()
localPip := config.Local.Pip
_ = _execCommand(localPip, args)
// _ = _execCommand(localPip, args)
proc := NewProcess(localPip, args...)
out := proc.StreamOutput()
file, err := os.OpenFile("system.log", os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
log.Fatalf("failed opening file: %s", err)
}
go func() {
for out.Scan() {
_, err := file.WriteString(out.Text() + "\n")
if err != nil {
log.Fatalf("failed writing to file: %s", err)
}
defer file.Close()
log.Println(out.Text())
}
}()
proc.Start()
}

func python(args []string) {
Expand All @@ -21,13 +42,144 @@ func python(args []string) {

func _execCommand(commandName string, params []string) bool {
cmd := exec.Command(commandName, params...)
cmd.Stdout = os.Stdout
fmt.Println(cmd.Args)
output, err := cmd.CombinedOutput()
return true
}

type Process struct {
proc *exec.Cmd
cancellationSignal chan uint8
done chan error
returnCode chan error
started bool
stdOutRead *io.PipeReader
stdOutWrite *io.PipeWriter
inputWriter *io.PipeWriter
inputStreamSet bool
outputStreamSet bool
completed bool
timeout time.Duration
// Access to completed MUST capture the lock.
mutex sync.RWMutex
}

func NewProcess(command string, args ...string) *Process {
process := &Process{
exec.Command(command, args...),
make(chan uint8, 1),
make(chan error, 1),
make(chan error, 1),
false,
&io.PipeReader{},
&io.PipeWriter{},
&io.PipeWriter{},
false,
false,
false,
0,
sync.RWMutex{}}
return process
}

func (p *Process) Start() *Process {
if p.timeout > 0 {
log.Println("Its greater than 0")
timer := time.NewTimer(p.timeout)
go func() {
<-timer.C
p.Kill()
}()
}
p.started = true
//Call the other functions to stream stdin and stdout
err := p.proc.Start()
if err != nil {
raven.CaptureErrorAndWait(err, nil)
log.Fatal(err)
return false
panic(err)
}
log.Printf(string(output))
return true
go p.awaitOutput()
go p.finishTimeOutOrDie()
return p
}

func (p *Process) SetTimeout(d time.Duration) {
if p.started {
panic("Can not set timeout after process started")
}
p.timeout = d
}

func (p *Process) Wait() error {
return <-p.returnCode
}

func (p *Process) awaitOutput() {
//send the exit code to the done channel to signify the command finished
p.done <- p.proc.Wait()
}

func (p *Process) Kill() {
p.mutex.Lock()
if !p.completed {
p.cancellationSignal <- 1
}
p.mutex.Unlock()
}

func (p *Process) OpenInputStream() (io.WriteCloser, error) {
if p.inputStreamSet {
panic("Input stream already set")
}
if p.started {
panic("process already started")
}
stdIn, err := p.proc.StdinPipe()
p.inputStreamSet = true
return stdIn, err

}
func (p *Process) StreamOutput() *bufio.Scanner {
//pipe both stdout and stderr into the same pipe
//panics if you do streamoutput after proccess starting or
//if the output stream is already set
if p.started {
panic("Cant set output stream after starting")
}
if p.outputStreamSet {
panic("output stream already set!")
}
p.stdOutRead, p.stdOutWrite = io.Pipe()
p.proc.Stdout = p.stdOutWrite
p.proc.Stderr = p.stdOutWrite
p.outputStreamSet = true
//return a scanner which they can read from till empty
return bufio.NewScanner(p.stdOutRead)
}

func (p *Process) finishTimeOutOrDie() {
defer p.cleanup()
var result error
select {
case result = <-p.done:
case <-p.cancellationSignal:
log.Println("received cancellationSignal")
//NOT PORTABLE TO WINDOWS
err := p.proc.Process.Kill()
if err != nil {
log.Println(err)
}
}
p.returnCode <- result
}

func (p *Process) cleanup() {
p.mutex.Lock()
p.completed = true
p.mutex.Unlock()
if p.outputStreamSet {
p.stdOutRead.Close()
p.stdOutWrite.Close()
}
close(p.done)
close(p.cancellationSignal)
}
3 changes: 0 additions & 3 deletions cli/user.go
Expand Up @@ -21,7 +21,6 @@ type User struct {
}

func (u *User) login() User {
fmt.Println(u.Username)
csrp, _ := cognitosrp.NewCognitoSRP(u.Username, u.Password, "us-east-1_IYJ3FvCKZ", "1jinmsd412vcs8pkhqg5u0gjd2", nil)
cfg, _ := external.LoadDefaultAWSConfig()
cfg.Region = endpoints.UsEast1RegionID
Expand All @@ -33,8 +32,6 @@ func (u *User) login() User {
AuthParameters: csrp.GetAuthParams(),
})
resp, _ := req.Send()
fmt.Println("123456")
fmt.Println(resp.ChallengeName)
if resp.ChallengeName == cip.ChallengeNameTypePasswordVerifier {
challengeInput, _ := csrp.PasswordVerifierChallenge(resp.ChallengeParameters, time.Now())
chal := svc.RespondToAuthChallengeRequest(challengeInput)
Expand Down
16 changes: 16 additions & 0 deletions cli/utils.go
@@ -0,0 +1,16 @@
package main

import (
"os"
)

func isExists(path string) bool {
_, err := os.Stat(path)
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
Empty file.
2 changes: 1 addition & 1 deletion dashboard/src/components/CVPM-News.vue
Expand Up @@ -54,6 +54,6 @@ export default {
padding-right: 1em;
}
.cvpm-news-card {
width: 40%;
width: 90%;
}
</style>
2 changes: 1 addition & 1 deletion dashboard/src/components/CVPM-Status.vue
Expand Up @@ -33,7 +33,7 @@ export default {

<style scoped>
.cvpm-status-card {
width: 40%;
width: 95%;
}
.cvpm-status-content {
padding-left: 2em;
Expand Down
6 changes: 6 additions & 0 deletions dashboard/src/pages/Landing.vue
@@ -1,7 +1,13 @@
<template>
<v-container>
<v-layout row wrap>
<v-flex xs6>
<cvpm-news></cvpm-news>
</v-flex>
<v-flex xs6>
<cvpm-status></cvpm-status>
</v-flex>
</v-layout>
</v-container>
</template>

Expand Down
16 changes: 16 additions & 0 deletions scripts/runner.tpl
@@ -0,0 +1,16 @@
#coding:utf-8
import os
import argparse
import sys
os.chdir(sys.path[0])

parser = argparse.ArgumentParser(description='CVPM Runner')
parser.add_argument('port', type=int, help='Listening on Port')

args = parser.parse_args()

from {{Package}}.{{Filename}} import {{Classname}}

solver = {{Classname}}()

solver.start(args.port)

0 comments on commit 76120c9

Please sign in to comment.