code
stringlengths
67
15.9k
labels
listlengths
1
4
// Copyright © 2019 The Things Network Foundation, The Things Industries B.V. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cups_test import ( "bytes" "crypto/x509" "testing" "github.com/smarty/assertions" "go.thethings.network/lorawan-stack/v3/pkg/basicstation/cups" "go.thethings.network/lorawan-stack/v3/pkg/util/test/assertions/should" ) func TestUpdateInfoResponse(t *testing.T) { for _, tt := range []struct { Name string cups.UpdateInfoResponse }{ {Name: "Empty"}, {Name: "Full", UpdateInfoResponse: cups.UpdateInfoResponse{ CUPSURI: "https://cups.example.com", LNSURI: "https://lns.example.com", CUPSCredentials: bytes.Repeat([]byte("CUPS CREDENTIALS"), 1000), LNSCredentials: bytes.Repeat([]byte("LNS CREDENTIALS"), 1000), SignatureKeyCRC: 12345678, Signature: bytes.Repeat([]byte("THIS IS THE SIGNATURE"), 1000), UpdateData: bytes.Repeat([]byte("THIS IS THE UPDATE DATA"), 1000), }}, } { t.Run(tt.Name, func(t *testing.T) { a := assertions.New(t) data, err := tt.UpdateInfoResponse.MarshalBinary() a.So(err, should.BeNil) var dec cups.UpdateInfoResponse err = dec.UnmarshalBinary(data) a.So(err, should.BeNil) a.So(dec, should.Resemble, tt.UpdateInfoResponse) }) } } func TestTokenCredentials(t *testing.T) { for _, tc := range []struct { Name string Token string Expected []byte ErrorAssertion func(err error) bool }{ { Name: "WithExtraNewline", Token: "token\n", Expected: []byte{0x4C, 0x45, 0x54, 0x53, 0x20, 0x4E, 0x4F, 0x54, 0x20, 0x45, 0x4E, 0x43, 0x52, 0x59, 0x50, 0x54, 0x0, 0x0, 0x0, 0x0, 0x41, 0x75, 0x74, 0x68, 0x6F, 0x72, 0x69, 0x7A, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x3A, 0x20, 0x74, 0x6F, 0x6B, 0x65, 0x6E, 0xD, 0xA}, }, { Name: "Valid", Token: "token", Expected: []byte{0x4C, 0x45, 0x54, 0x53, 0x20, 0x4E, 0x4F, 0x54, 0x20, 0x45, 0x4E, 0x43, 0x52, 0x59, 0x50, 0x54, 0x0, 0x0, 0x0, 0x0, 0x41, 0x75, 0x74, 0x68, 0x6F, 0x72, 0x69, 0x7A, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x3A, 0x20, 0x74, 0x6F, 0x6B, 0x65, 0x6E, 0xD, 0xA}, }, } { t.Run(tc.Name, func(t *testing.T) { a := assertions.New(t) creds, err := cups.TokenCredentials(&x509.Certificate{ Raw: []byte("LETS NOT ENCRYPT"), }, tc.Token) if err != nil && (tc.ErrorAssertion == nil || !a.So(tc.ErrorAssertion(err), should.BeTrue)) { t.Fatalf("Unexpected error: %v", err) } else { if !a.So(creds, should.Resemble, tc.Expected) { t.Fatalf("Unexpected token credentials: %v", creds) } } }) } }
[ 4 ]
package test import ( "context" "encoding/json" "fmt" "github.com/DATA-DOG/go-sqlmock" "github.com/micro/go-micro/client" "github.com/micro/go-micro/errors" "liaotian/domain/user/handler" "liaotian/domain/user/proto" "liaotian/domain/user/repository" "net/http" "github.com/micro/go-micro" "liaotian/middlewares/logger/zap" "testing" "time" ) func TestMain(m *testing.M) { zap.InitLogger() db, mockDb := repository.NewMockDb() repository.Init(db, mockDb) // 新建服务 service := micro.NewService( micro.Name("domain.user.service"), micro.Version("latest"), micro.RegisterTTL(time.Second*15), ) // 注册服务 _ = proto.RegisterUserHandler(service.Server(), handler.Init()) go func() { // 启动服务 if err := service.Run(); err != nil { zap.SugarLogger.Fatalf("服务启动失败,error: %v", err) } }() fmt.Print("服务启动成功") time.Sleep(time.Second * 1) m.Run() } func TestCreateUserInfo(t *testing.T) { testData := []struct { Account string Name string Password string Avatar string Code int32 Msg string Data string }{ {"zhangsan", "张三", "123456", "http://baidu.com", http.StatusCreated, "success", "{\"id\":1,\"name\":\"张三\",\"avatar\":\"http://baidu.com\"}"}, {"zhangsan", "张三", "123456", "", http.StatusForbidden, "用户已存在", ""}, {"", "张三", "123456", "http://baidu.com", http.StatusBadRequest, "参数错误", ""}, {"zhangsan", "", "123456", "http://baidu.com", http.StatusBadRequest, "参数错误", ""}, {"zhangsan", "张三", "", "http://baidu.com", http.StatusBadRequest, "参数错误", ""}, } service := proto.NewUserService("domain.user.service", client.DefaultClient) for i, data := range testData { t.Run("", func(t *testing.T) { request := proto.Request{ Account: data.Account, Name: data.Name, Password: data.Password, Avatar: data.Avatar, } if i == 0 { repository.Repo.MockDb.ExpectQuery("SELECT \\* FROM `users`"). WithArgs(data.Account). WillReturnRows(sqlmock.NewRows(nil)) repository.Repo.MockDb.ExpectBegin() repository.Repo.MockDb.ExpectExec("^INSERT INTO `users` (`name`,`account`,`password`,`avatar`,`created_at`,`updated_at`)*"). WillReturnResult(sqlmock.NewResult(1, 1)) repository.Repo.MockDb.ExpectCommit() } if i == 1 { row := sqlmock.NewRows([]string{"id", "name", "account", "password", "avatar"}). AddRow(1, data.Name, data.Account, data.Password, data.Avatar) repository.Repo.MockDb.ExpectQuery("SELECT \\* FROM `users`"). WithArgs(data.Account). WillReturnRows(row) } resp, err := service.CreateUserInfo(context.Background(), &request) if err != nil { errData := errors.Parse(err.Error()) if errData.Code != data.Code { t.Errorf("响应Code错误,want:%v, got:%v", data.Code, errData.Code) } if errData.Detail != data.Msg { t.Errorf("响应Msg错误,want:%v, got:%v", data.Msg, errData.Detail) } } else { if data.Data != "" { byteData, _ := json.Marshal(resp.Data) if string(byteData) != data.Data { t.Errorf("响应Data错误,want:%v, got:%v", data.Data, string(byteData)) } } } if err = repository.Repo.MockDb.ExpectationsWereMet(); err != nil { t.Errorf("sqlmock 执行不符合预期 : %v", err) } }) } } func TestGetUserInfo(t *testing.T) { testData := []struct { Account string Name string Id int64 Code int32 Msg string Data string }{ {"zhangsan", "张三", 1, http.StatusOK, "success", "{\"id\":1,\"name\":\"张三\",\"account\":\"zhangsan\",\"avatar\":\"http://baidu.com\"}"}, {"lisi", "", 0, http.StatusNotFound, "用户不存在", ""}, {"", "", 0, http.StatusBadRequest, "参数错误", ""}, } service := proto.NewUserService("domain.user.service", client.DefaultClient) for i, data := range testData { t.Run("", func(t *testing.T) { request := proto.Request{ Account: data.Account, Name: data.Name, Id: data.Id, } if i == 0 { row := sqlmock.NewRows([]string{"id", "name", "account", "password", "avatar"}). AddRow(1, data.Name, data.Account, "123456", "http://baidu.com") repository.Repo.MockDb.ExpectQuery("^SELECT \\* FROM `users`*"). WillReturnRows(row) } if i == 1 { repository.Repo.MockDb.ExpectQuery("^SELECT \\* FROM `users`*"). WillReturnRows(sqlmock.NewRows(nil)) } resp, err := service.GetUserInfo(context.Background(), &request) if err != nil { errData := errors.Parse(err.Error()) if errData.Code != data.Code { t.Errorf("响应Code错误,want:%v, got?:%v", data.Code, errData.Code) } if errData.Detail != data.Msg { t.Errorf("响应Msg错误,want:%v, got:%v", data.Msg, errData.Detail) } } else { if data.Data != "" { byteData, _ := json.Marshal(resp.Data) if string(byteData) != data.Data { t.Errorf("响应Data错误,want:%v, got:%v", data.Data, string(byteData)) } } } if err = repository.Repo.MockDb.ExpectationsWereMet(); err != nil { t.Errorf("sqlmock 执行不符合预期 : %v", err) } }) } } func TestUpdateUserInfo(t *testing.T) { testData := []struct { Id int64 Account string Name string Password string Avatar string Code int32 Msg string Data string }{ {1, "zhangsan", "张三2", "123123", "http://google.com", http.StatusOK, "success", "{\"id\":1,\"name\":\"张三2\",\"avatar\":\"http://google.com\"}"}, {2, "zhangsan", "张三2", "123123", "http://google.com", http.StatusNotFound, "用户不存在", ""}, {0, "zhangsan", "张三2", "123123", "http://google.com", http.StatusBadRequest, "参数错误", ""}, } service := proto.NewUserService("domain.user.service", client.DefaultClient) for i, data := range testData { t.Run("", func(t *testing.T) { if i == 0 { row := sqlmock.NewRows([]string{"id", "name", "account", "password", "avatar"}). AddRow(data.Id, data.Name, data.Account, data.Password, data.Avatar) repository.Repo.MockDb.ExpectQuery("^SELECT \\* FROM `users`*"). WithArgs(data.Id). WillReturnRows(row) repository.Repo.MockDb.ExpectBegin() repository.Repo.MockDb.ExpectExec("^UPDATE `users` SET*"). WillReturnResult(sqlmock.NewResult(1, 1)) repository.Repo.MockDb.ExpectCommit() } if i == 1 { repository.Repo.MockDb.ExpectQuery("^SELECT \\* FROM `users`*"). WithArgs(data.Id). WillReturnRows(sqlmock.NewRows(nil)) } request := proto.Request{ Id: data.Id, Name: data.Name, Password: data.Password, Avatar: data.Avatar, } resp, err := service.UpdateUserInfo(context.Background(), &request) if err != nil { errData := errors.Parse(err.Error()) if errData.Code != data.Code { t.Errorf("响应Code错误,want:%v, got:%v", data.Code, errData.Code) } if errData.Detail != data.Msg { t.Errorf("响应Msg错误,want:%v, got:%v", data.Msg, errData.Detail) } } else { if data.Data != "" { byteData, _ := json.Marshal(resp.Data) if string(byteData) != data.Data { t.Errorf("响应Data错误,want:%v, got:%v", data.Data, string(byteData)) } } } if err = repository.Repo.MockDb.ExpectationsWereMet(); err != nil { t.Errorf("sqlmock 执行不符合预期: %v", err) } }) } } func TestCheckUserPwd(t *testing.T) { testData := []struct { Id int64 Account string Name string Password string Avatar string Code int32 Msg string Data string }{ {1, "zhangsan", "张三", "123456", "http://baidu.com", http.StatusOK, "success", "{\"id\":1,\"name\":\"张三\",\"avatar\":\"http://baidu.com\"}"}, {1, "zhangsan", "张三", "111111", "", http.StatusUnauthorized, "密码错误", ""}, {2, "lisi", "李四", "123456", "http://baidu.com", http.StatusNotFound, "用户不存在", ""}, {0, "", "张三", "123456", "http://baidu.com", http.StatusBadRequest, "参数错误", ""}, } service := proto.NewUserService("domain.user.service", client.DefaultClient) for i, data := range testData { t.Run("", func(t *testing.T) { request := proto.Request{ Account: data.Account, Password: data.Password, } if i < 2 { row := sqlmock.NewRows([]string{"id", "name", "account", "password", "avatar"}). AddRow(data.Id, data.Name, data.Account, "123456", data.Avatar) repository.Repo.MockDb.ExpectQuery("^SELECT \\* FROM `users`*"). WithArgs(data.Account). WillReturnRows(row) } if i == 2 { repository.Repo.MockDb.ExpectQuery("^SELECT \\* FROM `users`*"). WithArgs(data.Account). WillReturnRows(sqlmock.NewRows(nil)) } resp, err := service.CheckUserPwd(context.Background(), &request) if err != nil { errData := errors.Parse(err.Error()) if errData.Code != data.Code { t.Errorf("响应Code错误,want:%v, got:%v", data.Code, errData.Code) } if errData.Detail != data.Msg { t.Errorf("响应Msg错误,want:%v, got:%v", data.Msg, errData.Detail) } } else { if data.Data != "" { byteData, _ := json.Marshal(resp.Data) if string(byteData) != data.Data { t.Errorf("响应Data错误,want:%v, got:%v", data.Data, string(byteData)) } } } if err = repository.Repo.MockDb.ExpectationsWereMet(); err != nil { t.Errorf("sqlmock 执行不符合预期: %v", err) } }) } } func TestBatchGetUserInfo(t *testing.T) { testData := []struct { Ids []int64 Code int32 Msg string Data string }{ {[]int64{1, 2}, http.StatusOK, "success", "[{\"id\":1,\"name\":\"张三\",\"account\":\"zhangsan\",\"avatar\":\"www.baidu.com\"},{\"id\":2,\"name\":\"李四\",\"account\":\"lisi\",\"avatar\":\"www.weibo.com\"}]"}, {[]int64{}, http.StatusBadRequest, "参数错误", ""}, } service := proto.NewUserService("domain.user.service", client.DefaultClient) for i, data := range testData { t.Run("", func(t *testing.T) { request := proto.BatchGetUserInfoRequest{ Ids: data.Ids, } if i < 1 { row := sqlmock.NewRows([]string{"id", "name", "account", "password", "avatar"}). AddRow(1, "张三", "zhangsan", "123456", "www.baidu.com"). AddRow(2, "李四", "lisi", "aaaaa", "www.weibo.com") repository.Repo.MockDb.ExpectQuery("^SELECT \\* FROM `users`*"). WillReturnRows(row) } resp, err := service.BatchGetUserInfo(context.Background(), &request) if err != nil { errData := errors.Parse(err.Error()) if errData.Code != data.Code { t.Errorf("响应Code错误,want:%v, got:%v", data.Code, errData.Code) } if errData.Detail != data.Msg { t.Errorf("响应Msg错误,want:%v, got:%v", data.Msg, errData.Detail) } } else { if data.Data != "" { byteData, _ := json.Marshal(resp.Data) if string(byteData) != data.Data { t.Errorf("响应Data错误,want:%v, got:%v", data.Data, string(byteData)) } } } if err = repository.Repo.MockDb.ExpectationsWereMet(); err != nil { t.Errorf("sqlmock 执行不符合预期: %v", err) } }) } }
[ 4 ]
// Code generated by mockery v2.1.0. DO NOT EDIT. package mocks import ( models "github.com/gojek/turing/api/turing/models" mock "github.com/stretchr/testify/mock" ) // AlertService is an autogenerated mock type for the AlertService type type AlertService struct { mock.Mock } // Delete provides a mock function with given fields: alert, authorEmail func (_m *AlertService) Delete(alert models.Alert, authorEmail string) error { ret := _m.Called(alert, authorEmail) var r0 error if rf, ok := ret.Get(0).(func(models.Alert, string) error); ok { r0 = rf(alert, authorEmail) } else { r0 = ret.Error(0) } return r0 } // FindByID provides a mock function with given fields: id func (_m *AlertService) FindByID(id uint) (*models.Alert, error) { ret := _m.Called(id) var r0 *models.Alert if rf, ok := ret.Get(0).(func(uint) *models.Alert); ok { r0 = rf(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*models.Alert) } } var r1 error if rf, ok := ret.Get(1).(func(uint) error); ok { r1 = rf(id) } else { r1 = ret.Error(1) } return r0, r1 } // List provides a mock function with given fields: _a0 func (_m *AlertService) List(_a0 string) ([]*models.Alert, error) { ret := _m.Called(_a0) var r0 []*models.Alert if rf, ok := ret.Get(0).(func(string) []*models.Alert); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*models.Alert) } } var r1 error if rf, ok := ret.Get(1).(func(string) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) } return r0, r1 } // Save provides a mock function with given fields: alert, authorEmail func (_m *AlertService) Save(alert models.Alert, authorEmail string) (*models.Alert, error) { ret := _m.Called(alert, authorEmail) var r0 *models.Alert if rf, ok := ret.Get(0).(func(models.Alert, string) *models.Alert); ok { r0 = rf(alert, authorEmail) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*models.Alert) } } var r1 error if rf, ok := ret.Get(1).(func(models.Alert, string) error); ok { r1 = rf(alert, authorEmail) } else { r1 = ret.Error(1) } return r0, r1 } // Update provides a mock function with given fields: alert, authorEmail func (_m *AlertService) Update(alert models.Alert, authorEmail string) error { ret := _m.Called(alert, authorEmail) var r0 error if rf, ok := ret.Get(0).(func(models.Alert, string) error); ok { r0 = rf(alert, authorEmail) } else { r0 = ret.Error(0) } return r0 }
[ 4 ]
// +build linux darwin package main import ( "errors" "fmt" "github.com/gosuri/uiprogress" "github.com/upyun/go-sdk/upyun" "log" "os" "path" "path/filepath" "strings" "sync" "time" ) type FsDriver struct { curDir string operator string bucket string maxConc int up *upyun.UpYun logger *log.Logger progress *uiprogress.Progress } func NewFsDriver(bucket, username, password, curDir string, conc int, logger *log.Logger) (*FsDriver, error) { driver := &FsDriver{ curDir: curDir, operator: username, bucket: bucket, up: upyun.NewUpYun(bucket, username, password), maxConc: conc, logger: logger, } var err error _, err = driver.up.Usage() if err != nil { return nil, err } driver.progress = uiprogress.New() driver.progress.RefreshInterval = time.Millisecond * 100 driver.progress.Start() return driver, nil } func short(s string) string { l := len(s) if l <= 40 { return s } return s[0:17] + "..." + s[l-20:l] } func (dr *FsDriver) ChangeDir(path string) error { path = dr.abs(path) if info, err := dr.up.GetInfo(path); err != nil { return err } else { if info.Type == "folder" { dr.curDir = dr.abs(path + "/") fmt.Println(dr.curDir) return nil } return errors.New(fmt.Sprintf("%s: Not a directory", path)) } } func (dr *FsDriver) GetCurDir() string { return dr.curDir } func (dr *FsDriver) getItem(src, des string) error { var dkInfo os.FileInfo var fd *os.File var upInfo *upyun.FileInfo var err error var wg sync.WaitGroup var skip bool = false if upInfo, err = dr.up.GetInfo(src); err != nil { return err } if dkInfo, err = os.Lstat(des); err == nil && dkInfo.Size() == upInfo.Size { skip = true } barSize := upInfo.Size // hack for empty file if barSize == 0 { barSize = 1 } bar := dr.progress.AddBar(int(barSize)).AppendCompleted() bar.PrependFunc(func(b *uiprogress.Bar) string { status := "WAIT" if skip { status = "SKIP" } else { if b.Current() == int(barSize) { status = "OK" } } if err != nil { return fmt.Sprintf("%-40s ERR %s", short(src), err) } return fmt.Sprintf("%-40s %+4s", short(src), status) }) wg.Add(1) go func() { v := 0 defer wg.Done() for { var verr error time.Sleep(time.Millisecond * 40) if dkInfo, verr = os.Lstat(des); verr == nil { v = int(dkInfo.Size()) } bar.Set(v) if v == int(upInfo.Size) { if v == 0 { bar.Set(1) } return } } }() if !skip { if fd, err = os.OpenFile(des, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0600); err == nil { defer fd.Close() if err = dr.up.Get(src, fd); err != nil { return err } } } wg.Wait() return err } func (dr *FsDriver) GetItems(src, des string) error { var ch chan *upyun.FileInfo src = dr.abs(src) if ok, err := dr.IsDir(src); err != nil { return err } else { if ok { ch = dr.up.GetLargeList(src, true) } else { ch = make(chan *upyun.FileInfo, 10) ch <- &upyun.FileInfo{ Type: "file", Name: "", } close(ch) } } var wg sync.WaitGroup for w := 0; w < dr.maxConc; w++ { wg.Add(1) go func() { defer wg.Done() for { upInfo, more := <-ch if !more { return } if upInfo.Type != "folder" { // if des is a directory, should add basename to des filename srcPath := src desPath := des if upInfo.Name != "" { srcPath += "/" + upInfo.Name desPath += "/" + upInfo.Name } else { if info, err := os.Lstat(des); err == nil && info.IsDir() { desPath += "/" + path.Base(srcPath) } } srcPath = dr.abs(srcPath) desPath = path.Clean(desPath) var err error if err = os.MkdirAll(path.Dir(desPath), os.ModePerm); err == nil { err = dr.getItem(srcPath, desPath) } } } }() } wg.Wait() return nil } func (dr *FsDriver) ListDir(path string) (infos []*upyun.FileInfo, err error) { path = dr.abs(path) if info, err := dr.up.GetInfo(path); err != nil { return nil, err } else { if info.Type != "folder" { return []*upyun.FileInfo{info}, nil } } ch := dr.up.GetLargeList(path, false) for k := 0; k < 1000; k++ { info, more := <-ch if !more { return infos[0:k], nil } infos = append(infos, info) } close(ch) return infos, nil } func (dr *FsDriver) MakeDir(path string) error { path = dr.abs(path) fmt.Println(path) if err := dr.up.Mkdir(path); err != nil { return err } return nil } func (dr *FsDriver) putItem(src, des string) error { var dkInfo os.FileInfo var upInfo *upyun.FileInfo var err error var skip bool = false var wg sync.WaitGroup if dkInfo, err = os.Lstat(src); err != nil { return err } if upInfo, err = dr.up.GetInfo(des); err == nil && dkInfo.Size() == upInfo.Size { skip = true } err = nil barSize := dkInfo.Size() if barSize == 0 { barSize = 1 } bar := dr.progress.AddBar(int(barSize)).AppendCompleted() bar.PrependFunc(func(b *uiprogress.Bar) string { status := "WAIT" if skip { status = "SKIP" } else { if b.Current() == int(barSize) { status = "OK" } } if err != nil { return fmt.Sprintf("%-40s ERR %s", short(des), err) } return fmt.Sprintf("%-40s %+4s", short(des), status) }) wg.Add(1) lock := new(sync.Mutex) go func() { defer wg.Done() for { time.Sleep(time.Millisecond * 20) lock.Lock() v := bar.Current() if v == int(barSize) || err != nil { lock.Unlock() return } add := 102400 if add+v < int(barSize)*98/100 { bar.Set(add + v) } lock.Unlock() } }() if !skip { var fd *os.File if fd, err = os.OpenFile(src, os.O_RDWR, 0600); err == nil { _, err = dr.up.Put(des, fd, false, "", "", nil) fd.Close() } } // hack if err == nil { lock.Lock() bar.Set(int(barSize)) lock.Unlock() } wg.Wait() return err } func (dr *FsDriver) PutItems(src, des string) error { var wg sync.WaitGroup ch := make(chan string, dr.maxConc+10) des = dr.abs(des) isUpDir, err := dr.IsDir(des) if err != nil && err.Error() != "404" { return err } srcInfo, err := os.Lstat(src) if err != nil { return err } // upload items to the directory which doesn't exist if strings.HasSuffix(des, "/") { isUpDir = true } for w := 0; w < dr.maxConc; w++ { wg.Add(1) go func() { defer wg.Done() for { srcPath, more := <-ch if !more { return } var desPath string desPath = des if isUpDir { if srcInfo.IsDir() { desPath += "/" + strings.Replace(srcPath, src, "", 1) } else { desPath += "/" + filepath.Base(srcPath) } } if strings.HasSuffix(desPath, "/") { panic(fmt.Sprintf("desPath should not HasSuffix with / %s", desPath)) } desPath = dr.abs(desPath) dr.putItem(srcPath, desPath) } }() } filepath.Walk(src, func(path string, info os.FileInfo, err error) error { if !info.IsDir() { ch <- path } return nil }) close(ch) wg.Wait() return nil } func (dr *FsDriver) Remove(path string) error { path = dr.abs(path) ok, err := dr.IsDir(path) if err != nil { return err } if ok { // remove all items in directory var wg sync.WaitGroup ch := dr.up.GetLargeList(path, true) // UPYUN Delete Limit Rate maxWorker := 1 for w := 0; w < maxWorker; w++ { wg.Add(1) go func() { defer wg.Done() for { info, more := <-ch if !more { return } desPath := dr.abs(path + "/" + info.Name) // TODO: retry if err := dr.up.Delete(desPath); err != nil { //TODO: error dr.logger.Printf("DELETE %s FAIL %v", desPath, err) } else { dr.logger.Printf("DELETE %s OK", desPath) } } }() } wg.Wait() } if err = dr.up.Delete(path); err != nil { dr.logger.Printf("DELETE %s FAIL %v", path, err) } else { dr.logger.Printf("DELETE %s OK", path) } // TODO: more information return nil } func (dr *FsDriver) IsDir(path string) (bool, error) { path = dr.abs(path) if strings.HasSuffix(path, "/") { path = path[0 : len(path)-1] } if info, err := dr.up.GetInfo(path); err != nil || info.Type != "folder" { return false, err } return true, nil } func (dr *FsDriver) abs(path string) string { if path[0] != '/' { path = dr.curDir + "/" + path } if strings.HasSuffix(path, "/.") || strings.HasSuffix(path, "/..") { path += "/" } size := 0 parts := strings.Split(path, "/") for _, p := range parts { switch p { case "", ".": continue case "..": size-- if size < 0 { return "/" } default: parts[size] = p size++ } } if size == 0 { return "/" } if strings.HasSuffix(path, "/") { return "/" + strings.Join(parts[0:size], "/") + "/" } return "/" + strings.Join(parts[0:size], "/") } //func (dr *FsDriver) limitConcRun(f func(ch chan interface{}, args ...string) error, args ...string) error { // var wg sync.WaitGroup // for w := 0; w < dr.maxConc; w++ { // wg.Add(1) // go func() { // defer wg.Done() // sargs := make([]string, len(args)) // for k, arg := range args { // sargs[k] = arg // } // }() // } // wg.Wait() //}
[ 4 ]
package update import ( "github.com/cjburchell/reefstatus/common/models" "github.com/cjburchell/reefstatus/controller/service" "github.com/cjburchell/reefstatus/controller/profilux" ) func currentPumps(controller *profilux.Controller, repo service.Controller) error { for i := 0; i < controller.GetCurrentPumpCount(); i++ { pump, err := repo.GetCurrentPump(models.GetID(models.CurrentPumpType, i)) if err != nil && err != service.ErrNotFound { return err } found := err != service.ErrNotFound isAssigned, err := controller.GetIsCurrentPumpAssigned(i) if isAssigned { if !found { pump = models.NewCurrentPump(i) } pump.Value, err = controller.GetCurrentPumpValue(pump.Index) if err != nil { return err } err = repo.SetCurrentPump(pump, !found) if err != nil { return err } } else { if found { err = repo.DeleteCurrentPump(pump) if err != nil { return err } } } } return nil }
[ 4 ]
package fetcher import ( "context" "encoding/json" "errors" "fmt" "net/http" "strconv" "strings" "sync" "sync/atomic" "time" "github.com/lionsoul2014/ip2region/binding/golang/ip2region" "github.com/qiniu/rpc.v3" xlog "github.com/qiniu/xlog.v1" "qbox.us/api/kmqcli" tblmgr "qbox.us/api/tblmgr.v2" "qbox.us/api/uc.v3" "qiniu.com/argus/AIProjects/wangan/yuqing" "qiniu.com/argus/com/uri" "qiniu.com/argus/com/util" qboxmac "qiniu.com/auth/qboxmac.v1" ) const ( OP_INPUT = "i" USER_CENTER_HOST = "http://uc.qbox.me" ) type KodoConfig struct { kmqcli.Config `json:"kmq"` TblMgrProxy string `json:"tblmgr_proxy"` UID uint32 `json:"uid"` QueueName string `json:"queue_name"` IPRegion string `json:"ipregion_db"` } type Kodo interface { Run(context.Context) AddItbl(context.Context, int, []string) error AddBlackList(context.Context, uint32, []string) error Message() chan yuqing.Message Buckets() []yuqing.BucketEntry BlackList() []yuqing.BucketEntry GetMetrics() yuqing.Metrics SetMaxVideoSize(size int) } type kodo struct { KodoConfig yuqing.Metrics //Nets []net.IPNet MsgChannel chan yuqing.Message partitions []int32 users []int buckets sync.Map // key:itbl black_list sync.Map maxVideoSize int ipregion *ip2region.Ip2Region } var _ Kodo = &kodo{} func NewKodo(conf KodoConfig) (Kodo, error) { ipregion, err := ip2region.New(conf.IPRegion) if err != nil { return nil, errors.New("create ipregion err:" + err.Error()) } return &kodo{ KodoConfig: conf, MsgChannel: make(chan yuqing.Message, 100), maxVideoSize: 10 * 1024 * 1024, ipregion: ipregion, }, nil } func (k *kodo) Run(ctx context.Context) { var ( xl = xlog.FromContextSafe(ctx) cli = kmqcli.New(&k.KodoConfig.Config) ) code, partitions, err := cli.GetQueuePartitions(k.UID, k.QueueName, xl) if err != nil || code != 200 { xl.Info("fail to get partitions, err: ", err) return } if len(partitions) == 0 { xl.Errorf("kmq partitions is empty") return } k.partitions = partitions for _, partition := range k.partitions { go func(ctx context.Context, partition int32) { xl := xlog.FromContextSafe(ctx) client := kmqcli.New(&k.KodoConfig.Config) index := 0 position := "@" for { code, messages, next, err := client.ConsumeMessagesByPartitonAdmin(k.UID, k.QueueName, position, 1000, partition, xl) if code == 612 || len(messages) == 0 { xl.Info("all message is consumed...") time.Sleep(1 * time.Second) break } if err != nil || code != 200 { xl.Info("fail to ConsumeMessagesAdmin, err: ", err) return } for _, m := range messages { var message yuqing.KmqMsg err := json.Unmarshal([]byte(m), &message) if err != nil { xl.Warnf("Json unmarshal err: %s, message: %s", err.Error(), m) } ip, port := ParseIpPortFromBase64(message.Object.IP) if message.Op == OP_INPUT { atomic.AddUint64(&k.Total, 1) //if strings.HasPrefix(message.Object.MimeType, "video/") && message.Object.FSize < 10*1024*1024 { if message.Object.MimeType != "video/MP2T" && (message.Object.MimeType == "application/x-mpegurl" || strings.HasPrefix(message.Object.MimeType, "video/")) && message.Object.FSize < int64(k.maxVideoSize) { //if message.Object.MimeType == "application/x-mpegurl" || strings.HasPrefix(message.Object.MimeType, "video/") { atomic.AddUint64(&k.TargetVideo, 1) info, err := k.ipregion.MemorySearch(ip.String()) if err != nil { xl.Warnf("fail to query ipregion (%s), error: %s", ip.String(), err.Error()) continue } if info.CityId == 995 || !uri.IsPublicIP(ip.String()) { atomic.AddUint64(&k.TargetRegion, 1) // target user var ( value interface{} bucket yuqing.BucketEntry ok bool e0 error itbl = strings.Split(message.Object.ID, ":")[0] ) if _, ok = k.black_list.Load(itbl); ok { atomic.AddUint64(&k.Unavailable, 1) continue } value, ok = k.buckets.Load(itbl) if !ok { if len(k.users) > 0 { continue } itbl_num, _ := strconv.ParseUint(itbl, 36, 32) if bucket, e0 = k.getBucketByItbl(ctx, uint32(itbl_num)); e0 != nil { xl.Errorf("fail to get bucket info by itbl %d, err: %s", itbl_num, e0.Error()) break } info, e1 := k.getBucketInfo(ctx, bucket.Uid, bucket.Name) if e1 != nil { xl.Errorf("fail to get bucket %s info through uc, uid %d, error: %s", bucket.Name, bucket.Uid, err.Error()) break } else { if info.Private == 1 || info.Protected == 1 { xl.Warnf("cache private bucket %s, uid %d, itbl %s", bucket.Name, bucket.Uid, itbl) atomic.AddUint64(&k.Unavailable, 1) k.black_list.LoadOrStore(itbl, bucket) break } } if bucket.Domains, e0 = k.getDomainsByTbl(ctx, bucket.Name, bucket.Uid); e0 != nil { xl.Errorf("failed to get domain for bucket %s, error: %s", bucket.Name, e0.Error()) break } k.buckets.Store(itbl, bucket) } else { bucket = value.(yuqing.BucketEntry) } atomic.AddUint64(&k.TargetUser, 1) ids := strings.Split(message.Object.ID, ":") var uri string if len(bucket.Domains) > 0 { uri = "http://" + bucket.Domains[0] + "/" + ids[1] } msg := yuqing.Message{ Bucket: bucket.Name, UID: bucket.Uid, Itbl: ids[0], Key: ids[1], MD5: ParseMD5FromBase64(message.Object.MD5), Fsize: message.Object.FSize, IP: ip.String(), Port: port, URI: uri, FH: message.Object.FH, MimeType: message.Object.MimeType, PutTime: time.Unix(message.Object.PutTime/10000000, message.Object.PutTime%10000000), } k.MsgChannel <- msg } if !uri.IsPublicIP(ip.String()) { atomic.AddUint64(&k.Inner, 1) } } } } index++ position = next } }(util.SpawnContext2(ctx, int(partition)), partition) } } func (k *kodo) Message() chan yuqing.Message { return k.MsgChannel } func (k *kodo) GetMetrics() yuqing.Metrics { return k.Metrics } func (k *kodo) SetMaxVideoSize(size int) { k.maxVideoSize = size } func (k *kodo) AddBlackList(ctx context.Context, uid uint32, bl_buckets []string) error { var ( xl = xlog.FromContextSafe(ctx) ) suInfo := fmt.Sprintf("%d/0", uid) transportMac := qboxmac.Mac{ AccessKey: k.AccessKey, SecretKey: []byte(k.SecretKey), } transport := qboxmac.NewAdminTransport(&transportMac, suInfo, nil) tbl := tblmgr.New(USER_CENTER_HOST, transport) entries, err := tbl.Buckets(xl, "z0") if err != nil { xl.Errorf("fail to call get buckets, error: %s", err.Error()) return err } for _, bucket := range entries { itbl := strconv.FormatUint(uint64(bucket.Itbl), 36) var found bool if len(bl_buckets) > 0 { for _, bl := range bl_buckets { if bl == bucket.Tbl { found = true } } } else { found = true } if found { k.black_list.Store(itbl, yuqing.BucketEntry{ Itbl: itbl, Name: bucket.Tbl, Uid: bucket.Uid, Zone: bucket.Zone, }) } } return nil } func (k *kodo) AddItbl(ctx context.Context, uid int, buckets []string) error { var ( xl = xlog.FromContextSafe(ctx) ) suInfo := fmt.Sprintf("%d/0", uid) transportMac := qboxmac.Mac{ AccessKey: k.AccessKey, SecretKey: []byte(k.SecretKey), } transport := qboxmac.NewAdminTransport(&transportMac, suInfo, nil) tbl := tblmgr.New(USER_CENTER_HOST, transport) entries, err := tbl.Buckets(xl, "z0") if err != nil { xl.Errorf("fail to call get buckets, error: %s", err.Error()) return err } fmt.Println("Entries:", entries) for _, bucket := range entries { var ( found bool ) if len(buckets) == 0 { found = true } else { for _, name := range buckets { if name == bucket.Tbl { found = true } } } if found { _, err := k.getBucketInfo(ctx, bucket.Uid, bucket.Tbl) //if err != nil || info.Private == 1 || info.Protected == 1 { if err != nil { continue } itbl := strconv.FormatUint(uint64(bucket.Itbl), 36) bucketInfo := yuqing.BucketEntry{ Itbl: itbl, Name: bucket.Tbl, Uid: bucket.Uid, Zone: bucket.Zone, } if bucketInfo.Domains, err = k.getDomainsByTbl(ctx, bucket.Tbl, uint32(uid)); err != nil { xl.Errorf("failed to get domain for bucket %s, error: %s", bucket.Tbl, err.Error()) return err } k.buckets.Store(itbl, bucketInfo) } } k.users = append(k.users, uid) return nil } func (k *kodo) Buckets() []yuqing.BucketEntry { var ret []yuqing.BucketEntry k.buckets.Range(func(key, value interface{}) bool { ret = append(ret, value.(yuqing.BucketEntry)) return true }) return ret } func (k *kodo) BlackList() []yuqing.BucketEntry { var ret []yuqing.BucketEntry k.black_list.Range(func(key, value interface{}) bool { ret = append(ret, value.(yuqing.BucketEntry)) return true }) return ret } func (k *kodo) getDomainsByTbl(ctx context.Context, tbl string, uid uint32) ([]string, error) { suInfo := fmt.Sprintf("%d/0", uid) transportMac := qboxmac.Mac{ AccessKey: k.AccessKey, SecretKey: []byte(k.SecretKey), } transport := qboxmac.NewAdminTransport(&transportMac, suInfo, nil) var domains = []struct { Domain string `json:"domain"` Tbl string `json:"tbl"` Global bool `json:"global"` }{} cli := rpc.Client{Client: &http.Client{Transport: transport}} err := cli.CallWithJson(ctx, &domains, "GET", fmt.Sprintf("http://api.qiniu.com/v7/domain/list?tbl=%s", tbl), nil) if err != nil { return nil, err } var ret []string for _, domain := range domains { if !strings.HasPrefix(domain.Domain, ".") { ret = append(ret, domain.Domain) } } return ret, nil } func (k *kodo) getBucketByItbl(ctx context.Context, itbl uint32) (bucket yuqing.BucketEntry, err error) { cli := rpc.Client{Client: &http.Client{}} var ret tblmgr.BucketEntry err = cli.CallWithJson(ctx, &ret, "GET", k.TblMgrProxy+"/itblbucket/"+strconv.Itoa(int(itbl)), nil) if err != nil { return yuqing.BucketEntry{}, err } bucket = yuqing.BucketEntry{ Itbl: strconv.FormatUint(uint64(ret.Itbl), 36), Name: ret.Tbl, Uid: ret.Uid, Zone: ret.Zone, } return } func (k *kodo) getBucketInfo(ctx context.Context, uid uint32, bucket string) (uc.BucketInfo, error) { suInfo := fmt.Sprintf("%d/0", uid) transportMac := qboxmac.Mac{ AccessKey: k.AccessKey, SecretKey: []byte(k.SecretKey), } transport := qboxmac.NewAdminTransport(&transportMac, suInfo, nil) cli := uc.New([]string{"http://uc.qbox.me"}, transport) return cli.BucketInfo(xlog.FromContextSafe(ctx), bucket) }
[ 4 ]
// Copyright (c) 2014 Couchbase, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. package bleve import ( "io/ioutil" "os" "testing" "time" ) type Address struct { Street string `json:"street"` City string `json:"city"` State string `json:"state"` Zip string `json:"zip"` } type Person struct { Identifier string `json:"id"` Name string `json:"name"` Age float64 `json:"age"` Title string `json:"title"` Birthday time.Time `json:"birthday"` Address *Address `json:"address"` Hideouts []*Address `json:"hideouts"` Tags []string `json:"tags"` } func (p *Person) Type() string { return "person" } var nameMapping = NewDocumentMapping(). AddFieldMapping(NewFieldMapping("", "text", "en", true, true, true, true)) var tagsMapping = NewDocumentMapping(). AddFieldMapping(NewFieldMapping("", "text", "standard", true, true, true, false)) var personMapping = NewDocumentMapping(). AddSubDocumentMapping("name", nameMapping). AddSubDocumentMapping("id", NewDocumentDisabledMapping()). AddSubDocumentMapping("tags", tagsMapping) var mapping = NewIndexMapping(). AddDocumentMapping("person", personMapping) var people = []*Person{ &Person{ Identifier: "a", Name: "marty", Age: 19, // has no birthday set to test handling of zero time Title: "mista", Tags: []string{"gopher", "belieber"}, }, &Person{ Identifier: "b", Name: "steve has a long name", Age: 27, Birthday: time.Unix(1000000000, 0), Title: "missess", }, &Person{ Identifier: "c", Name: "bob walks home", Age: 64, Birthday: time.Unix(1400000000, 0), Title: "masta", }, &Person{ Identifier: "d", Name: "bobbleheaded wings top the phone", Age: 72, Birthday: time.Unix(1400000000, 0), Title: "mizz", }, } // FIXME needs more assertions func TestIndex(t *testing.T) { defer os.RemoveAll("testidx") index, err := New("testidx", mapping) if err != nil { t.Fatal(err) } defer index.Close() // index all the people for _, person := range people { err = index.Index(person.Identifier, person) if err != nil { t.Error(err) } } termQuery := NewTermQuery("marti").SetField("name") searchRequest := NewSearchRequest(termQuery) searchResult, err := index.Search(searchRequest) if err != nil { t.Error(err) } if searchResult.Total != uint64(1) { t.Errorf("expected 1 total hit for term query, got %d", searchResult.Total) } else { if searchResult.Hits[0].ID != "a" { t.Errorf("expected top hit id 'a', got '%s'", searchResult.Hits[0].ID) } } termQuery = NewTermQuery("noone").SetField("name") searchRequest = NewSearchRequest(termQuery) searchResult, err = index.Search(searchRequest) if err != nil { t.Error(err) } if searchResult.Total != uint64(0) { t.Errorf("expected 0 total hits") } matchPhraseQuery := NewMatchPhraseQuery("long name") searchRequest = NewSearchRequest(matchPhraseQuery) searchResult, err = index.Search(searchRequest) if err != nil { t.Error(err) } if searchResult.Total != uint64(1) { t.Errorf("expected 1 total hit for phrase query, got %d", searchResult.Total) } else { if searchResult.Hits[0].ID != "b" { t.Errorf("expected top hit id 'b', got '%s'", searchResult.Hits[0].ID) } } termQuery = NewTermQuery("walking").SetField("name") searchRequest = NewSearchRequest(termQuery) searchResult, err = index.Search(searchRequest) if err != nil { t.Error(err) } if searchResult.Total != uint64(0) { t.Errorf("expected 0 total hits") } matchQuery := NewMatchQuery("walking").SetField("name") searchRequest = NewSearchRequest(matchQuery) searchResult, err = index.Search(searchRequest) if err != nil { t.Error(err) } if searchResult.Total != uint64(1) { t.Errorf("expected 1 total hit for match query, got %d", searchResult.Total) } else { if searchResult.Hits[0].ID != "c" { t.Errorf("expected top hit id 'c', got '%s'", searchResult.Hits[0].ID) } } prefixQuery := NewPrefixQuery("bobble").SetField("name") searchRequest = NewSearchRequest(prefixQuery) searchResult, err = index.Search(searchRequest) if err != nil { t.Error(err) } if searchResult.Total != uint64(1) { t.Errorf("expected 1 total hit for prefix query, got %d", searchResult.Total) } else { if searchResult.Hits[0].ID != "d" { t.Errorf("expected top hit id 'd', got '%s'", searchResult.Hits[0].ID) } } syntaxQuery := NewSyntaxQuery("+name:phone") searchRequest = NewSearchRequest(syntaxQuery) searchResult, err = index.Search(searchRequest) if err != nil { t.Error(err) } if searchResult.Total != uint64(1) { t.Errorf("expected 1 total hit for syntax query, got %d", searchResult.Total) } else { if searchResult.Hits[0].ID != "d" { t.Errorf("expected top hit id 'd', got '%s'", searchResult.Hits[0].ID) } } maxAge := 30.0 numericRangeQuery := NewNumericRangeQuery(nil, &maxAge).SetField("age") searchRequest = NewSearchRequest(numericRangeQuery) searchResult, err = index.Search(searchRequest) if err != nil { t.Error(err) } if searchResult.Total != uint64(2) { t.Errorf("expected 2 total hits for numeric range query, got %d", searchResult.Total) } else { if searchResult.Hits[0].ID != "b" { t.Errorf("expected top hit id 'b', got '%s'", searchResult.Hits[0].ID) } if searchResult.Hits[1].ID != "a" { t.Errorf("expected next hit id 'a', got '%s'", searchResult.Hits[1].ID) } } startDate = "2010-01-01" dateRangeQuery := NewDateRangeQuery(&startDate, nil).SetField("birthday") searchRequest = NewSearchRequest(dateRangeQuery) searchResult, err = index.Search(searchRequest) if err != nil { t.Error(err) } if searchResult.Total != uint64(2) { t.Errorf("expected 2 total hits for numeric range query, got %d", searchResult.Total) } else { if searchResult.Hits[0].ID != "d" { t.Errorf("expected top hit id 'd', got '%s'", searchResult.Hits[0].ID) } if searchResult.Hits[1].ID != "c" { t.Errorf("expected next hit id 'c', got '%s'", searchResult.Hits[1].ID) } } // test that 0 time doesn't get indexed endDate = "2010-01-01" dateRangeQuery = NewDateRangeQuery(nil, &endDate).SetField("birthday") searchRequest = NewSearchRequest(dateRangeQuery) searchResult, err = index.Search(searchRequest) if err != nil { t.Error(err) } if searchResult.Total != uint64(1) { t.Errorf("expected 1 total hit for numeric range query, got %d", searchResult.Total) } else { if searchResult.Hits[0].ID != "b" { t.Errorf("expected top hit id 'b', got '%s'", searchResult.Hits[0].ID) } } // test behavior of arrays // make sure we can successfully find by all elements in array termQuery = NewTermQuery("gopher").SetField("tags") searchRequest = NewSearchRequest(termQuery) searchResult, err = index.Search(searchRequest) if err != nil { t.Error(err) } else { if searchResult.Total != uint64(1) { t.Errorf("expected 1 total hit for term query, got %d", searchResult.Total) } else { if searchResult.Hits[0].ID != "a" { t.Errorf("expected top hit id 'a', got '%s'", searchResult.Hits[0].ID) } } } termQuery = NewTermQuery("belieber").SetField("tags") searchRequest = NewSearchRequest(termQuery) searchResult, err = index.Search(searchRequest) if err != nil { t.Error(err) } else { if searchResult.Total != uint64(1) { t.Errorf("expected 1 total hit for term query, got %d", searchResult.Total) } else { if searchResult.Hits[0].ID != "a" { t.Errorf("expected top hit id 'a', got '%s'", searchResult.Hits[0].ID) } } } termQuery = NewTermQuery("notintagsarray").SetField("tags") searchRequest = NewSearchRequest(termQuery) searchResult, err = index.Search(searchRequest) if err != nil { t.Error(err) } if searchResult.Total != uint64(0) { t.Errorf("expected 0 total hits") } // lookup document a // expect to find 2 values for field "tags" tagsCount := 0 doc, err := index.Document("a") if err != nil { t.Error(err) } else { for _, f := range doc.Fields { if f.Name() == "tags" { tagsCount++ } } } if tagsCount != 2 { t.Errorf("expected to find 2 values for tags") } } func TestIndexCreateNewOverExisting(t *testing.T) { defer os.RemoveAll("testidx") index, err := New("testidx", NewIndexMapping()) if err != nil { t.Fatal(err) } index.Close() index, err = New("testidx", NewIndexMapping()) if err != ERROR_INDEX_PATH_EXISTS { t.Fatalf("expected error index path exists, got %v", err) } } func TestIndexOpenNonExisting(t *testing.T) { _, err := Open("doesnotexist") if err != ERROR_INDEX_PATH_DOES_NOT_EXIST { t.Fatalf("expected error index path does not exist, got %v", err) } } func TestIndexOpenMetaMissingOrCorrupt(t *testing.T) { defer os.RemoveAll("testidx") index, err := New("testidx", NewIndexMapping()) if err != nil { t.Fatal(err) } index.Close() // now intentionally corrupt the metadata ioutil.WriteFile("testidx/index_meta.json", []byte("corrupted"), 0666) index, err = Open("testidx") if err != ERROR_INDEX_META_CORRUPT { t.Fatalf("expected error index metadata corrupted, got %v", err) } // no intentionally remove the metadata os.Remove("testidx/index_meta.json") index, err = Open("testidx") if err != ERROR_INDEX_META_MISSING { t.Fatalf("expected error index metadata missing, got %v", err) } }
[ 4 ]
// Code generated by mockery v1.0.0. DO NOT EDIT. package mocks import ( pingdom "github.com/jsdidierlaurent/go-pingdom/pingdom" mock "github.com/stretchr/testify/mock" ) // PingdomTransactionCheckAPI is an autogenerated mock type for the PingdomTransactionCheckAPI type type PingdomTransactionCheckAPI struct { mock.Mock } // List provides a mock function with given fields: params func (_m *PingdomTransactionCheckAPI) List(params ...map[string]string) ([]pingdom.TransactionCheckResponse, error) { _va := make([]interface{}, len(params)) for _i := range params { _va[_i] = params[_i] } var _ca []interface{} _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 []pingdom.TransactionCheckResponse if rf, ok := ret.Get(0).(func(...map[string]string) []pingdom.TransactionCheckResponse); ok { r0 = rf(params...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]pingdom.TransactionCheckResponse) } } var r1 error if rf, ok := ret.Get(1).(func(...map[string]string) error); ok { r1 = rf(params...) } else { r1 = ret.Error(1) } return r0, r1 } // Read provides a mock function with given fields: id func (_m *PingdomTransactionCheckAPI) Read(id int) (*pingdom.TransactionCheckResponse, error) { ret := _m.Called(id) var r0 *pingdom.TransactionCheckResponse if rf, ok := ret.Get(0).(func(int) *pingdom.TransactionCheckResponse); ok { r0 = rf(id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*pingdom.TransactionCheckResponse) } } var r1 error if rf, ok := ret.Get(1).(func(int) error); ok { r1 = rf(id) } else { r1 = ret.Error(1) } return r0, r1 }
[ 4 ]
package controllers import ( "strings" "github.com/astaxie/beego" ) const ( headerAccessToken = "Access-Token" headerRefreshToken = "Refresh-Token" headerUser = "User" ) func sendResponse(c *beego.Controller, statusCode int, reason error, body interface{}) { c.Ctx.ResponseWriter.WriteHeader(statusCode) if reason != nil { c.Data["json"] = reason.Error() } else { if body != nil { c.Data["json"] = body } } c.ServeJSON() } func getHeader(c *beego.Controller, h string) string { return c.Ctx.Input.Header(h) } type requestHeader struct { accessToken string refreshToken string platform string user string } func parseHeader(c *beego.Controller) requestHeader { h := requestHeader{ accessToken: c.Ctx.Input.Header(headerAccessToken), refreshToken: c.Ctx.Input.Header(headerRefreshToken), user: c.Ctx.Input.Header(headerUser), } v := strings.Split(h.user, "/") if len(v) == 2 { h.platform = v[0] } return h }
[ 4 ]
package editbox import ( "io" "os" "time" "github.com/nsf/termbox-go" ) type Editbox struct { currentX int currentY int offsetLeft int offsetTop int width int height int lines *EditLine currentLine *EditLine fileName string } func (this *Editbox) GetNumLines() int { countLines := 0 iter := this.lines for iter != nil { countLines++ iter = iter.nextLine } return countLines } func (this *Editbox) Init() { this.lines = &EditLine{0, []rune{}, nil, nil} this.currentLine = this.lines this.offsetLeft = 3 this.offsetTop = 2 this.currentX = this.offsetLeft this.currentY = this.offsetTop this.width, this.height = termbox.Size() this.fileName = "./testest.txt" termbox.SetInputMode(termbox.InputAlt | termbox.InputMouse | termbox.InputEsc) termbox.SetCursor(this.offsetLeft, this.offsetTop) termbox.Flush() } func (this *Editbox) InsertTabAtCurrentPos() { for i := 0; i < 4; i++ { this.InsertCharAtCurrentPos(' ') } } func (this *Editbox) MoveCursorUp() { if this.currentY-1-this.offsetTop >= 0 { this.currentY-- } if this.currentLine.prevLine != nil { this.currentLine = this.currentLine.prevLine this.ShowAllText() } if this.currentX-this.offsetLeft >= this.currentLine.GetLen() { this.currentX = this.currentLine.GetLen() + this.offsetLeft } this.updateCursor() } func (this *Editbox) MoveCursorDown() { if this.currentY+1 <= this.height && this.currentLine.nextLine != nil { this.currentY++ } if this.currentLine.nextLine != nil { this.currentLine = this.currentLine.nextLine this.ShowAllText() } if this.currentX-this.offsetLeft >= this.currentLine.GetLen() { this.currentX = this.currentLine.GetLen() + this.offsetLeft } this.updateCursor() } func (this *Editbox) MoveCursorLeft() { if this.currentX-1-this.offsetLeft >= 0 { this.currentX-- } else { if this.currentY-1-this.offsetTop >= 0 { if this.currentY-1-this.offsetTop >= 0 { this.currentY-- } if this.currentLine.prevLine != nil { this.currentLine = this.currentLine.prevLine } this.currentX = this.currentLine.GetLen() + this.offsetLeft } } this.updateCursor() } func (this *Editbox) MoveCursorRight() { if this.currentX-this.offsetLeft < this.currentLine.GetLen() { this.currentX++ } else { if this.currentY+1-this.offsetTop < this.GetNumLines() { if this.currentLine.nextLine != nil { this.currentLine = this.currentLine.nextLine } if this.currentY+1 < this.height { this.currentY++ } this.currentX = this.offsetLeft } } this.updateCursor() } func (this *Editbox) SetWindowSize() { this.width, this.height = termbox.Size() } func (this *Editbox) writeToFile(filename string, data string) error { file, err := os.Create(filename) if err != nil { return err } defer file.Close() _, err = io.WriteString(file, data) if err != nil { return err } return file.Sync() } func (this *Editbox) SaveToFile() { strBuffer := "" iter := this.lines for iter != nil { strBuffer += string(iter.text) + "\n" iter = iter.nextLine } this.writeToFile(this.fileName, strBuffer) } func (this *Editbox) BreakNewLine() { if this.currentLine != nil { newLine := this.currentLine.SliceAt(this.currentX - this.offsetLeft) iter := newLine.nextLine for iter != nil { iter.idLine += 1 iter = iter.nextLine } if this.currentY+1 < this.height { this.currentY++ } this.currentLine = newLine this.currentX = this.offsetLeft this.updateCursor() termbox.Flush() } } func (this *Editbox) BlindCursor() { for { termbox.SetCursor(this.currentX, this.currentY) termbox.Flush() time.Sleep(500 * time.Millisecond) termbox.HideCursor() termbox.Flush() time.Sleep(500 * time.Millisecond) } } func (this *Editbox) updateCursor() { termbox.SetCursor(this.currentX, this.currentY) termbox.Flush() } func (this *Editbox) InsertCharAtCurrentPos(char rune) { if this.currentLine != nil { this.currentLine.InsertAt(this.currentX-this.offsetLeft, char) this.currentX++ this.updateCursor() termbox.Flush() } } func (this *Editbox) DeleteCharAtCurrentPos() { if this.currentLine != nil { var savePreLineLen = 0 if this.currentY != this.offsetTop { savePreLineLen = this.currentLine.prevLine.GetLen() } this.currentLine.DeleteCharAt(this.currentX - 1 - this.offsetLeft) if this.currentX <= this.offsetLeft { if this.currentY != this.offsetTop { this.currentX = savePreLineLen + this.offsetLeft if this.currentY-1-this.offsetTop >= 0 { this.currentY-- } if this.currentLine.prevLine != nil { this.currentLine = this.currentLine.prevLine } lastLine := this.GetLastLine() if lastLine != nil { for i := range lastLine.text { termbox.SetCell(i+this.offsetLeft, lastLine.idLine+1, 0, termbox.ColorDefault, termbox.ColorDefault) } } } } else { this.currentX-- } } this.updateCursor() } func (this *Editbox) GetLastLine() *EditLine { iter := this.lines if iter != nil && iter.nextLine != nil { iter = iter.nextLine } return iter } func countNums(num int) int { count := 1 for num >= 10 { num /= 10 count++ } return count } func (this *Editbox) ShowNumLine(yPos int, line *EditLine) { lineId := line.GetLineId() lenLineId := len(lineId) newOffset := countNums(this.GetNumLines()) + 3 // print space before num line numSpace := newOffset - lenLineId - 2 // print num line for i, num := range lineId { termbox.SetCell(i+numSpace, yPos, num, termbox.ColorYellow, termbox.ColorDefault) } termbox.SetCell(lenLineId+numSpace, yPos, 9475, termbox.ColorMagenta, termbox.ColorBlack) termbox.SetCell(lenLineId+numSpace+1, yPos, ' ', termbox.ColorDefault, termbox.ColorDefault) if this.offsetLeft != newOffset { this.currentX += newOffset - this.offsetLeft } this.offsetLeft = newOffset } func (this *Editbox) ShowAllText() { termbox.Clear(termbox.ColorDefault, termbox.ColorDefault) termbox.Flush() yPos := this.currentY iterLine := this.currentLine for yPos >= this.offsetTop { if iterLine != nil { this.ShowNumLine(yPos, iterLine) for i, char := range iterLine.text { termbox.SetCell(i+this.offsetLeft, yPos, char, termbox.ColorDefault, termbox.ColorDefault) } iterLine = iterLine.prevLine } yPos-- } yPos = this.currentY iterLine = this.currentLine for yPos < this.height { if iterLine != nil { this.ShowNumLine(yPos, iterLine) for i, char := range iterLine.text { termbox.SetCell(i+this.offsetLeft, yPos, char, termbox.ColorDefault, termbox.ColorDefault) } iterLine = iterLine.nextLine } yPos++ } termbox.Flush() }
[ 4 ]
/* Copyright (c) 2017 VMware, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package simulator import ( "context" "reflect" "testing" "github.com/vmware/govmomi" "github.com/vmware/govmomi/find" "github.com/vmware/govmomi/object" "github.com/vmware/govmomi/simulator/esx" "github.com/vmware/govmomi/simulator/vpx" "github.com/vmware/govmomi/vim25" "github.com/vmware/govmomi/vim25/methods" "github.com/vmware/govmomi/vim25/mo" "github.com/vmware/govmomi/vim25/soap" "github.com/vmware/govmomi/vim25/types" ) func addStandaloneHostTask(folder *object.Folder, spec types.HostConnectSpec) (*object.Task, error) { // TODO: add govmomi wrapper req := types.AddStandaloneHost_Task{ This: folder.Reference(), Spec: spec, AddConnected: true, } res, err := methods.AddStandaloneHost_Task(context.TODO(), folder.Client(), &req) if err != nil { return nil, err } task := object.NewTask(folder.Client(), res.Returnval) return task, nil } func TestFolderESX(t *testing.T) { content := esx.ServiceContent s := New(NewServiceInstance(SpoofContext(), content, esx.RootFolder)) ts := s.NewServer() defer ts.Close() ctx := context.Background() c, err := govmomi.NewClient(ctx, ts.URL, true) if err != nil { t.Fatal(err) } f := object.NewRootFolder(c.Client) _, err = f.CreateFolder(ctx, "foo") if err == nil { t.Error("expected error") } _, err = f.CreateDatacenter(ctx, "foo") if err == nil { t.Error("expected error") } finder := find.NewFinder(c.Client, false) dc, err := finder.DatacenterOrDefault(ctx, "") if err != nil { t.Fatal(err) } folders, err := dc.Folders(ctx) if err != nil { t.Fatal(err) } spec := types.HostConnectSpec{} _, err = addStandaloneHostTask(folders.HostFolder, spec) if err == nil { t.Fatal("expected error") } _, err = folders.DatastoreFolder.CreateStoragePod(ctx, "pod") if err == nil { t.Fatal("expected error") } } func TestFolderVC(t *testing.T) { content := vpx.ServiceContent s := New(NewServiceInstance(SpoofContext(), content, vpx.RootFolder)) ts := s.NewServer() defer ts.Close() ctx := context.Background() c, err := govmomi.NewClient(ctx, ts.URL, true) if err != nil { t.Fatal(err) } f := object.NewRootFolder(c.Client) ff, err := f.CreateFolder(ctx, "foo") if err != nil { t.Error(err) } dc, err := f.CreateDatacenter(ctx, "bar") if err != nil { t.Error(err) } for _, ref := range []object.Reference{ff, dc} { o := Map.Get(ref.Reference()) if o == nil { t.Fatalf("failed to find %#v", ref) } e := o.(mo.Entity).Entity() if *e.Parent != f.Reference() { t.Fail() } } dc, err = ff.CreateDatacenter(ctx, "biz") if err != nil { t.Error(err) } folders, err := dc.Folders(ctx) if err != nil { t.Fatal(err) } _, err = folders.VmFolder.CreateStoragePod(ctx, "pod") if err == nil { t.Error("expected error") } _, err = folders.DatastoreFolder.CreateStoragePod(ctx, "pod") if err != nil { t.Error(err) } tests := []struct { name string state types.TaskInfoState }{ {"", types.TaskInfoStateError}, {"foo.local", types.TaskInfoStateSuccess}, } for _, test := range tests { spec := types.HostConnectSpec{ HostName: test.name, } task, err := addStandaloneHostTask(folders.HostFolder, spec) if err != nil { t.Fatal(err) } res, err := task.WaitForResult(ctx, nil) if test.state == types.TaskInfoStateError { if err == nil { t.Error("expected error") } if res.Result != nil { t.Error("expected nil") } } else { if err != nil { t.Fatal(err) } ref, ok := res.Result.(types.ManagedObjectReference) if !ok { t.Errorf("expected moref, got type=%T", res.Result) } host := Map.Get(ref).(*HostSystem) if host.Name != test.name { t.Fail() } if ref == esx.HostSystem.Self { t.Error("expected new host Self reference") } if *host.Summary.Host == esx.HostSystem.Self { t.Error("expected new host summary Self reference") } pool := Map.Get(*host.Parent).(*mo.ComputeResource).ResourcePool if *pool == esx.ResourcePool.Self { t.Error("expected new pool Self reference") } } if res.State != test.state { t.Fatalf("%s", res.State) } } } func TestFolderSpecialCharaters(t *testing.T) { content := vpx.ServiceContent s := New(NewServiceInstance(SpoofContext(), content, vpx.RootFolder)) ts := s.NewServer() defer ts.Close() ctx := context.Background() c, err := govmomi.NewClient(ctx, ts.URL, true) if err != nil { t.Fatal(err) } f := object.NewRootFolder(c.Client) tests := []struct { name string expected string }{ {`/`, `%2f`}, {`\`, `%5c`}, {`%`, `%25`}, // multiple special characters {`%%`, `%25%25`}, } for _, test := range tests { ff, err := f.CreateFolder(ctx, test.name) if err != nil { t.Fatal(err) } o := Map.Get(ff.Reference()) if o == nil { t.Fatalf("failed to find %#v", ff) } e := o.(mo.Entity).Entity() if e.Name != test.expected { t.Errorf("expected %s, got %s", test.expected, e.Name) } } } func TestFolderFaults(t *testing.T) { f := Folder{} f.ChildType = []string{"VirtualMachine"} if f.CreateFolder(nil, nil).Fault() == nil { t.Error("expected fault") } if f.CreateDatacenter(nil, nil).Fault() == nil { t.Error("expected fault") } } func TestRegisterVm(t *testing.T) { ctx := context.Background() for i, model := range []*Model{ESX(), VPX()} { match := "*" if i == 1 { model.App = 1 match = "*APP*" } defer model.Remove() err := model.Create() if err != nil { t.Fatal(err) } s := model.Service.NewServer() defer s.Close() c, err := govmomi.NewClient(ctx, s.URL, true) if err != nil { t.Fatal(err) } finder := find.NewFinder(c.Client, false) dc, err := finder.DefaultDatacenter(ctx) if err != nil { t.Fatal(err) } finder.SetDatacenter(dc) folders, err := dc.Folders(ctx) if err != nil { t.Fatal(err) } vmFolder := folders.VmFolder vms, err := finder.VirtualMachineList(ctx, match) if err != nil { t.Fatal(err) } vm := Map.Get(vms[0].Reference()).(*VirtualMachine) req := types.RegisterVM_Task{ This: vmFolder.Reference(), AsTemplate: true, } steps := []struct { e interface{} f func() }{ { new(types.InvalidArgument), func() { req.AsTemplate = false }, }, { new(types.InvalidArgument), func() { req.Pool = vm.ResourcePool }, }, { new(types.InvalidArgument), func() { req.Path = "enoent" }, }, { new(types.InvalidDatastorePath), func() { req.Path = vm.Config.Files.VmPathName + "-enoent" }, }, { new(types.NotFound), func() { req.Path = vm.Config.Files.VmPathName }, }, { new(types.AlreadyExists), func() { Map.Remove(SpoofContext(), vm.Reference()) }, }, { nil, func() {}, }, } for _, step := range steps { res, err := methods.RegisterVM_Task(ctx, c.Client, &req) if err != nil { t.Fatal(err) } ct := object.NewTask(c.Client, res.Returnval) _ = ct.Wait(ctx) rt := Map.Get(res.Returnval).(*Task) if step.e != nil { fault := rt.Info.Error.Fault if reflect.TypeOf(fault) != reflect.TypeOf(step.e) { t.Errorf("%T != %T", fault, step.e) } } else { if rt.Info.Error != nil { t.Errorf("unexpected error: %#v", rt.Info.Error) } } step.f() } nvm, err := finder.VirtualMachine(ctx, vm.Name) if err != nil { t.Fatal(err) } if nvm.Reference() == vm.Reference() { t.Error("expected new moref") } onTask, _ := nvm.PowerOn(ctx) _ = onTask.Wait(ctx) steps = []struct { e interface{} f func() }{ { types.InvalidPowerState{}, func() { offTask, _ := nvm.PowerOff(ctx); _ = offTask.Wait(ctx) }, }, { nil, func() {}, }, { types.ManagedObjectNotFound{}, func() {}, }, } for _, step := range steps { err = nvm.Unregister(ctx) if step.e != nil { fault := soap.ToSoapFault(err).VimFault() if reflect.TypeOf(fault) != reflect.TypeOf(step.e) { t.Errorf("%T != %T", fault, step.e) } } else { if err != nil { t.Errorf("unexpected error: %#v", err) } } step.f() } } } func TestFolderMoveInto(t *testing.T) { ctx := context.Background() model := VPX() defer model.Remove() err := model.Create() if err != nil { t.Fatal(err) } s := model.Service.NewServer() defer s.Close() c, err := govmomi.NewClient(ctx, s.URL, true) if err != nil { t.Fatal(err) } finder := find.NewFinder(c.Client, false) dc, err := finder.DefaultDatacenter(ctx) if err != nil { t.Fatal(err) } finder.SetDatacenter(dc) folders, err := dc.Folders(ctx) if err != nil { t.Fatal(err) } ds, err := finder.DefaultDatastore(ctx) if err != nil { t.Fatal(err) } // Move Datastore into a vm folder should fail task, err := folders.VmFolder.MoveInto(ctx, []types.ManagedObjectReference{ds.Reference()}) if err != nil { t.Fatal(err) } err = task.Wait(ctx) if err == nil { t.Errorf("expected error") } // Move Datacenter into a sub folder should pass f, err := object.NewRootFolder(c.Client).CreateFolder(ctx, "foo") if err != nil { t.Error(err) } task, _ = f.MoveInto(ctx, []types.ManagedObjectReference{dc.Reference()}) err = task.Wait(ctx) if err != nil { t.Error(err) } pod, err := folders.DatastoreFolder.CreateStoragePod(ctx, "pod") if err != nil { t.Error(err) } // Moving any type other than Datastore into a StoragePod should fail task, _ = pod.MoveInto(ctx, []types.ManagedObjectReference{dc.Reference()}) err = task.Wait(ctx) if err == nil { t.Error("expected error") } // Move DS into a StoragePod task, _ = pod.MoveInto(ctx, []types.ManagedObjectReference{ds.Reference()}) err = task.Wait(ctx) if err != nil { t.Error(err) } } func TestFolderCreateDVS(t *testing.T) { ctx := context.Background() model := VPX() defer model.Remove() err := model.Create() if err != nil { t.Fatal(err) } s := model.Service.NewServer() defer s.Close() c, err := govmomi.NewClient(ctx, s.URL, true) if err != nil { t.Fatal(err) } finder := find.NewFinder(c.Client, false) dc, err := finder.DefaultDatacenter(ctx) if err != nil { t.Fatal(err) } finder.SetDatacenter(dc) folders, err := dc.Folders(ctx) if err != nil { t.Fatal(err) } var spec types.DVSCreateSpec spec.ConfigSpec = &types.VMwareDVSConfigSpec{} spec.ConfigSpec.GetDVSConfigSpec().Name = "foo" task, err := folders.NetworkFolder.CreateDVS(ctx, spec) if err != nil { t.Fatal(err) } err = task.Wait(ctx) if err != nil { t.Error(err) } net, err := finder.Network(ctx, "foo") if err != nil { t.Error(err) } dvs, ok := net.(*object.DistributedVirtualSwitch) if !ok { t.Fatalf("%T is not of type %T", net, dvs) } task, err = folders.NetworkFolder.CreateDVS(ctx, spec) if err != nil { t.Fatal(err) } err = task.Wait(ctx) if err == nil { t.Error("expected error") } pspec := types.DVPortgroupConfigSpec{Name: "xnet"} task, err = dvs.AddPortgroup(ctx, []types.DVPortgroupConfigSpec{pspec}) if err != nil { t.Fatal(err) } err = task.Wait(ctx) if err != nil { t.Error(err) } net, err = finder.Network(ctx, "xnet") if err != nil { t.Error(err) } pg, ok := net.(*object.DistributedVirtualPortgroup) if !ok { t.Fatalf("%T is not of type %T", net, pg) } backing, err := net.EthernetCardBackingInfo(ctx) if err != nil { t.Fatal(err) } info, ok := backing.(*types.VirtualEthernetCardDistributedVirtualPortBackingInfo) if ok { if info.Port.SwitchUuid == "" || info.Port.PortgroupKey == "" { t.Errorf("invalid port: %#v", info.Port) } } else { t.Fatalf("%T is not of type %T", net, info) } task, err = dvs.AddPortgroup(ctx, []types.DVPortgroupConfigSpec{pspec}) if err != nil { t.Fatal(err) } err = task.Wait(ctx) if err == nil { t.Error("expected error") } } func TestPlaceVmsXCluster(t *testing.T) { vpx := VPX() vpx.Cluster = 3 Test(func(ctx context.Context, c *vim25.Client) { finder := find.NewFinder(c, false) spec := types.PlaceVmsXClusterSpec{} pools, err := finder.ResourcePoolList(ctx, "/DC0/host/DC0_C*/*") if err != nil { t.Fatal(err) } for _, pool := range pools { spec.ResourcePools = append(spec.ResourcePools, pool.Reference()) } spec.VmPlacementSpecs = []types.PlaceVmsXClusterSpecVmPlacementSpec{{ ConfigSpec: types.VirtualMachineConfigSpec{ Name: "test-vm", }, }} folder := object.NewRootFolder(c) res, err := folder.PlaceVmsXCluster(ctx, spec) if err != nil { t.Fatal(err) } if len(res.PlacementInfos) != len(spec.VmPlacementSpecs) { t.Errorf("%d PlacementInfos vs %d VmPlacementSpecs", len(res.PlacementInfos), len(spec.VmPlacementSpecs)) } }, vpx) }
[ 4 ]
package log import ( "github.com/astaxie/beego/logs" "os" "path/filepath" "syscall" ) func InitLog(runMode string, dirs ...string) *logs.BeeLogger { DefaultLog = logs.NewLogger() DefaultLog.EnableFuncCallDepth(true) DefaultLog.SetLogFuncCallDepth(3) if runMode == "dev" { DefaultLog.SetLogger(logs.AdapterConsole) } else { workPath, err := os.Getwd() if err != nil { panic(err) } logDir := filepath.Join(workPath) for _, dir := range dirs { logDir = filepath.Join(logDir, dir) if !isPathExist(logDir) { oldMask := syscall.Umask(0) err = os.Mkdir(logDir, 0755) if err != nil { println(err.Error(), logDir) panic(err) } syscall.Umask(oldMask) } } logFile := filepath.Join(logDir, "log.txt") if !isPathExist(logDir) { oldMask := syscall.Umask(0) err = os.Mkdir(logDir, 0755) if err != nil { println(err.Error(), logDir) panic(err) } f, err := os.Create(logFile) if err != nil { println(err.Error(), logFile) panic(err) } f.Close() syscall.Umask(oldMask) } else { if !isPathExist(logFile) { f, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0755) if err != nil { println(err.Error(), logFile) panic(err) } f.Close() } } configs := `{"filename":"` + logFile + `","separate":["emergency", "alert", "critical", "error", "warning", "notice", "info", "debug"]}` err = DefaultLog.SetLogger(logs.AdapterMultiFile, configs) if err != nil { println(err.Error()) panic(err) } } return DefaultLog }
[ 4 ]
// Code generated by mockery v1.0.0. DO NOT EDIT. package mocks import ( configmodels "github.com/monitoror/monitoror/api/config/models" mock "github.com/stretchr/testify/mock" models "github.com/monitoror/monitoror/monitorables/pingdom/api/models" monitorormodels "github.com/monitoror/monitoror/models" ) // Usecase is an autogenerated mock type for the Usecase type type Usecase struct { mock.Mock } // Check provides a mock function with given fields: params func (_m *Usecase) Check(params *models.CheckParams) (*monitorormodels.Tile, error) { ret := _m.Called(params) var r0 *monitorormodels.Tile if rf, ok := ret.Get(0).(func(*models.CheckParams) *monitorormodels.Tile); ok { r0 = rf(params) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*monitorormodels.Tile) } } var r1 error if rf, ok := ret.Get(1).(func(*models.CheckParams) error); ok { r1 = rf(params) } else { r1 = ret.Error(1) } return r0, r1 } // CheckGenerator provides a mock function with given fields: params func (_m *Usecase) CheckGenerator(params interface{}) ([]configmodels.GeneratedTile, error) { ret := _m.Called(params) var r0 []configmodels.GeneratedTile if rf, ok := ret.Get(0).(func(interface{}) []configmodels.GeneratedTile); ok { r0 = rf(params) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]configmodels.GeneratedTile) } } var r1 error if rf, ok := ret.Get(1).(func(interface{}) error); ok { r1 = rf(params) } else { r1 = ret.Error(1) } return r0, r1 } // TransactionCheck provides a mock function with given fields: params func (_m *Usecase) TransactionCheck(params *models.TransactionCheckParams) (*monitorormodels.Tile, error) { ret := _m.Called(params) var r0 *monitorormodels.Tile if rf, ok := ret.Get(0).(func(*models.TransactionCheckParams) *monitorormodels.Tile); ok { r0 = rf(params) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*monitorormodels.Tile) } } var r1 error if rf, ok := ret.Get(1).(func(*models.TransactionCheckParams) error); ok { r1 = rf(params) } else { r1 = ret.Error(1) } return r0, r1 } // TransactionCheckGenerator provides a mock function with given fields: params func (_m *Usecase) TransactionCheckGenerator(params interface{}) ([]configmodels.GeneratedTile, error) { ret := _m.Called(params) var r0 []configmodels.GeneratedTile if rf, ok := ret.Get(0).(func(interface{}) []configmodels.GeneratedTile); ok { r0 = rf(params) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]configmodels.GeneratedTile) } } var r1 error if rf, ok := ret.Get(1).(func(interface{}) error); ok { r1 = rf(params) } else { r1 = ret.Error(1) } return r0, r1 }
[ 4 ]
package groups import ( "fmt" "gowork/controllers" . "gowork/models/groups" "gowork/utils" "strconv" "strings" //"time" "github.com/astaxie/beego" "github.com/astaxie/beego/utils/pagination" ) //组管理 type ManageGroupController struct { controllers.BaseController } func (this *ManageGroupController) Get() { //权限检测 if !strings.Contains(this.GetSession("userPermission").(string), "group-manage") { this.Abort("401") } page, err := this.GetInt("p") if err != nil { page = 1 } offset, err1 := beego.AppConfig.Int("pageoffset") if err1 != nil { offset = 15 } keywords := this.GetString("keywords") condArr := make(map[string]string) condArr["keywords"] = keywords countGroup := CountGroup(condArr) paginator := pagination.SetPaginator(this.Ctx, offset, countGroup) _, _, groups := ListGroup(condArr, page, offset) this.Data["paginator"] = paginator this.Data["condArr"] = condArr this.Data["groups"] = groups this.Data["countGroup"] = countGroup this.TplName = "groups/index.tpl" } type FormGroupController struct { controllers.BaseController } func (this *FormGroupController) Get() { idstr := this.Ctx.Input.Param(":id") if "" != idstr { //权限检测 if !strings.Contains(this.GetSession("userPermission").(string), "group-edit") { this.Abort("401") } id, _ := strconv.ParseInt(idstr, 10, 64) group, _ := GetGroup(int64(id)) this.Data["group"] = group } else { //权限检测 if !strings.Contains(this.GetSession("userPermission").(string), "group-add") { this.Abort("401") } } this.TplName = "groups/form.tpl" } func (this *FormGroupController) Post() { //权限检测 name := this.GetString("name") if "" == name { this.Data["json"] = map[string]interface{}{"code": 0, "message": "请填写组名称"} this.ServeJSON() return } summary := this.GetString("summary") var group Groups group.Name = name group.Summary = summary groupid, _ := this.GetInt64("id") var err error if groupid <= 0 { groupid = utils.SnowFlakeId() group.Id = groupid err = AddGroup(group) } else { err = UpdateGroup(groupid, group) } if err == nil { this.Data["json"] = map[string]interface{}{"code": 1, "message": "操作成功", "id": fmt.Sprintf("%d", groupid)} } else { this.Data["json"] = map[string]interface{}{"code": 0, "message": "添加失败"} } this.ServeJSON() } type AjaxDeleteGroupController struct { controllers.BaseController } func (this *AjaxDeleteGroupController) Post() { //权限检测 if !strings.Contains(this.GetSession("userPermission").(string), "group-delete") { this.Data["json"] = map[string]interface{}{"code": 0, "message": "无权设置"} this.ServeJSON() return } ids := this.GetString("ids") if "" == ids { this.Data["json"] = map[string]interface{}{"code": 0, "message": "请选择要删除的选项"} this.ServeJSON() return } err := DeleteGroup(ids) if err == nil { this.Data["json"] = map[string]interface{}{"code": 1, "message": "删除成功"} } else { this.Data["json"] = map[string]interface{}{"code": 0, "message": "删除失败"} } this.ServeJSON() }
[ 4 ]
// Copyright (C) 2012-2023 Miquel Sabaté Solà <[email protected]> // This file is licensed under the MIT license. // See the LICENSE file. package user_agent import ( "strings" ) // OSInfo represents full information on the operating system extracted from the // user agent. type OSInfo struct { // Full name of the operating system. This is identical to the output of ua.OS() FullName string // Name of the operating system. This is sometimes a shorter version of the // operating system name, e.g. "Mac OS X" instead of "Intel Mac OS X" Name string // Operating system version, e.g. 7 for Windows 7 or 10.8 for Max OS X Mountain Lion Version string } // Normalize the name of the operating system. By now, this just // affects to Windows NT. // // Returns a string containing the normalized name for the Operating System. func normalizeOS(name string) string { sp := strings.SplitN(name, " ", 3) if len(sp) != 3 || sp[1] != "NT" { return name } switch sp[2] { case "5.0": return "Windows 2000" case "5.01": return "Windows 2000, Service Pack 1 (SP1)" case "5.1": return "Windows XP" case "5.2": return "Windows XP x64 Edition" case "6.0": return "Windows Vista" case "6.1": return "Windows 7" case "6.2": return "Windows 8" case "6.3": return "Windows 8.1" case "10.0": return "Windows 10" } return name } // Guess the OS, the localization and if this is a mobile device for a // Webkit-powered browser. // // The first argument p is a reference to the current UserAgent and the second // argument is a slice of strings containing the comment. func webkit(p *UserAgent, comment []string) { if p.platform == "webOS" { p.browser.Name = p.platform p.os = "Palm" if len(comment) > 2 { p.localization = comment[2] } p.mobile = true } else if p.platform == "Symbian" { p.mobile = true p.browser.Name = p.platform p.os = comment[0] } else if p.platform == "Linux" { p.mobile = true if p.browser.Name == "Safari" { p.browser.Name = "Android" } if len(comment) > 1 { if comment[1] == "U" || comment[1] == "arm_64" { if len(comment) > 2 { p.os = comment[2] } else { p.mobile = false p.os = comment[0] } } else { p.os = comment[1] } } if len(comment) > 3 { p.localization = comment[3] } else if len(comment) == 3 { _ = p.googleOrBingBot() } } else if len(comment) > 0 { if len(comment) > 3 { p.localization = comment[3] } if strings.HasPrefix(comment[0], "Windows NT") { p.os = normalizeOS(comment[0]) } else if len(comment) < 2 { p.localization = comment[0] } else if len(comment) < 3 { if !p.googleOrBingBot() && !p.iMessagePreview() { p.os = normalizeOS(comment[1]) } } else { p.os = normalizeOS(comment[2]) } if p.platform == "BlackBerry" { p.browser.Name = p.platform if p.os == "Touch" { p.os = p.platform } } } // Special case for Firefox on iPad, where the platform is advertised as Macintosh instead of iPad if p.platform == "Macintosh" && p.browser.Engine == "AppleWebKit" && p.browser.Name == "Firefox" { p.platform = "iPad" p.mobile = true } } // Guess the OS, the localization and if this is a mobile device // for a Gecko-powered browser. // // The first argument p is a reference to the current UserAgent and the second // argument is a slice of strings containing the comment. func gecko(p *UserAgent, comment []string) { if len(comment) > 1 { if comment[1] == "U" || comment[1] == "arm_64" { if len(comment) > 2 { p.os = normalizeOS(comment[2]) } else { p.os = normalizeOS(comment[1]) } } else { if strings.Contains(p.platform, "Android") { p.mobile = true p.platform, p.os = normalizeOS(comment[1]), p.platform } else if comment[0] == "Mobile" || comment[0] == "Tablet" { p.mobile = true p.os = "FirefoxOS" } else { if p.os == "" { p.os = normalizeOS(comment[1]) } } } // Only parse 4th comment as localization if it doesn't start with rv:. // For example Firefox on Ubuntu contains "rv:XX.X" in this field. if len(comment) > 3 && !strings.HasPrefix(comment[3], "rv:") { p.localization = comment[3] } } } // Guess the OS, the localization and if this is a mobile device // for Internet Explorer. // // The first argument p is a reference to the current UserAgent and the second // argument is a slice of strings containing the comment. func trident(p *UserAgent, comment []string) { // Internet Explorer only runs on Windows. p.platform = "Windows" // The OS can be set before to handle a new case in IE11. if p.os == "" { if len(comment) > 2 { p.os = normalizeOS(comment[2]) } else { p.os = "Windows NT 4.0" } } // Last but not least, let's detect if it comes from a mobile device. for _, v := range comment { if strings.HasPrefix(v, "IEMobile") { p.mobile = true return } } } // Guess the OS, the localization and if this is a mobile device // for Opera. // // The first argument p is a reference to the current UserAgent and the second // argument is a slice of strings containing the comment. func opera(p *UserAgent, comment []string) { slen := len(comment) if strings.HasPrefix(comment[0], "Windows") { p.platform = "Windows" p.os = normalizeOS(comment[0]) if slen > 2 { if slen > 3 && strings.HasPrefix(comment[2], "MRA") { p.localization = comment[3] } else { p.localization = comment[2] } } } else { if strings.HasPrefix(comment[0], "Android") { p.mobile = true } p.platform = comment[0] if slen > 1 { p.os = comment[1] if slen > 3 { p.localization = comment[3] } } else { p.os = comment[0] } } } // Guess the OS. Android browsers send Dalvik as the user agent in the // request header. // // The first argument p is a reference to the current UserAgent and the second // argument is a slice of strings containing the comment. func dalvik(p *UserAgent, comment []string) { slen := len(comment) if strings.HasPrefix(comment[0], "Linux") { p.platform = comment[0] if slen > 2 { p.os = comment[2] } p.mobile = true } } // Given the comment of the first section of the UserAgent string, // get the platform. func getPlatform(comment []string) string { if len(comment) > 0 { if comment[0] != "compatible" { if strings.HasPrefix(comment[0], "Windows") { return "Windows" } else if strings.HasPrefix(comment[0], "Symbian") { return "Symbian" } else if strings.HasPrefix(comment[0], "webOS") { return "webOS" } else if comment[0] == "BB10" { return "BlackBerry" } return comment[0] } } return "" } // Detect some properties of the OS from the given section. func (p *UserAgent) detectOS(s section) { if s.name == "Mozilla" { // Get the platform here. Be aware that IE11 provides a new format // that is not backwards-compatible with previous versions of IE. p.platform = getPlatform(s.comment) if p.platform == "Windows" && len(s.comment) > 0 { p.os = normalizeOS(s.comment[0]) } // And finally get the OS depending on the engine. switch p.browser.Engine { case "": p.undecided = true case "Gecko": gecko(p, s.comment) case "AppleWebKit": webkit(p, s.comment) case "Trident": trident(p, s.comment) } } else if s.name == "Opera" { if len(s.comment) > 0 { opera(p, s.comment) } } else if s.name == "Dalvik" { if len(s.comment) > 0 { dalvik(p, s.comment) } } else if s.name == "okhttp" { p.mobile = true p.browser.Name = "OkHttp" p.browser.Version = s.version } else { // Check whether this is a bot or just a weird browser. p.undecided = true } } // Platform returns a string containing the platform.. func (p *UserAgent) Platform() string { return p.platform } // OS returns a string containing the name of the Operating System. func (p *UserAgent) OS() string { return p.os } // Localization returns a string containing the localization. func (p *UserAgent) Localization() string { return p.localization } // Model returns a string containing the Phone Model like "Nexus 5X" func (p *UserAgent) Model() string { return p.model } // Return OS name and version from a slice of strings created from the full name of the OS. func osName(osSplit []string) (name, version string) { if len(osSplit) == 1 { name = osSplit[0] version = "" } else { // Assume version is stored in the last part of the array. nameSplit := osSplit[:len(osSplit)-1] version = osSplit[len(osSplit)-1] // Nicer looking Mac OS X if len(nameSplit) >= 2 && nameSplit[0] == "Intel" && nameSplit[1] == "Mac" { nameSplit = nameSplit[1:] } name = strings.Join(nameSplit, " ") if strings.Contains(version, "x86") || strings.Contains(version, "i686") { // x86_64 and i868 are not Linux versions but architectures version = "" } else if version == "X" && name == "Mac OS" { // X is not a version for Mac OS. name = name + " " + version version = "" } } return name, version } // OSInfo returns combined information for the operating system. func (p *UserAgent) OSInfo() OSInfo { // Special case for iPhone weirdness os := strings.Replace(p.os, "like Mac OS X", "", 1) os = strings.Replace(os, "CPU", "", 1) os = strings.Trim(os, " ") osSplit := strings.Split(os, " ") // Special case for x64 edition of Windows if os == "Windows XP x64 Edition" { osSplit = osSplit[:len(osSplit)-2] } name, version := osName(osSplit) // Special case for names that contain a forward slash version separator. if strings.Contains(name, "/") { s := strings.Split(name, "/") name = s[0] version = s[1] } // Special case for versions that use underscores version = strings.Replace(version, "_", ".", -1) return OSInfo{ FullName: p.os, Name: name, Version: version, } }
[ 4 ]
package twitch_chat_filter import ( irc "github.com/fluffle/goirc/client" ui "github.com/gizak/termui" "github.com/spf13/cobra" "fmt" "os" "time" "github.com/karlseguin/ccache" "strconv" "strings" ) type IrcMessage struct { Nick string Message string } func (self *IrcMessage) toString() string { return self.Nick + ": " + self.Message } type UILayoutState struct { Header *ui.Par ChatHistory *ChatHistory ChatBox *ChatBox MinuteStats *MessageStatsChart HourStats *MessageStatsChart MessageRateWidget *ui.Sparklines MinuteMessageRate *MessageRateSparkline HourMessageRate *MessageRateSparkline SecondsChatAggregator *ChatAggregator MinuteChatAggregator *ChatAggregator MessageStream <-chan *IrcMessage IrcConn *irc.Conn } func (self *UILayoutState) buildBody() { par := ui.NewPar("penis") par.Height = 10 par.Width = 10 ui.Body.AddRows( ui.NewRow( ui.NewCol(4, 0, self.MessageRateWidget, self.MinuteStats.Widget, self.HourStats.Widget, self.SecondsChatAggregator.Widget, self.MinuteChatAggregator.Widget), ui.NewCol(8, 0, self.Header, self.ChatHistory.Widget, self.ChatBox.Widget), ), ) } func RegisterIrcAndUiHandlers(c *irc.Conn) (quits chan bool, msgs chan *IrcMessage, typings chan string) { // Add handlers to do things here! // e.g. join a channel on connect. quits = make(chan bool) msgs = make(chan *IrcMessage) typings = make(chan string) c.HandleFunc(irc.CONNECTED, func(conn *irc.Conn, line *irc.Line) { ch := "#" + IrcChannel conn.Join(ch) }, ) // And a signal on disconnect c.HandleFunc(irc.DISCONNECTED, func(conn *irc.Conn, line *irc.Line) { quits <- true }, ) // Put all messages into the messages channel c.HandleFunc(irc.PRIVMSG, func(conn *irc.Conn, line *irc.Line) { message := strings.Join(line.Args[1:], "") msgs <- &IrcMessage{line.Nick, message} }, ) c.HandleFunc(irc.PING, func(conn *irc.Conn, line *irc.Line) { conn.Pong(line.Host) }, ) ui.Handle("/sys/kbd/C-c", func(ui.Event) { ui.StopLoop() ui.Close() os.Exit(0) }) ui.Handle("/sys/kbd", func(kbdEvent ui.Event) { // Could also be handled with state machine. inputStr := kbdEvent.Data.(ui.EvtKbd).KeyStr typings <- inputStr }) ui.Handle("/timer/1s", func(e ui.Event) { ui.Clear() ui.Body.Align() ui.Render(ui.Body) }) go func() { for { _ = <- time.Tick(5 * time.Second) if !c.Connected() { err := c.Connect() if err == nil { c.Join("#"+IrcChannel) } } } }() return quits, msgs, typings } func (self *UILayoutState) InitBodyAndLoop() { self.buildBody() ui.Clear() ui.Body.Align() ui.Render(ui.Body) ui.Loop() } func NewUILayoutState() *UILayoutState { err := ui.Init() if err != nil { panic(err) } c := ircConn() quits, messages, typings := RegisterIrcAndUiHandlers(c) // Tell client to connect. if err = c.Connect(); err != nil { fmt.Printf("Connection error: %s\n", err.Error()) } minuteCounter, err := NewSlidingWindowCounter(3 * time.Second, 60) if err != nil { fmt.Println(err.Error()) os.Exit(1) } hourCounter, err := NewSlidingWindowCounter(1 * time.Minute, 60) if err != nil { fmt.Println(err.Error()) os.Exit(1) } minuteMessageRate := NewMessageRateSparkline(ui.ColorCyan, minuteCounter) hourMessageRate := NewMessageRateSparkline(ui.ColorYellow, hourCounter) messageRateWidget := ui.NewSparklines(*minuteMessageRate.Widget, *hourMessageRate.Widget) messageRateWidget.Height = 8 messageRateWidget.BorderFg = ui.ColorDefault header := ui.NewPar("PRESS ctrl+c TO QUIT") header.Height = 3 header.Width = 30 header.TextFgColor = ui.ColorDefault header.BorderLabel = "Twitch Chat Filterer" header.BorderFg = ui.ColorCyan uiState := UILayoutState{ Header: header, ChatHistory: NewChatHistory(), ChatBox: NewChatBox(typings, messages, c), MinuteStats: NewMessageStatsChart(ui.ColorCyan, ui.ColorRed, minuteCounter), HourStats: NewMessageStatsChart(ui.ColorYellow, ui.ColorMagenta, hourCounter), MessageRateWidget: messageRateWidget, MinuteMessageRate: minuteMessageRate, HourMessageRate: hourMessageRate, SecondsChatAggregator: NewChatAggregator(ui.ColorCyan, 10 * time.Second), MinuteChatAggregator: NewChatAggregator(ui.ColorYellow, 1 * time.Minute), MessageStream: messages, IrcConn: c, } go func() { for { msg := <-uiState.MessageStream // increment counters, update buffers, rerender views uiState.HourMessageRate.IncrementAndRender(uiState.MessageRateWidget) uiState.MinuteMessageRate.IncrementAndRender(uiState.MessageRateWidget) uiState.MessageRateWidget.Lines[0] = *uiState.MinuteMessageRate.Widget uiState.MessageRateWidget.Lines[1] = *uiState.HourMessageRate.Widget uiState.MinuteStats.Render() uiState.HourStats.Render() uiState.ChatHistory.UpdateAndRender(msg) uiState.SecondsChatAggregator.SortedMessages.Increment(msg.Message, uiState.SecondsChatAggregator.TTL) uiState.MinuteChatAggregator.SortedMessages.Increment(msg.Message, uiState.MinuteChatAggregator.TTL) } }() go func() { for { _ = <- quits uiState.ChatHistory.updateAndRender("<<<WARNING: CHAT DISCONNECTED. Reconnecting in a few seconds...>>>") } }() return &uiState } type ChatBox struct { Widget *ui.Par DefaultMessage string Data string Input <-chan string } func NewChatBox(input <-chan string, messages chan<- *IrcMessage, c *irc.Conn) *ChatBox { defaultText := "Start typing, press Enter to send message" widget := ui.NewPar(defaultText) widget.Height = 3 widget.Width = 30 widget.TextFgColor = ui.ColorDefault widget.BorderLabel = "Chat" widget.BorderFg = ui.ColorDefault go func() { for { typing := <-input if typing == "C-8" { // backspace if widget.Text == defaultText { widget.Text = "" } else { if len(widget.Text) > 0 { widget.Text = widget.Text[:len(widget.Text)-1] } } } else if typing == "<enter>" { c.Privmsg("#"+IrcChannel, widget.Text) messages <- &IrcMessage{ Nick: IrcUser, Message: widget.Text, } widget.Text = "" } else { if widget.Text == defaultText { widget.Text = ReplaceText(typing) } else { widget.Text = widget.Text + ReplaceText(typing) } } ui.Render(widget) } }() return &ChatBox{ Widget: widget, DefaultMessage: defaultText, Data: defaultText, Input: input, } } func ReplaceText(input string) string { if input == "<space>" { return " " } else { return input } } type ChatHistory struct { Widget *ui.List ChatHistoryData []string Size int FilteredMessagesSet *ccache.Cache } func NewChatHistory() *ChatHistory { uiMessageBuffer := make([]string, 32) widget := ui.NewList() widget.Width = 10 widget.Height = 34 widget.BorderLabel = "Chat History" widget.BorderFg = ui.ColorDefault widget.ItemFgColor = ui.ColorDefault widget.Items = uiMessageBuffer return &ChatHistory{ Widget : widget, ChatHistoryData: uiMessageBuffer, FilteredMessagesSet: ccache.New(ccache.Configure()), } } func (self *ChatHistory) UpdateAndRender(msg *IrcMessage) { if !self.shouldFilter(msg) { self.updateAndRender(msg.toString()) } } func (self *ChatHistory) updateAndRender(msg string) { self.ChatHistoryData = append(self.ChatHistoryData, msg) if len(self.ChatHistoryData) > self.Size { self.ChatHistoryData = self.ChatHistoryData[1:] } self.Widget.Items = self.ChatHistoryData ui.Render(self.Widget) } func (self *ChatHistory) shouldFilter(msg *IrcMessage) bool { if FilterDuplicates { if self.FilteredMessagesSet.Get(msg.Message) != nil { return true } else { self.FilteredMessagesSet.Set(msg.Message, true, FilterDuplicateTTL) return false } } else { return false } } type ChatAggregator struct { TTL time.Duration Widget *ui.List SortedMessages *SortedMessages } func NewChatAggregator(textColor ui.Attribute, ttl time.Duration) *ChatAggregator { widget := ui.NewList() trendingMessages := NewSortedMessages(20, 2) widget.Width = 10 widget.Height = 10 printedTime := ttl / time.Second widget.BorderLabel = "Trending (" + strconv.FormatInt(int64(printedTime), 10) + " secs)" widget.BorderFg = ui.ColorDefault widget.ItemFgColor = ui.ColorDefault widget.Items = trendingMessages.View widget.ItemFgColor = textColor go func() { for { _ = <-trendingMessages.NotifyViewChange widget.Items = trendingMessages.View ui.Render(widget) } }() return &ChatAggregator{ TTL: ttl, Widget: widget, SortedMessages: trendingMessages, } } type MessageStatsChart struct { Widget *ui.BarChart Counter *SlidingWindowCounter } func NewMessageStatsChart(barColor, numColor ui.Attribute, counter *SlidingWindowCounter) *MessageStatsChart { statsWidget := ui.NewBarChart() labels := []string{ "Min", "Max", "Avg", } statsWidget.BorderLabel = "Stats (~ 3 min)" statsWidget.Data = counter.Stats statsWidget.Width = 10 statsWidget.BarGap = 1 statsWidget.BarWidth = 4 statsWidget.Height = 6 statsWidget.DataLabels = labels statsWidget.TextColor = ui.ColorDefault statsWidget.BarColor = barColor statsWidget.NumColor = numColor statsWidget.BorderFg = ui.ColorDefault return &MessageStatsChart{ Widget: statsWidget, Counter: counter, } } func (self *MessageStatsChart) Render() { self.Widget.Data = self.Counter.Stats ui.Render(self.Widget) } type MessageRateSparkline struct { Widget *ui.Sparkline Counter *SlidingWindowCounter } func NewMessageRateSparkline(color ui.Attribute, counter *SlidingWindowCounter) *MessageRateSparkline { widget := ui.NewSparkline() widget.Data = counter.Data formattedTime := strconv.Itoa(counter.NumWindows * int(counter.Window) / int(time.Minute)) widget.Title = "Message Rate (~ " + formattedTime + " Minutes)" widget.Height = 2 widget.LineColor = color widget.TitleColor = ui.ColorGreen return &MessageRateSparkline{ Widget: &widget, Counter: counter, } } func (self *MessageRateSparkline) IncrementAndRender(sparklines *ui.Sparklines) { self.Counter.Increment() // Update UI View data buffers self.Widget.Data = self.Counter.Data ui.Render(sparklines) } func ircConn() *irc.Conn { cfg := irc.NewConfig(IrcUser) if IrcUser == "" || IrcServerHost == "" || IrcChannel == "" { TwitchCmd.Help() os.Exit(-1) } if IrcPassword != "" { cfg.Pass = IrcPassword } cfg.Server = IrcServerHost + ":" + IrcServerPort c := irc.Client(cfg) return c } func Start(cmd *cobra.Command, args []string) { uiState := NewUILayoutState() uiState.InitBodyAndLoop() }
[ 4 ]
// Code generated by mockery v1.0.0. DO NOT EDIT. package mocks import entities "go-clean-architecture-demo/app/entities" import mock "github.com/stretchr/testify/mock" // Repository is an autogenerated mock type for the Repository type type Repository struct { mock.Mock } // Create provides a mock function with given fields: _a0 func (_m *Repository) Create(_a0 *entities.User) (uint, error) { ret := _m.Called(_a0) var r0 uint if rf, ok := ret.Get(0).(func(*entities.User) uint); ok { r0 = rf(_a0) } else { r0 = ret.Get(0).(uint) } var r1 error if rf, ok := ret.Get(1).(func(*entities.User) error); ok { r1 = rf(_a0) } else { r1 = ret.Error(1) } return r0, r1 } // GetByPhoneNumber provides a mock function with given fields: id func (_m *Repository) GetByPhoneNumber(id int64) (entities.User, error) { ret := _m.Called(id) var r0 entities.User if rf, ok := ret.Get(0).(func(int64) entities.User); ok { r0 = rf(id) } else { r0 = ret.Get(0).(entities.User) } var r1 error if rf, ok := ret.Get(1).(func(int64) error); ok { r1 = rf(id) } else { r1 = ret.Error(1) } return r0, r1 } // List provides a mock function with given fields: skip, limit func (_m *Repository) List(skip int, limit int) ([]*entities.User, error) { ret := _m.Called(skip, limit) var r0 []*entities.User if rf, ok := ret.Get(0).(func(int, int) []*entities.User); ok { r0 = rf(skip, limit) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*entities.User) } } var r1 error if rf, ok := ret.Get(1).(func(int, int) error); ok { r1 = rf(skip, limit) } else { r1 = ret.Error(1) } return r0, r1 } // Update provides a mock function with given fields: condition, _a1 func (_m *Repository) Update(condition *entities.User, _a1 *entities.User) (uint, error) { ret := _m.Called(condition, _a1) var r0 uint if rf, ok := ret.Get(0).(func(*entities.User, *entities.User) uint); ok { r0 = rf(condition, _a1) } else { r0 = ret.Get(0).(uint) } var r1 error if rf, ok := ret.Get(1).(func(*entities.User, *entities.User) error); ok { r1 = rf(condition, _a1) } else { r1 = ret.Error(1) } return r0, r1 }
[ 4 ]
package builder import ( "bytes" "encoding/json" "errors" "fmt" "go/build" "go/parser" "go/token" "net/http" "os" "os/exec" "path/filepath" "regexp" "strconv" "strings" "github.com/ulrichSchreiner/carpo/workspace/filesystem" ) type goCommand string const ( goCommand_build goCommand = "install" goCommand_vet goCommand = "vet" goCommand_env goCommand = "env" goCommand_test goCommand = "test" workdir = ".carpowork" abssrc = "/src/" godoc_org = "http://api.godoc.org" goerr_cantloadpackage = "can't load package: " ) var ( build_line = regexp.MustCompile("(.*?):(\\d*(:\\d*)?): (.*)") go_file_postfix = []byte(".go") expected_declaration = regexp.MustCompile(`found 'IDENT' (\w*)`) ) func (ws *GoWorkspace) findPackageFromDirectory(dir string) (string, error) { for _, gp := range ws.GoPath { srcdir := filepath.Join(gp, "src") if strings.HasPrefix(dir, srcdir) { return filepath.Rel(srcdir, dir) } } return "", fmt.Errorf("Directory '%s' not found in GOPATH (%+v)", dir, ws.GoPath) } func (ws *GoWorkspace) findDirectoryFromPackage(p string) string { return filepath.Join("src", p) } func (ws *GoWorkspace) search(def filesystem.WorkspaceFS, cwd, pt string) (filesystem.WorkspaceFS, string, error) { if strings.HasPrefix(pt, "../src") { return def, pt[2:], nil } if strings.HasPrefix(pt, def.Base()) { return def, pt[len(def.Base()):], nil } abspath := filepath.Clean(filepath.Join(cwd, pt)) for _, wfs := range ws.filesystems { if strings.HasPrefix(abspath, wfs.Base()) { return wfs, abspath[len(wfs.Base()):], nil } } return nil, "", fmt.Errorf("cannot find %s/%s in filesystems", cwd, pt) } func (ws *GoWorkspace) addDependency(p *build.Package, needs []string) { ws.dependencies[p.ImportPath] = needs } func (ws *GoWorkspace) addTestDependency(p *build.Package, needs []string) { ws.testdependencies[p.ImportPath] = needs } func (ws *GoWorkspace) resolveDeps(deps *map[string][]string, needs *map[string][]string) { for p, pkgs := range *deps { for _, pack := range pkgs { packs, ok := (*needs)[pack] if !ok { packs = []string{p} } else { packs = append(packs, p) } (*needs)[pack] = packs } } } func (ws *GoWorkspace) packageHasTests(packname string) bool { p, ok := ws.Packages[packname] if ok { return len(p.TestGoFiles) > 0 } return false } func (ws *GoWorkspace) resolve() { ws.resolveDeps(&ws.dependencies, &ws.neededBy) ws.resolveDeps(&ws.testdependencies, &ws.testneededBy) } func (ws *GoWorkspace) importSystemPackage(packname string, path string) error { // systempackages are only imported at startup time so we only import them once _, ok := ws.SystemPackages[packname] if ok { return nil } pack, err := ws.context.Import(packname, path, 0) if err != nil { return err } else { ws.SystemPackages[packname] = pack } return nil } func (ws *GoWorkspace) importPackage(packname string, path string) error { pack, err := ws.context.Import(packname, path, 0) if err != nil { return err } else { ws.Packages[packname] = pack ws.addDependency(pack, pack.Imports) ws.addTestDependency(pack, pack.TestImports) } return nil } type srcDir struct { fs filesystem.WorkspaceFS workspace *GoWorkspace importer func(string, string) error path string relpath string } func (src *srcDir) walker(path string, info os.FileInfo, err error) error { if info != nil && !info.IsDir() { if bytes.Compare([]byte(strings.ToLower(filepath.Ext(info.Name()))), go_file_postfix) == 0 { // we have a go file :-) //TODO: check if this directory was already imported rel, err := filepath.Rel(src.path, path) if err != nil { // the walker found a subdir of "src.path" but filepath.Rel says no ... // this cannot happen, but if this happens, something terrible happend ... } else { packname := filepath.Dir(rel) src.importer(packname, path) src.workspace.Typeserver.AddPackage(src.fs, filepath.Join(src.relpath, packname), packname) } } } return nil } func (ws *GoWorkspace) mergeBuildResults(compiledPackages []string, res []BuildResult) (bs []BuildResult) { m := make(map[string]bool) for _, s := range compiledPackages { m[s] = true } for _, br := range ws.Build { if _, ok := m[br.PackageImportPath]; !ok { bs = append(bs, br) } } for _, br := range res { if !containsBuildResult(bs, br) { bs = append(bs, br) } } return } func containsBuildResult(results []BuildResult, br BuildResult) bool { for _, b := range results { if b == br { return true } } return false } func (ws *GoWorkspace) gocmd(gobin string, command string, dir string, args ...string) (string, error) { arguments := []string{command} arguments = append(arguments, args...) cmd := exec.Command(gobin, arguments...) cmd.Dir = dir cmd.Env = []string{fmt.Sprintf("GOPATH=%s", ws.context.GOPATH), fmt.Sprintf("PATH=%s", os.ExpandEnv("$PATH"))} buildLogger.Debugf("execute %#v", cmd) res, err := cmd.CombinedOutput() if err != nil { // check if the command resulted with an error-exit code if _, ok := err.(*exec.ExitError); !ok { // no Exit-Error --> a fundamental problem occured return "", err } } return string(res), nil } func (ws *GoWorkspace) plugin(command string, dir string, args ...string) (string, error) { cmd := exec.Command(filepath.Join(ws.plugindir, "bin", command), args...) cmd.Dir = dir cmd.Env = []string{fmt.Sprintf("GOPATH=%s", ws.context.GOPATH), fmt.Sprintf("PATH=%s", os.ExpandEnv("$PATH"))} res, err := cmd.CombinedOutput() if err != nil { // check if the command resulted with an error-exit code if _, ok := err.(*exec.ExitError); !ok { // no Exit-Error --> a fundamental problem occured return "", err } } return string(res), nil } func (ws *GoWorkspace) env(key string) (root string, err error) { root, err = ws.gocmd(ws.gobinpath, string(goCommand_env), ws.Workdir, key) if err == nil { root = strings.TrimSpace(root) } return } func (ws *GoWorkspace) build(args ...string) (res string, err error) { //-gcflags "-N -l" //buildargs := []string{"-race"} //args = append(buildargs, args...) return ws.gocmd(ws.gobinpath, string(goCommand_build), ws.Workdir, args...) } func (ws *GoWorkspace) lint(args ...string) (res string, err error) { return ws.plugin("golint", ws.Workdir, args...) } func (ws *GoWorkspace) vet(args ...string) (res string, err error) { return ws.gocmd(ws.gobinpath, string(goCommand_vet), ws.Workdir, args...) } func (ws *GoWorkspace) buildtests(args ...string) (res string) { for _, p := range args { if ws.packageHasTests(p) { testres, testerr := ws.gocmd(ws.gobinpath, string(goCommand_test), ws.Workdir, "-c", p) if testerr == nil && !strings.HasPrefix(testres, "?") { res = res + "\n" + testres } } } return } func (ws *GoWorkspace) parseBuildOutput(base filesystem.WorkspaceFS, output string) []BuildResult { return ws.parseBuildTypedOutput(base, output, BUILD_ERROR) } func (ws *GoWorkspace) parseBuildTypedOutput(base filesystem.WorkspaceFS, output string, etype BuildResultType) []BuildResult { var res []BuildResult resultset := make(map[BuildResult]bool) lines := strings.Split(output, "\n") for _, l := range lines { if strings.HasPrefix(l, "#") { continue } l = strings.TrimSpace(l) b := []byte(l) if strings.HasPrefix(l, goerr_cantloadpackage) { b = []byte(l[len(goerr_cantloadpackage):]) } m := build_line.FindSubmatch(b) if m != nil { var br BuildResult br.Original = l br.Source = string(m[1]) br.Type = etype fs, pt, err := ws.search(base, ws.Workdir, br.Source) if err != nil { buildLogger.Errorf("cannot parse buildresult : %s", err) br.File = br.Source } else { br.File = pt br.Filesystem = fs.Name() } // we always work in a subdirectory named ".carpowork", so strip the ".." from the filepath br.Directory = filepath.Dir(br.File) pt, err = ws.findPackageFromDirectory(filepath.Join(base.Base(), br.Directory)) if err != nil { buildLogger.Errorf("cannot find package for directory '%s': %s", br.Directory, err) } else { br.PackageImportPath = pt } br.Message = string(m[len(m)-1]) sourceline := strings.Split(string(m[2]), ":")[0] ln, err := strconv.ParseInt(sourceline, 10, 0) if err != nil { buildLogger.Errorf("Compiler output line cannot be parsed as INT: Output=%s, Message=%s\n", l, err) } else { br.Line = int(ln) } if _, ok := resultset[br]; !ok { // do not append the same message twice. this can happen, because wie build packages AND their tests res = append(res, br) } } else { if len(res) > 0 { l = strings.TrimSpace(l) if len(l) > 0 { last := &res[len(res)-1] last.Original = last.Original + " " + l last.Message = last.Message + " " + l } } } } // now parse output return res } func (ws *GoWorkspace) findRemotePackagesWithName(name string, ignore map[string]bool) (results Godoc_results) { resp, err := http.Get(fmt.Sprintf("%s/search?q=%s", godoc_org, name)) if err != nil { return } defer resp.Body.Close() dec := json.NewDecoder(resp.Body) dec.Decode(&results) return results } func (ws *GoWorkspace) findPackagesWithName(name string, ignore map[string]bool) (res []string) { for _, v := range ws.SystemPackages { pname := v.Name importpath := v.ImportPath if _, ok := ignore[importpath]; ok { continue } //if bytes.Equal([]byte(name), []byte(pname)) { if strings.Contains(pname, name) { res = append(res, importpath) } } for _, v := range ws.Packages { pname := v.Name importpath := v.ImportPath if _, ok := ignore[importpath]; ok { continue } //if bytes.Equal([]byte(name), []byte(pname)) { if strings.Contains(pname, name) { res = append(res, importpath) } } return } func (ws *GoWorkspace) findImportsInCode(source string) (res map[string]bool, err error) { fset := token.NewFileSet() f, err := parser.ParseFile(fset, "source.go", source, parser.ImportsOnly) if err != nil { return } res = make(map[string]bool) for _, s := range f.Imports { v := s.Path.Value res[v[1:len(v)-1]] = true // strip off the quotes at both ends } return } func (ws *GoWorkspace) findUnresolvedAt(source string, pos, row, col int) (tok string, err error) { fset := token.NewFileSet() f, err := parser.ParseFile(fset, "source.go", source, parser.DeclarationErrors) if err != nil { if strings.HasPrefix(err.Error(), fmt.Sprintf("source.go:%d", row+1)) { subm := expected_declaration.FindStringSubmatch(err.Error()) if subm != nil { tok = subm[1] err = nil } } return } for _, s := range f.Unresolved { offs := len(s.Name) + fset.Position(s.NamePos).Offset if offs == pos { tok = s.Name return } } return "", errors.New("no unresolved found") }
[ 4 ]
package main import ( "crypto/sha1" "encoding/hex" "encoding/json" "fmt" "github.com/gorilla/mux" "github.com/gorilla/websocket" "log" "net/http" "strconv" "time" ) // Controls rooms, and as an all around coordinator. type Hub struct { hub map[string]*Room upgrader websocket.Upgrader db DB } type moveStruct struct { Col int `json:"col"` Player int `json:"player"` Room string `json:"room"` PlayerId string `json:"PlayerId"` } type ChatMessage struct { Message string `json:"message"` Room string `json:"room"` PlayerId string `json:"PlayerId"` } type Rematch struct { Player int `json:"player"` Room string `json:"room"` PlayerId string `json:"PlayerId"` } type Resign struct { Player int `json:"player"` Room string `json:"room"` PlayerId string `json:"PlayerId"` } type Leave struct { Player int `json:"player"` Room string `json:"room"` PlayerId string `json:"PlayerId"` } type GameHistory struct { PlayerId string `json:"PlayerId"` } func (h *Hub) CreateRoom(name string) *Room { // Hash the "Name" hash := sha1.New() hash.Write([]byte(name)) bs := hex.EncodeToString(hash.Sum(nil)) if _, ok := h.hub[bs]; !ok { room := NewRoom(bs) h.hub[bs] = room err := RoomDaoInstance().CreateRoom(room) if err != nil { fmt.Println(err.Error()) } } return h.hub[bs] } // Iterate through all rooms, and find one with only one person. If none exists, // then create a new room. func (h *Hub) FindSeat(d string) (*Room, Game) { /* Handle resurrecting a game. A when a websocket connection disconnects, which is common, rely on an incomplete in play game, and return that old seat to the user without making a new room from scratch. */ game, err := GameDaoInstance().FindIncompleteGameForDevice(d) if err == nil && game.ID != "" { room, err := RoomDaoInstance().FindRoom(game.Room) if err == nil && room != nil { if h.hub[room.Name] != nil { return h.hub[room.Name], game } else { h.hub[room.Name] = room // Because this room is no longer in memory, clear out the clients. room.Clients = make(map[string]*Client) return room, game } } } log.Println("Finding a seat.") for _, room := range h.hub { /* Iterate through to check if the room has a seat available, that the game is not currently in play, and the * existing deviceId is not already in. */ if len(room.PlayerId) < 2 && room.InPlay == false && !containsPlayerId(d, room) && !isBlackListed(d, room) { return room, game } } // If we make it here, create the room anew. log.Println("No seats found; creating a room anew.") return h.CreateRoom(time.Now().String()), game } func isBlackListed(d string, r *Room) bool { for _, b := range r.BlackList { if b == d { return true } } return false } func containsPlayerId(d string, r *Room) bool { for _, device := range r.PlayerId { if device == d { return true } } return false } func (h *Hub) HandleWS(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) deviceId := params["deviceId"] c, err := h.upgrader.Upgrade(w, r, nil) if err != nil { log.Println("upgrade:", err) return } defer c.Close() log.Println("Join request received from: ", deviceId) room, game := h.FindSeat(deviceId) // This returns the first "random (order not guaranteed seat)" room.Join(c, deviceId, game) /* Reads from the client's out bound channel and broadcasts it */ go room.HandleMsg(deviceId) go room.Clients[deviceId].WritePump() /* Reads from client and if this loop breaks then client disconnected. */ room.Clients[deviceId].ReadLoop() room.Leave(deviceId) if len(room.Clients) == 0 { // If the room is empty, remove the room from memory entirely. if _, ok := h.hub[room.Name]; ok { delete(h.hub, room.Name) fmt.Println("Deleting Room from memory: ", room.Name) } } } func (h *Hub) HandleMessage(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) var chat ChatMessage err := decoder.Decode(&chat) if err != nil { log.Printf("ERROR: %s", err) http.Error(w, "Bad request", http.StatusTeapot) return } message := chat.Message roomhash := chat.Room room := h.hub[roomhash] playerId := chat.PlayerId var playerPosition string for k, v := range room.PlayerId { if v == playerId { playerPosition = k } } go room.HandleMove("Player " + playerPosition + ": " + message) defer r.Body.Close() } func (h *Hub) HandleMove(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) var move moveStruct err := decoder.Decode(&move) if err != nil { log.Printf("ERROR: %s", err) http.Error(w, "Bad request", http.StatusTeapot) return } col := move.Col player := move.Player roomhash := move.Room room := h.hub[roomhash] playerId := move.PlayerId if room == nil { log.Printf("ERROR: %s", err) http.Error(w, "The room does not exist. It's possible your connection was disconnected. Please background the app and start again.", 400) return } if room.InPlay == false { log.Printf("ERROR: %s", err) http.Error(w, "The game is over, you cannot submit a move.", 400) return } if col > len(room.Board[0]) { log.Printf("ERROR: %s", err) http.Error(w, "The move was out of bounds.", 400) return } else { fmt.Println("Players: ", room.PlayerId) originalBoardStates := room.CurrentGame.BoardStates duplicate := make([][][]int, len(originalBoardStates)) for i := range originalBoardStates { duplicate[i] = make([][]int, len(originalBoardStates[i])) for j := range originalBoardStates[i] { duplicate[i][j] = make([]int, len(originalBoardStates[i][j])) copy(duplicate[i][j], originalBoardStates[i][j]) } } // Validate that the position is question is empty, and that player is in Turn. if isTurn(player, room, playerId) { // Amend the 2D array // Note, in the game of connect four, the item is dropped. walker := 0 // Check if in penultimate spot //TODO find a way to simplify keep board board state up to date and check by column [n] and just length if room.Board[walker + 1][col] == 0 { // Check to see if we can fall through for room.Board[walker][col] == 0 { if walker < len(room.Board) - 1 { walker++ if walker == len(room.Board) - 1 { // We have reached the end of the Board. break } else if room.Board[walker + 1][col] != 0 { break } } } } if isZero(room, walker, col) { room.Board[walker][col] = player room.CurrentGame.TurnCount++ fmt.Println("Turn Count", room.CurrentGame.TurnCount) } else { http.Error(w, "The column has been filled.", 400) return } result := room.CheckBoard(player) if result { // We have a Winner room.DeclareWinner(player) } else { if room.CurrentGame.TurnCount == 42 { // 42 turns have occurred without a Winner; declare a tie. room.DeclareTie() } } flip(room) } else { http.Error(w, "An illegal Turn or illegal play was made", 400) return } // Update the data base with the move if room.CurrentGame != nil { gameBoardStates := append(duplicate, room.Board) // Set the new Board state with the latest move. room.CurrentGame.BoardStates = gameBoardStates GameDaoInstance().UpdateGame(room.CurrentGame) RoomDaoInstance().UpdateRoom(room) } go room.HandleMove("") } defer r.Body.Close() } func (h *Hub) HandleResignRequest(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) var resign Resign err := decoder.Decode(&resign) if err != nil { log.Printf("ERROR: %s", err) http.Error(w, "Bad request", http.StatusTeapot) return } room := h.hub[resign.Room] room.ForceLoss(resign.Player) } func (h *Hub) HandleLeaveRequest(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) var leave Leave err := decoder.Decode(&leave) if err != nil { //log.Println("ERROR: %s", err) http.Error(w, "Bad request", http.StatusTeapot) return } room := h.hub[leave.Room] playerString := strconv.Itoa(leave.Player) if room != nil { delete(room.PlayerId, playerString) room.Leave(leave.PlayerId) room.Blacklist(leave.PlayerId) fmt.Println("Removing playerId: ", room.PlayerId[playerString]) if len(room.PlayerId) == 0 { // If the room is empty, remove the room from memory entirely. if _, ok := h.hub[leave.Room]; ok { delete(h.hub, leave.Room) fmt.Println("Deleting Room from memory: ", leave.Room) } } } room.HandleMove("Your opponent has left the room.") } func (h *Hub) HandleRematchRequest(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) var rematch Rematch err := decoder.Decode(&rematch) if err != nil { log.Printf("ERROR: %s", err) http.Error(w, "Bad request", http.StatusTeapot) return } player := rematch.Player roomhash := rematch.Room room := h.hub[roomhash] playerId := rematch.PlayerId if room == nil { http.Error(w, "The room does not exist. It's possible your connection was disconnected. Please background the app and start again.", 400) return } if playerId != room.PlayerId[strconv.Itoa(player)] { http.Error(w, "You are only allowed to request a rematch on your own behalf.", 400) return } room.RematchRequest[playerId] = true playerOne := room.PlayerId["1"] playerTwo := room.PlayerId["2"] if room.RematchRequest[playerOne] && room.RematchRequest[playerTwo] { room.ResetGame() } // Consider this a state change go room.HandleMove("") // Return request state js, err := json.Marshal(room.RematchRequest) w.Header().Set("Content-Type", "application/json") w.Write(js) defer r.Body.Close() } func (h *Hub) HandleFindAllGamesPlayedRequest(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) var history GameHistory err := decoder.Decode(&history) if err != nil { log.Printf("ERROR: %s", err) http.Error(w, "Bad request", http.StatusTeapot) return } games, err := GameDaoInstance().FindAllCompleteGamesByPlayer(history.PlayerId) js, err := json.Marshal(games) w.Header().Set("Content-Type", "application/json") w.Write(js) defer r.Body.Close() } func isZero(r *Room, row int, col int) bool { return r.Board[row][col] == 0 } func isTurn(turn int, r *Room, playerId string) bool { return r.PlayerId[strconv.Itoa(r.Turn)] == playerId && r.Turn == turn } func flip(r *Room) { v := r.Turn if v == 1 { r.Turn = 2 } else { r.Turn = 1 } } /* Constructor */ func NewHub() *Hub { hub := new(Hub) hub.hub = make(map[string]*Room) hub.upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { return true }, } return hub }
[ 4 ]
package tree import ( "encoding/json" "fmt" "testing" ) type rootTestCase struct { root Root valid bool input []byte } var unmarshalTestCases = []rootTestCase{ {Root{0: 0xaa, 31: 0xbb}, true, []byte("aa000000000000000000000000000000000000000000000000000000000000bb")}, {Root{0: 0xaa, 31: 0xbb}, true, []byte("0xaa000000000000000000000000000000000000000000000000000000000000bb")}, {Root{0: 0xaa, 31: 0xbb}, true, []byte("0Xaa000000000000000000000000000000000000000000000000000000000000bb")}, {Root{0: 0xaa, 31: 0xbb}, true, []byte("0XaA000000000000000000000000000000000000000000000000000000000000bb")}, {Root{0: 0xaa, 31: 0xbb}, true, []byte("AA000000000000000000000000000000000000000000000000000000000000BB")}, {Root{0: 0xaa, 31: 0xbb}, true, []byte("0XAA000000000000000000000000000000000000000000000000000000000000BB")}, {Root{}, false, []byte("aa000000000000000000000000000000000000000000000000000000000000bb0x")}, {Root{}, false, []byte("0xaa000000000000000000000000000000000000000000000000000000000000bb0")}, {Root{}, false, []byte("0xaa000000000000000000000000000000000000000000000000000000000000b")}, {Root{}, false, []byte("xaa000000000000000000000000000000000000000000000000000000000000bb")}, {Root{}, false, []byte("a000000000000000000000000000000000000000000000000000000000000bb")}, {Root{}, false, []byte("aa00000000000000000000000000000000000000y000000000000000000000bb")}, {Root{}, false, []byte("aa00")}, {Root{}, false, []byte("a")}, {Root{}, false, []byte{}}, } func TestRoot_UnmarshalText(t *testing.T) { for i, testCase := range unmarshalTestCases { t.Run(fmt.Sprintf("case%d", i), func(t *testing.T) { var x Root err := x.UnmarshalText(testCase.input) if testCase.valid { if err != nil { t.Error(err) return } if x != testCase.root { t.Errorf("Expected %x but got %x", testCase.root[:], x[:]) } } else { if err == nil { t.Error("expected error but did not get any") } } }) } } func TestRoot_MarshalText(t *testing.T) { x := Root{0: 0xaa, 31: 0xbb} data, err := x.MarshalText() if err != nil { t.Error(t) return } if string(data) != "0xaa000000000000000000000000000000000000000000000000000000000000bb" { t.Errorf("unexpected string: %s", string(data)) return } } func TestRoot_String(t *testing.T) { x := Root{0: 0xaa, 31: 0xbb} if res := fmt.Sprintf("fmt %s", x); res != "fmt 0xaa000000000000000000000000000000000000000000000000000000000000bb" { t.Errorf("unexpected direct fmt result: %s", res) return } if res := fmt.Sprintf("fmt %s", &x); res != "fmt 0xaa000000000000000000000000000000000000000000000000000000000000bb" { t.Errorf("unexpected pointer fmt result: %s", res) return } } func TestRoot_JSON_Marshal(t *testing.T) { x := Root{0: 0xaa, 31: 0xbb} out, err := json.Marshal(x) if err != nil { t.Error(err) return } if string(out) != "\"0xaa000000000000000000000000000000000000000000000000000000000000bb\"" { t.Errorf("unexpected json: %s", string(out)) return } } func TestRoot_JSON_Unmarshal(t *testing.T) { var x Root if err := json.Unmarshal([]byte("\"0xaa000000000000000000000000000000000000000000000000000000000000bb\""), &x); err != nil { t.Error(err) return } if x != (Root{0: 0xaa, 31: 0xbb}) { t.Errorf("unexpected value: %s", x) return } }
[ 4 ]
package check import "testing" import ( "github.com/alowde/dpoller/node" "net" "time" ) var time1 int var time2 int var node1 = node.Node{ 1000000000000000000, net.IP{10, 0, 0, 1}, "test_node_1", } /* var node2 = node.Node{ 2000000000000000000, net.IP{10, 0, 0, 2}, "test_node_2", } */ /* type Check struct { URL string `json:"url"` Name string `json:"name"` OkStatus []int `json:"ok-statuses"` AlertInterval int `json:"alert-interval"` TestInterval int `json:"test-interval"` Contacts []string `json:"contacts"` } */ // Valid url, should pass var check1 = Check{ URL: "www.google.com", Name: "Google", OkStatus: []int{200}, AlertInterval: 30, TestInterval: 10, Contacts: []string{"ops1", "ops2"}, } /* // Valid url, should fail var check2 = Check{ URL: "www.google.com", Name: "Google", OkStatus: []int{700}, AlertInterval: 30, TestInterval: 10, } // Unresolvable url var check3 = Check{ URL: "www.thisshouldneverresolvebutifitdoesohboy.wtfiswrongwithiana", Name: "Google", OkStatus: []int{200}, AlertInterval: 30, TestInterval: 10, Contacts: []string{"ops1", "ops2"}, } */ /* type Status struct { Node node.Node Url Check // the URL that was tested Rtime int // number of milliseconds taken to complete the request StatusCode int // status code returned, or magic number 0 for non-numeric status StatusTxt string // detailed description of the status returned Timestamp int // timestamp at which this status was recorded } */ // A 200 status from node1 var status1 = Status{ Node: node1, Url: check1, Rtime: 20, StatusCode: 200, StatusTxt: "status1", } // A 500 status from node1 var status2 = Status{ Node: node1, Url: check1, Rtime: 20, StatusCode: 500, StatusTxt: "status2", } func init() { t, _ := time.Parse("20060102 150405", "20180101 010000") time1 = int(t.Unix()) time2 = int(t.Add(1 * time.Second).Unix()) status1.Timestamp = time1 status2.Timestamp = time2 } func TestDedupe(t *testing.T) { ts1 := Statuses{status1, status2} tsr1 := ts1.Dedupe() t.Run("OneNode", func(t *testing.T) { if len(tsr1) != 1 { t.Errorf("Error in GetFailed(), expected one Failed test, got %v", len(tsr1)) } else { if tsr1[0].StatusTxt != "status2" { t.Errorf("Error in GetFailed(), expected status2, got %#v", tsr1[0]) } } }) }
[ 4 ]
// Code generated by mockery v1.0.0. DO NOT EDIT. package mocks import databases "localhost/medium-mongo-go-driver/databases" import mock "github.com/stretchr/testify/mock" // DatabaseHelper is an autogenerated mock type for the DatabaseHelper type type DatabaseHelper struct { mock.Mock } // Client provides a mock function with given fields: func (_m *DatabaseHelper) Client() databases.ClientHelper { ret := _m.Called() var r0 databases.ClientHelper if rf, ok := ret.Get(0).(func() databases.ClientHelper); ok { r0 = rf() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(databases.ClientHelper) } } return r0 } // Collection provides a mock function with given fields: name func (_m *DatabaseHelper) Collection(name string) databases.CollectionHelper { ret := _m.Called(name) var r0 databases.CollectionHelper if rf, ok := ret.Get(0).(func(string) databases.CollectionHelper); ok { r0 = rf(name) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(databases.CollectionHelper) } } return r0 }
[ 4 ]
package entry import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/json" "errors" "fmt" "github.com/kevinkassimo/gokey/src/confirm" "golang.org/x/crypto/bcrypt" "io" "io/ioutil" "log" ) type UserEntry struct { FileName string Name string Password []byte Data []byte Entry DataEntry } func (e *UserEntry) ReadData() bool { data, err := ioutil.ReadFile(e.FileName) if err != nil { log.Fatalf("Cannot read file %s: %s\n", e.FileName, err) } e.Data = data if err := json.Unmarshal(data, &(e.Entry)); err != nil { log.Fatalf("User data unmarshalling failed: %s\n", err) } if err := bcrypt.CompareHashAndPassword(e.Entry.Hash, e.Password); err != nil { return false // Password validation failed } for i, entry := range e.Entry.Entries { entry.Decode(e.Password) // Must do this! entry is NOT a pointer, BUT a copy! e.Entry.Entries[i] = entry } return true } func (e *UserEntry) WriteData() { // We are assuming the Entry is having some data hash, err := bcrypt.GenerateFromPassword(e.Password, bcrypt.DefaultCost) if err != nil { log.Fatalf("Bcrypt GenerateFromPassword failed: %s\n", err) } e.Entry.Hash = hash var newDataEntry DataEntry // make is necessary! When just trying to copy, it will NOT have enough capacity... newDataEntry.Hash = make([]byte, len(e.Entry.Hash)) copy(newDataEntry.Hash, e.Entry.Hash) for _, ent := range e.Entry.Entries { var newEntry PasswordEntry newEntry.Name = make([]byte, len(ent.Name)) copy(newEntry.Name, ent.Name) newEntry.Desc = make([]byte, len(ent.Desc)) copy(newEntry.Desc, ent.Desc) newEntry.Password = make([]byte, len(ent.Password)) copy(newEntry.Password, ent.Password) newEntry.Encode(e.Password) newDataEntry.Entries = append(newDataEntry.Entries, newEntry) } data, err := json.Marshal(newDataEntry) if err != nil { log.Fatalf("User data marshalling failed: %s\n", err) } if err := ioutil.WriteFile(e.FileName, data, 0770); err != nil { log.Fatalf("Write user data failed: %s\n", err) } } type DataEntry struct { Hash []byte Entries []PasswordEntry `json: entries` } func (e *DataEntry) AddEntry(pe PasswordEntry) { findDup := false shouldOverwrite := false overwriteIndex := -1 for i, entry := range e.Entries { if bytes.Equal(entry.Name, pe.Name) { findDup = true shouldOverwrite = confirm.Ask("Past record found, overwrite?") overwriteIndex = i break } } if !findDup { e.Entries = append(e.Entries, pe) } else { if shouldOverwrite { e.Entries[overwriteIndex] = pe } } } func (e *DataEntry) RemoveEntry(name []byte) { removeIndex := -1 for i, entry := range e.Entries { if bytes.Equal(entry.Name, name) { removeIndex = i break } } if removeIndex < 0 { fmt.Printf("No entry of %s found, nothing to remove.\n", name) } else { // Non-in-seq removal if confirm.Ask("Are you sure?") { e.Entries[removeIndex] = e.Entries[len(e.Entries)-1] e.Entries = e.Entries[:len(e.Entries)-1] } } } type PasswordEntry struct { Name []byte `json: name` Desc []byte `json: description` Password []byte `json: password` } //Adapted from https://astaxie.gitbooks.io/build-web-application-with-golang/en/09.6.html func (e *PasswordEntry) Decode(p []byte) { c, err := aes.NewCipher(p) if err != nil { log.Fatalf("Generate cipher error: %s\n", err) } gcm, err := cipher.NewGCM(c) if err != nil { log.Fatalf("Generate GCM error: %s\n", err) } nonceSize := gcm.NonceSize() if len(e.Name) < nonceSize { log.Fatalf("Error: Cipher text too short\n") } nonce0, cipherText0 := e.Name[:nonceSize], e.Name[nonceSize:] result0, err0 := gcm.Open(nil, nonce0, cipherText0, nil) if err0 != nil { log.Fatalf("Decoding failed: %s", err0) } e.Name = result0 if len(e.Desc) < nonceSize { log.Fatalf("Error: Cipher text too short\n") } nonce1, cipherText1 := e.Desc[:nonceSize], e.Desc[nonceSize:] result1, err1 := gcm.Open(nil, nonce1, cipherText1, nil) if err1 != nil { log.Fatalf("Decoding failed: %s", err1) } e.Desc = result1 if len(e.Password) < nonceSize { log.Fatalf("Error: Cipher text too short\n") } nonce2, cipherText2 := e.Password[:nonceSize], e.Password[nonceSize:] result2, err2 := gcm.Open(nil, nonce2, cipherText2, nil) if err2 != nil { log.Fatalf("Decoding failed: %s", err2) } e.Password = result2 } func (e *PasswordEntry) Encode(p []byte) { c, err := aes.NewCipher(p) if err != nil { log.Fatalf("Generate cipher error: %s\n", err) } gcm, err := cipher.NewGCM(c) if err != nil { log.Fatalf("Generate GCM error: %s\n", err) } nonce := make([]byte, 12) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { log.Fatalf("Error: %s\n", err) } e.Name = gcm.Seal(nonce, nonce, e.Name, nil) e.Desc = gcm.Seal(nonce, nonce, e.Desc, nil) e.Password = gcm.Seal(nonce, nonce, e.Password, nil) } func decrypt(ciphertext []byte, key []byte) ([]byte, error) { c, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(c) if err != nil { return nil, err } nonceSize := 12 if len(ciphertext) < nonceSize { return nil, errors.New("ciphertext too short") } nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:] return gcm.Open(nil, nonce, ciphertext, nil) }
[ 4 ]
// Package grace use to hot reload // Description: http://grisha.org/blog/2014/06/03/graceful-restart-in-golang/ package gracenet import ( "os" "strings" "sync" "syscall" "time" "net" "strconv" "fmt" "os/exec" "log" "os/signal" "net/http" "errors" "context" ) const ( // StateInit represent the application inited StateInit = iota // StateRunning represent the application is running StateRunning // StateShuttingDown represent the application is shutting down StateShuttingDown // StateTerminate represent the application is killed StateTerminate ) const ( // Used to indicate a graceful restart in the new process. envCountKey = "LISTEN_FDS" envCountKeyPrefix = envCountKey + "=" ) var ( // DefaultReadTimeOut is the HTTP read timeout DefaultReadTimeOut time.Duration // DefaultWriteTimeOut is the HTTP Write timeout DefaultWriteTimeOut time.Duration // DefaultTimeout is the shutdown server's timeout. default is 60s DefaultTimeout = 60 * time.Second // LOG grace detail LogDetail = true hookableSignals []os.Signal // In order to keep the working directory the same as when we started we record // it at startup. originalWD, _ = os.Getwd() //grace servers info inherited []net.Listener listeners []*GraceListener mutex sync.Mutex inheritOnce sync.Once status int quit_chan chan bool // used in tests to override the default behavior of starting from fd 3. fdStart int ) func ListenHTTPHandlerAndServe(proto, addr string, http_handler http.Handler) error { server := &http.Server{Addr: addr, Handler: http_handler} return ListenHTTPAndServe(proto, addr, server) } func ListenHTTPAndServe(proto, addr string, server *http.Server) error { gl, err:= ListenHTTP(proto, addr, server) if err == nil{ if LogDetail { log.Printf("listen on %s ok, pid %d", addr, os.Getpid()) } ShutDownParentProcess() mutex.Lock() status = StateRunning mutex.Unlock() return gl.Server.Serve(gl) }else { return err } return nil } func ListenHTTP(proto, addr string, server *http.Server) (gl *GraceListener,err error){ if server == nil{ return nil, errors.New("HTTP Server is nil") } switch proto { case "tcp", "tcp4", "tcp6": laddr, err := net.ResolveTCPAddr(proto, addr ) if err != nil { return nil, err } gl,err = ListenTCP( proto, laddr ) case "unix", "unixpacket": laddr, err := net.ResolveUnixAddr(proto, addr) if err != nil { return nil, err } gl,err = ListenUnix(proto, laddr) default: return nil, net.UnknownNetworkError(proto) } if err == nil { gl.Server = server } return } func ListenAndServe(proto, addr string, h Handler ) error { gl, err:= Listen(proto, addr) if err == nil{ if LogDetail { log.Printf("listen on %s ok, pid %d", addr, os.Getpid()) } ShutDownParentProcess() gl.serve( h ) return nil }else { return err } return nil } func Listen(proto, addr string) (*GraceListener, error) { switch proto { case "tcp", "tcp4", "tcp6": laddr, err := net.ResolveTCPAddr(proto, addr ) if err != nil { return nil, err } return ListenTCP( proto, laddr ) case "unix", "unixpacket": laddr, err := net.ResolveUnixAddr(proto, addr) if err != nil { return nil, err } return ListenUnix(proto, laddr) default: return nil, net.UnknownNetworkError(proto) } } func ListenTCP(proto string, laddr *net.TCPAddr) (*GraceListener, error) { if err := inheritListeners(); err != nil { return nil, err } mutex.Lock() defer mutex.Unlock() // look for an inherited listener for i, l := range inherited { if l == nil { // we nil used inherited listeners continue } if isSameAddr(l.Addr(), laddr) { inherited[i] = nil if LogDetail { log.Println("[grace net] inhired tcp socket !") } gl := newGraceListener( l, TCP ) listeners = append(listeners, gl) return gl, nil } } // make a fresh listener l, err := net.ListenTCP(proto, laddr) if err != nil { return nil, err } gl := newGraceListener( l, TCP ) listeners = append(listeners, gl) return gl, nil } func ListenUnix(proto string, laddr *net.UnixAddr) (*GraceListener, error) { if err := inheritListeners(); err != nil { return nil, err } mutex.Lock() defer mutex.Unlock() // look for an inherited listener for i, l := range inherited { if l == nil { // we nil used inherited listeners continue } if isSameAddr(l.Addr(), laddr) { inherited[i] = nil gl := newGraceListener( l, UNIX ) listeners = append(listeners, gl) return gl, nil } } // make a fresh listener l, err := net.ListenUnix( proto, laddr ) if err != nil { if err.(*net.OpError).Err.(*os.SyscallError).Syscall == "bind" { log.Printf( "[grace net] clean unix path: %s", laddr.String()) os.Remove(laddr.String()) l, err = net.ListenUnix( proto, laddr ) if err != nil { return nil, err } } else { return nil, err } } gl := newGraceListener( l, UNIX ) l.SetUnlinkOnClose(false) listeners = append(listeners, gl) return gl, nil } func inheritListeners() error { var retErr error inheritOnce.Do(func() { mutex.Lock() defer mutex.Unlock() countStr := os.Getenv(envCountKey) if countStr == "" { return } count, err := strconv.Atoi(countStr) if err != nil { retErr = fmt.Errorf("[grace net] found invalid count value: %s=%s", envCountKey, countStr) return } // In tests this may be overridden. fdStart := fdStart if fdStart == 0 { // In normal operations if we are inheriting, the listeners will begin at // fd 3. fdStart = 3 } for i := fdStart; i < fdStart+count; i++ { file := os.NewFile(uintptr(i), "listener") l, err := net.FileListener(file) if err != nil { file.Close() retErr = fmt.Errorf("[grace net] error inheriting socket fd %d: %s", i, err) return } if err := file.Close(); err != nil { retErr = fmt.Errorf("[grace net] error closing inherited socket fd %d: %s", i, err) return } inherited = append(inherited, l) } }) return retErr } func isSameAddr(a1, a2 net.Addr) bool { if a1.Network() != a2.Network() { return false } a1s := a1.String() a2s := a2.String() if a1s == a2s { return true } // This allows for ipv6 vs ipv4 local addresses to compare as equal. This // scenario is common when listening on localhost. const ipv6prefix = "[::]" a1s = strings.TrimPrefix(a1s, ipv6prefix) a2s = strings.TrimPrefix(a2s, ipv6prefix) const ipv4prefix = "0.0.0.0" a1s = strings.TrimPrefix(a1s, ipv4prefix) a2s = strings.TrimPrefix(a2s, ipv4prefix) return a1s == a2s } func StartProcess() (int, error) { mutex.Lock() defer mutex.Unlock() files := make([]*os.File, len(listeners)) for i , srvPtr := range listeners { f, err := srvPtr.File() if err == nil{ files[i] = f } } if LogDetail { log.Println(files) } // Use the original binary location. This works with symlinks such that if // the file it points to has been changed we will use the updated symlink. path, err := exec.LookPath(os.Args[0]) if err != nil { return 0, err } var args []string if len(os.Args) > 1 { for _, arg := range os.Args[1:] { args = append(args, arg) } } // Pass on the environment and replace the old count key with the new one. var env []string for _, v := range os.Environ() { if !strings.HasPrefix(v, envCountKeyPrefix) { env = append(env, v) } } env = append(env, fmt.Sprintf("%s%d", envCountKeyPrefix, len(listeners))) cmd := exec.Command(path, args...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Env = env cmd.Dir = originalWD cmd.ExtraFiles = files err = cmd.Start() if err != nil { log.Fatalf("[grace net] Restart: Failed to launch, error: %v", err) return 0, err } return cmd.Process.Pid, nil } func ShutDownParentProcess() error { ppid := os.Getppid() if ppid != 1 && os.Getenv(envCountKey) != "" { //send kill signal if err := syscall.Kill(ppid, syscall.SIGTERM); err != nil { log.Fatalf("[grace net] failed to kill parent[%d] %s\n", ppid , err ) return err }else { log.Printf("[grace net] kill parent[%d] success !\n", ppid) } }else { if LogDetail { log.Println("[grace net] dont need kill parent") } } return nil } func shutdown() { <- quit_chan mutex.Lock() defer mutex.Unlock() if status == StateShuttingDown || status == StateTerminate { return } status = StateShuttingDown if LogDetail { log.Println("[grace net] status is shutting down") } tick := time.Tick(DefaultTimeout) ch := make(chan bool) go func() { for _ , srvPtr := range listeners { if srvPtr.Server != nil { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := srvPtr.Server.Shutdown(ctx); err != nil { log.Printf( "[grace net] HTTP Server Shutdown: %s", err) }else { if LogDetail { log.Println("[grace net] http server shutdown succ") } } } else { err := srvPtr.Close() if err != nil{ log.Printf("[grace net] close server fail, error [ %s ]\n", err) }else { if LogDetail { log.Println("[grace net] close server succ") } } } } ch <- true }() select { case <-tick: log.Println("[grace net] waiting too long time, force close.") break case <-ch: break } for _ , srvPtr := range listeners { srvPtr.closed <- true } status = StateTerminate } func init() { status = StateInit quit_chan = make(chan bool) hookableSignals = []os.Signal{ syscall.SIGUSR2, syscall.SIGTERM, } go shutdown() go signalHandler() } //信号处理函数 func signalHandler() { //初始化chan、注册信号处理 sigChan := make(chan os.Signal, 10) signal.Notify( sigChan, hookableSignals..., ) pid := syscall.Getpid() var sig os.Signal for { sig = <-sigChan switch sig { case syscall.SIGUSR2: log.Printf("Pid[%d] Received SIG USR2. start new process.\n", pid ) new_pid, err := StartProcess() if err != nil { log.Println("Fork err:", err) }else { if LogDetail { log.Println("Fork new process ", new_pid) } } case syscall.SIGTERM: log.Printf("Pid[%d] Received SIGTERM.\n", pid ) if status == StateShuttingDown || status == StateTerminate { break } quit_chan <- true default: log.Printf("Received %v: nothing i care about...\n", sig) } } }
[ 4 ]
// Code generated by mockery. DO NOT EDIT. package automock import ( context "context" model "github.com/kyma-incubator/compass/components/director/internal/model" mock "github.com/stretchr/testify/mock" ) // ApplicationService is an autogenerated mock type for the ApplicationService type type ApplicationService struct { mock.Mock } // Get provides a mock function with given fields: ctx, id func (_m *ApplicationService) Get(ctx context.Context, id string) (*model.Application, error) { ret := _m.Called(ctx, id) var r0 *model.Application if rf, ok := ret.Get(0).(func(context.Context, string) *model.Application); ok { r0 = rf(ctx, id) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.Application) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { r1 = rf(ctx, id) } else { r1 = ret.Error(1) } return r0, r1 } // ListAllByApplicationTemplateID provides a mock function with given fields: ctx, applicationTemplateID func (_m *ApplicationService) ListAllByApplicationTemplateID(ctx context.Context, applicationTemplateID string) ([]*model.Application, error) { ret := _m.Called(ctx, applicationTemplateID) var r0 []*model.Application if rf, ok := ret.Get(0).(func(context.Context, string) []*model.Application); ok { r0 = rf(ctx, applicationTemplateID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*model.Application) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { r1 = rf(ctx, applicationTemplateID) } else { r1 = ret.Error(1) } return r0, r1 } // Update provides a mock function with given fields: ctx, id, in func (_m *ApplicationService) Update(ctx context.Context, id string, in model.ApplicationUpdateInput) error { ret := _m.Called(ctx, id, in) var r0 error if rf, ok := ret.Get(0).(func(context.Context, string, model.ApplicationUpdateInput) error); ok { r0 = rf(ctx, id, in) } else { r0 = ret.Error(0) } return r0 } type mockConstructorTestingTNewApplicationService interface { mock.TestingT Cleanup(func()) } // NewApplicationService creates a new instance of ApplicationService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. func NewApplicationService(t mockConstructorTestingTNewApplicationService) *ApplicationService { mock := &ApplicationService{} mock.Mock.Test(t) t.Cleanup(func() { mock.AssertExpectations(t) }) return mock }
[ 4 ]
package getAll import ( "github.com/sinelga/images_provider/domains" // "fmt" "github.com/garyburd/redigo/redis" "log/syslog" "encoding/json" "math/rand" "time" // "strings" ) func shuffleSlice(slice []interface{}) []interface{} { rand.Seed(time.Now().UTC().UnixNano()) for i := range slice { j := rand.Intn(i + 1) slice[i], slice[j] = slice[j], slice[i] } return slice } func GetAll(golog syslog.Writer, c redis.Conn, site string) ([]domains.CharacterRedis,bool) { var charactersRedis []domains.CharacterRedis var exist bool = false if existint, err := redis.Int(c.Do("EXISTS", site)); err != nil { golog.Crit("bcharacterRedis " + err.Error() + " " + site) } else { if existint == 1 { exist = true if allfilds, err := redis.Strings(c.Do("HKEYS", site)); err != nil { golog.Crit(err.Error()) } else { list := make([]interface{}, len(allfilds)) for i, fild := range allfilds { list[i] = fild } shuffleSlice(list) var args []interface{} args = append(args, site) for i := 0; i < 15; i++ { args = append(args, list[i].(string)) } if bcharactersRedis, err := redis.MultiBulk(c.Do("HMGET", args...)); err != nil { golog.Crit(err.Error()) } else { for _, x := range bcharactersRedis { var v, ok = x.([]byte) if ok { var character domains.CharacterRedis if err := json.Unmarshal(v, &character); err != nil { golog.Crit(err.Error()) } else { if character.Sex == "female" { charactersRedis = append(charactersRedis, character) } } } } } } } } return charactersRedis,exist }
[ 4 ]
// Code generated by mockery v2.13.1. DO NOT EDIT. package mocks import ( time "time" aerospike "github.com/aerospike/aerospike-client-go/v6" mock "github.com/stretchr/testify/mock" ) // Asconn is an autogenerated mock type for the asconn type type Asconn struct { mock.Mock } // Close provides a mock function with given fields: func (_m *Asconn) Close() { _m.Called() } // Login provides a mock function with given fields: _a0 func (_m *Asconn) Login(_a0 *aerospike.ClientPolicy) aerospike.Error { ret := _m.Called(_a0) var r0 aerospike.Error if rf, ok := ret.Get(0).(func(*aerospike.ClientPolicy) aerospike.Error); ok { r0 = rf(_a0) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(aerospike.Error) } } return r0 } // RequestInfo provides a mock function with given fields: _a0 func (_m *Asconn) RequestInfo(_a0 ...string) (map[string]string, aerospike.Error) { _va := make([]interface{}, len(_a0)) for _i := range _a0 { _va[_i] = _a0[_i] } var _ca []interface{} _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 map[string]string if rf, ok := ret.Get(0).(func(...string) map[string]string); ok { r0 = rf(_a0...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(map[string]string) } } var r1 aerospike.Error if rf, ok := ret.Get(1).(func(...string) aerospike.Error); ok { r1 = rf(_a0...) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(aerospike.Error) } } return r0, r1 } // SetTimeout provides a mock function with given fields: _a0, _a1 func (_m *Asconn) SetTimeout(_a0 time.Time, _a1 time.Duration) aerospike.Error { ret := _m.Called(_a0, _a1) var r0 aerospike.Error if rf, ok := ret.Get(0).(func(time.Time, time.Duration) aerospike.Error); ok { r0 = rf(_a0, _a1) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(aerospike.Error) } } return r0 } type mockConstructorTestingTNewAsconn interface { mock.TestingT Cleanup(func()) } // NewAsconn creates a new instance of Asconn. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. func NewAsconn(t mockConstructorTestingTNewAsconn) *Asconn { mock := &Asconn{} mock.Mock.Test(t) t.Cleanup(func() { mock.AssertExpectations(t) }) return mock }
[ 4 ]
package libs import ( "bytes" "encoding/json" "encoding/xml" "io" "io/ioutil" "net/http" "net/http/httptest" "os" "reflect" "strings" "testing" // "github.com/septianw/golok" // "github.com/septianw/log15" ) type Payload struct { Id int8 Name string Active bool } type PayloadSequence struct { Text string Type uint8 PlainType string } func CaptureOutput(f func()) string { var old = os.Stdout r, w, _ := os.Pipe() os.Stdout = w f() outC := make(chan string) go func() { var buf bytes.Buffer io.Copy(&buf, r) outC <- buf.String() }() w.Close() os.Stdout = old out := <-outC return out } // convert from map to struct found on http://play.golang.org/p/tN8mxT_V9h http://stackoverflow.com/questions/26744873/converting-map-to-struct func TestSend(t *testing.T) { var paid [3]PayloadSequence record := Payload{ Id: 12, Name: "Robert Murdock", Active: true, } paid[0].Text = "Hi. I'm Robert. Robert Murdock" paid[0].Type = TEXT paid[0].PlainType = "text/plain" tmpjson, jsonr := json.Marshal(&record) paid[1].Text = string(tmpjson) paid[1].Type = JSON paid[1].PlainType = "application/json" tmpxml, xmlr := xml.Marshal(record) paid[2].Text = string(tmpxml) paid[2].Type = XML paid[2].PlainType = "application/xml" t.Logf("jsonr: %+v; xmlr: %+v", jsonr, xmlr) for _, pay := range paid { hts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { Send(w, OK, pay.Type, pay.Text) })) res, err := http.Get(hts.URL) if err != nil { t.Errorf("Unknown error: %+v", err) t.FailNow() return } body, err := ioutil.ReadAll(res.Body) res.Body.Close() if err != nil { t.Errorf("ioutil fail to read body: %+v", err) t.Fail() return } if strings.Compare(string(body), pay.Text) != 0 { t.Errorf("Expected %s, have %s", pay.Text, string(body)) } t.Logf("headers: %+v", res.Header) t.Logf("Body: %+v", string(body)) if strings.Compare(res.Header.Get("Content-Type"), pay.PlainType) != 0 { t.Errorf("Expected %s, have %s", pay.PlainType, (res.Header.Get("Content-Type"))) } hts.Close() } } func TestPackToHuman(t *testing.T) { person := Payload{15, "Sonoya Mizuno", true} // var result Payload personToHuman := PackToHuman(interface{}(person)) var humanToPerson Payload fail := PackToHuman(person) t.Log(fail) if strings.Compare(fail, "{}") == 0 { t.Errorf("PackToHuman input is %+v instead of %+v", reflect.TypeOf(person).Kind(), interface{}(person)) } t.Logf("PersonToHuman: %+v", personToHuman) t.Logf("personToHuman type: %+v", reflect.TypeOf(personToHuman).Kind()) t.Logf("Person type: %+v", reflect.TypeOf(interface{}(person)).Kind()) err := json.Unmarshal([]byte(personToHuman), &humanToPerson) // _ = FillStruct(map[string]interface{}(humanToPerson), result) if err != nil { t.Errorf("Unmarshal person fail. Reason: %+v", err) t.Fail() return } else { if !reflect.DeepEqual(person, humanToPerson) { t.Errorf("Person unequal %+v", humanToPerson) t.Fail() return } } }
[ 4 ]
package resourcetypes import ( "errors" "github.com/shwetha-pingala/HyperledgerProject/InvoiveProject/go-api/models" ) type UpdateOpts struct { Replace bool } func Update(id string, usr *models.ResourceType, opts *UpdateOpts) (*models.ResourceType, error) { var exists bool if opts == nil { opts = &UpdateOpts{} } for index, resourcetype := range mockResourceTypes { if resourcetype.ID == id { if opts.Replace { usr.ID = mockResourceTypes[index].ID mockResourceTypes[index] = *usr } else { if len(usr.Name) > 0 { mockResourceTypes[index].Name = usr.Name } } exists = true usr = &mockResourceTypes[index] } } if !exists { return nil, errors.New("unable to update resourcetype because resourcetype was not found") } return usr, nil }
[ 4 ]
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package log import ( "context" "fmt" "os" "strings" "testing" "time" "github.com/stretchr/testify/assert" "mosn.io/pkg/log" ) func TestErrorLoggerManager_EnableDisable(t *testing.T) { disabledLogger, err := GetOrCreateDefaultErrorLogger("/tmp/disabled.log", log.ERROR) if err != nil { t.Fatal(err) } if !assert.Falsef(t, disabledLogger.Disable(), "disable should be false") { t.FailNow() } GetErrorLoggerManagerInstance().Disable() if !assert.Equalf(t, true, GetErrorLoggerManagerInstance().disabled, "disabled in errLoggerManagerInstance should be true") { t.FailNow() } // test logger currently is disabled if !assert.Truef(t, disabledLogger.Disable(), "disable should be true") { t.FailNow() } // test new logger is disabled disabledLogger2, err := GetOrCreateDefaultErrorLogger("/tmp/disabled2.log", log.ERROR) if err != nil { t.Fatal(err) } if !assert.Truef(t, disabledLogger2.Disable(), "disable should be true") { t.FailNow() } GetErrorLoggerManagerInstance().Enable() if !assert.Equalf(t, false, GetErrorLoggerManagerInstance().disabled, "disabled in errLoggerManagerInstance should be false") { t.FailNow() } if !assert.Falsef(t, disabledLogger.Disable(), "disable should be false") { t.FailNow() } if !assert.Falsef(t, disabledLogger.Disable(), "disable should be false") { t.FailNow() } } func TestErrorLoggerManager_LogLevelControl(t *testing.T) { // test Enable GetErrorLoggerManagerInstance().SetLogLevelControl(log.FATAL) if !assert.Truef(t, GetErrorLoggerManagerInstance().withLogLevelControl, "with log level control in errLoggerManagerInstance should be true") { t.FailNow() } if !assert.Equalf(t, log.FATAL, GetErrorLoggerManagerInstance().logLevelControl, "log level control in errLoggerManagerInstance should be fatal") { t.FailNow() } controledlogger, err := GetOrCreateDefaultErrorLogger("/tmp/controled.log", log.INFO) if err != nil { t.Fatal(err) } if !assert.Equalf(t, log.FATAL, controledlogger.GetLogLevel(), "level should be contorled, to be fatal") { t.FailNow() } // test SetAllErrorLoggerLevel method controled by logLevelControl GetErrorLoggerManagerInstance().SetAllErrorLoggerLevel(log.INFO) controledlogger, err = GetOrCreateDefaultErrorLogger("/tmp/controled.log", log.INFO) if err != nil { t.Fatal(err) } if !assert.Equalf(t, log.FATAL, controledlogger.GetLogLevel(), "level should be contorled, to be fatal") { t.FailNow() } // test Disable GetErrorLoggerManagerInstance().DisableLogLevelControl() if !assert.Falsef(t, GetErrorLoggerManagerInstance().withLogLevelControl, "with log level control in errLoggerManagerInstance should be false") { t.FailNow() } if !assert.Equalf(t, log.RAW, GetErrorLoggerManagerInstance().logLevelControl, "log level control in errLoggerManagerInstance should be lowest level: raw") { t.FailNow() } notControledlogger, err := GetOrCreateDefaultErrorLogger("/tmp/not_controled.log", log.INFO) if err != nil { t.Fatal(err) } if !assert.Equalf(t, log.INFO, notControledlogger.GetLogLevel(), "level should be not contorled, to be info") { t.FailNow() } // test without logLevelControl, SetAllErrorLoggerLevel method can successfully set log level GetErrorLoggerManagerInstance().SetAllErrorLoggerLevel(log.ERROR) notControledlogger, err = GetOrCreateDefaultErrorLogger("/tmp/not_controled.log", log.ERROR) if err != nil { t.Fatal(err) } if !assert.Equalf(t, log.ERROR, notControledlogger.GetLogLevel(), "level should be contorled, to be error") { t.FailNow() } } func TestUpdateLoggerConfig(t *testing.T) { // reset for test errorLoggerManagerInstance.managers = make(map[string]log.ErrorLogger) log.ClearAll() // logName := "/tmp/mosn/test_update_logger.log" if lg, err := GetOrCreateDefaultErrorLogger(logName, log.DEBUG); err != nil { t.Fatal(err) } else { if lg.(*log.SimpleErrorLog).Level != log.DEBUG { t.Fatal("logger created, but level is not expected") } } if lg, err := GetOrCreateDefaultErrorLogger(logName, log.INFO); err != nil { t.Fatal(err) } else { if lg.(*log.SimpleErrorLog).Level != log.DEBUG { t.Fatal("expected get a logger, not create a new one") } } // keeps the logger lg, _ := GetOrCreateDefaultErrorLogger(logName, log.RAW) logger := lg.(*log.SimpleErrorLog) if ok := UpdateErrorLoggerLevel("not_exists", log.INFO); ok { t.Fatal("update a not exists logger, expected failed") } // update log level, effects the logger if ok := UpdateErrorLoggerLevel(logName, log.TRACE); !ok { t.Fatal("update logger failed") } else { if logger.Level != log.TRACE { t.Fatal("update logger failed") } } // test disable/ enable if ok := ToggleLogger(logName, true); !ok { t.Fatal("disable logger failed") } else { if !logger.Logger.Disable() { t.Fatal("disable logger failed") } } if ok := ToggleLogger(logName, false); !ok { t.Fatal("enable logger failed") } else { if logger.Logger.Disable() { t.Fatal("enable logger failed") } } // Toggle Logger (not error logger) baseLoggerPath := "/tmp/mosn/base_logger.log" baseLogger, err := log.GetOrCreateLogger(baseLoggerPath, nil) if err != nil || baseLogger.Disable() { t.Fatalf("Create Logger not expected, error: %v, logger state: %v", err, baseLogger.Disable()) } if ok := ToggleLogger(baseLoggerPath, true); !ok { t.Fatal("enable base logger failed") } if !baseLogger.Disable() { t.Fatal("disable Logger failed") } } func TestSetAllErrorLogLevel(t *testing.T) { defer log.CloseAll() // reset for test errorLoggerManagerInstance.managers = make(map[string]log.ErrorLogger) log.ClearAll() fatalLogger, err := GetOrCreateDefaultErrorLogger("/tmp/fatallog.log", log.FATAL) if err != nil { t.Fatal(err) } var logs []log.ErrorLogger for i := 0; i < 100; i++ { logName := fmt.Sprintf("/tmp/errorlog.%d.log", i) lg, err := GetOrCreateDefaultErrorLogger(logName, log.INFO) if err != nil { t.Fatal(err) } logs = append(logs, lg) } GetErrorLoggerManagerInstance().SetAllErrorLoggerLevel(log.ERROR) // verify for _, lg := range logs { if lg.GetLogLevel() != log.ERROR { t.Fatal("some error log's level is not changed") } } // log level higher than log.ERROR should be set if fatalLogger.GetLogLevel() != log.ERROR { t.Fatal("fatal logger level should be error") } // logger created after since should be level in the param loggerAfter, err := GetOrCreateDefaultErrorLogger("/tmp/after.log", log.INFO) if loggerAfter.GetLogLevel() != log.INFO { t.Fatal("logger created should be INFO level") } } func TestDefaultLoggerInit(t *testing.T) { logName := "/tmp/mosn/test_update_logger.log" // reset for test errorLoggerManagerInstance.managers = make(map[string]log.ErrorLogger) log.ClearAll() InitDefaultLogger(logName, ERROR) // Test Default Logger Level Update if !(DefaultLogger.GetLogLevel() == ERROR && Proxy.GetLogLevel() == ERROR) { t.Fatal("init log failed") } UpdateErrorLoggerLevel(logName, INFO) if !(DefaultLogger.GetLogLevel() == INFO && Proxy.GetLogLevel() == INFO) { t.Fatal("init log failed") } } // The error logger creator can be replaced to another implementation. // The logger manager & proxy logger will use the same implementation. func TestExtendErrorLogger(t *testing.T) { DefaultCreateErrorLoggerFunc = NewMockLogger defer func() { DefaultCreateErrorLoggerFunc = CreateDefaultErrorLogger }() logName := "/tmp/mosn/test_mock_log.log" os.Remove(logName) // reset for test errorLoggerManagerInstance.managers = make(map[string]log.ErrorLogger) log.ClearAll() if err := InitDefaultLogger(logName, INFO); err != nil { t.Fatal(err) } DefaultLogger.Infof("test_%d", 123) // [mocked] [INFO] [] test_123 Proxy.Infof(context.Background(), "test_%d", 123) // [mocked] [INFO] [] [connId,traceId] test_123 time.Sleep(time.Second) lines, err := readLines(logName) if err != nil { t.Fatal(err) } if len(lines) != 2 { t.Fatalf("logger write lines not expected, writes: %d, expected: %d", len(lines), 2) } for _, l := range lines { qs := strings.SplitN(l, " ", 4) if !(len(qs) == 4 && qs[0] == "[mocked]" && qs[1] == "[INFO]" && qs[2] == "[]" && strings.Contains(qs[3], "test_123")) { t.Fatalf("log output is unexpected: %s", l) } } ToggleLogger(logName, true) DefaultLogger.Infof("test_%d", 123) Proxy.Infof(context.Background(), "test_%d", 123) if lines, err := readLines(logName); err != nil || len(lines) != 2 { t.Fatal("disable proxy logger failed") } } // mock a logger type mockLogger struct { *log.SimpleErrorLog } func NewMockLogger(output string, level log.Level) (log.ErrorLogger, error) { lg, err := log.GetOrCreateLogger(output, nil) if err != nil { return nil, err } return &mockLogger{ &log.SimpleErrorLog{ Logger: lg, Level: level, Formatter: func(lv string, alert string, format string) string { return fmt.Sprintf("[mocked] %s [%s] %s", lv, alert, format) }, }, }, nil }
[ 4 ]
package storage import ( "errors" "fmt" "github.com/futurehomeno/fimpgo" "github.com/futurehomeno/fimpgo/fimptype/primefimp" log "github.com/sirupsen/logrus" "github.com/thingsplex/tpflow" "github.com/thingsplex/tpflow/registry/model" ) type VinculumRegistryStore struct { vApi *primefimp.ApiClient msgTransport *fimpgo.MqttTransport config *tpflow.Configs } func NewVinculumRegistryStore(config *tpflow.Configs) RegistryStorage { return &VinculumRegistryStore{config: config} } func (r *VinculumRegistryStore) Connect() error { clientId := r.config.MqttClientIdPrefix + "vinc_reg_store" r.msgTransport = fimpgo.NewMqttTransport(r.config.MqttServerURI, clientId, r.config.MqttUsername, r.config.MqttPassword, true, 1, 1) r.msgTransport.SetGlobalTopicPrefix(r.config.MqttTopicGlobalPrefix) err := r.msgTransport.Start() log.Info("<MqRegInt> Mqtt transport connected") if err != nil { log.Error("<MqRegInt> Error connecting to broker : ", err) return err } r.vApi = primefimp.NewApiClient("tpflow_reg", r.msgTransport, false) if r.config.IsDevMode { log.Info("<MqRegInt> DEV-MODE vinculum DB from file") err = r.vApi.LoadVincResponseFromFile("testdata/vinfimp/site-response.json") if err != nil { log.Error("Can't load site data from file . Error:", err) } } else { go func() { r.vApi.ReloadSiteToCache(40) r.vApi.StartNotifyRouter() }() } return nil } func (r *VinculumRegistryStore) GetBackendName() string { return "vinculum" } func (r *VinculumRegistryStore) Disconnect() { r.vApi.Stop() } func (VinculumRegistryStore) GetServiceById(Id model.ID) (*model.Service, error) { //log.Warn("GetServiceById NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetServiceByFullAddress(address string) (*model.ServiceExtendedView, error) { //log.Warn("GetServiceByFullAddress NOT implemented !!!!") return nil, errors.New("not implemented") } func (r *VinculumRegistryStore) GetLocationById(Id model.ID) (*model.Location, error) { locations, err := r.GetAllLocations() if err != nil { return nil, err } for i := range locations { if locations[i].ID == Id { return &locations[i], nil } } return nil, nil } func (r *VinculumRegistryStore) GetAllThings() ([]model.Thing, error) { site, err := r.vApi.GetSite(true) if err != nil { return nil, err } vThings := site.Things var things []model.Thing for i := range vThings { thing := model.Thing{} thing.ID = model.ID(vThings[i].ID) thing.Alias = vThings[i].Name thing.Address = vThings[i].Address thing.LocationId = model.ID(vThings[i].RoomID) thing.ProductHash, _ = vThings[i].Props["product_hash"] thing.ProductId, _ = vThings[i].Props["product_id"] thing.ProductName, _ = vThings[i].Props["product_name"] for di := range vThings[i].Devices { firstDev := site.GetDeviceById(vThings[i].Devices[di]) if firstDev != nil { thing.CommTechnology = firstDev.Fimp.Adapter _, isBattery := firstDev.Service["battery"] if isBattery { thing.PowerSource = "battery" } else { thing.PowerSource = "ac" } if thing.LocationId == 0 { if firstDev.Room == nil { continue } if *firstDev.Room == 0 { continue } thing.LocationId = model.ID(*firstDev.Room) } } } things = append(things, thing) } return things, nil } func (r *VinculumRegistryStore) GetDevicesByThingId(locationId model.ID) ([]model.Device, error) { log.Warn("GetDevicesByThingId NOT implemented !!!!") return nil, nil } func (r *VinculumRegistryStore) ExtendThingsWithLocation(things []model.Thing) []model.ThingWithLocationView { response := make([]model.ThingWithLocationView, len(things)) site, err := r.vApi.GetSite(true) if err != nil { return nil } for i := range things { response[i].Thing = things[i] room := site.GetRoomById(int(things[i].LocationId)) if room != nil { if room.Alias != "" { response[i].LocationAlias = room.Alias } else { if room.Type != nil { response[i].LocationAlias = *room.Type } } continue } area := site.GetAreaById(int(things[i].LocationId)) if area != nil { response[i].LocationAlias = area.Name } } return response } func (r *VinculumRegistryStore) GetAllServices() ([]model.Service, error) { site, err := r.vApi.GetSite(true) if err != nil { return nil, err } vDevs := site.Devices var services []model.Service for i := range vDevs { for k := range vDevs[i].Service { svc := model.Service{Name: k} svc.Address = vDevs[i].Service[k].Addr if vDevs[i].Client.Name != nil { svc.Alias = *vDevs[i].Client.Name } for _, intfName := range vDevs[i].Service[k].Interfaces { intf := model.Interface{ Type: "", // can be extracted from inclusion report , but currently not being used anywhere MsgType: intfName, ValueType: "", // can be extracted from inclusion report or use MsgType -> ValueType mapping Version: "", } svc.Interfaces = append(svc.Interfaces, intf) } svc.ParentContainerId = model.ID(vDevs[i].ID) svc.ParentContainerType = model.DeviceContainer if vDevs[i].Room != nil { svc.LocationId = model.ID(*vDevs[i].Room) } services = append(services, svc) } } return services, nil } func (VinculumRegistryStore) GetThingExtendedViewById(Id model.ID) (*model.ThingExtendedView, error) { //log.Warn("GetThingExtendedViewById NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetServiceByAddress(serviceName string, serviceAddress string) (*model.Service, error) { //log.Warn("GetServiceByAddress NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetExtendedServices(serviceNameFilter string, filterWithoutAlias bool, thingIdFilter model.ID, locationIdFilter model.ID) ([]model.ServiceExtendedView, error) { var svcs []model.ServiceExtendedView return svcs, errors.New("not implemented") } func (r *VinculumRegistryStore) GetAllLocations() ([]model.Location, error) { site, err := r.vApi.GetSite(true) if err != nil { return nil, err } var locations []model.Location for i := range site.Areas { loc := model.Location{} loc.ID = model.ID(site.Areas[i].ID) * (-1) loc.Type = "area" loc.Alias = site.Areas[i].Name loc.SubType = site.Areas[i].Type locations = append(locations, loc) } for i := range site.Rooms { loc := model.Location{} loc.ID = model.ID(site.Rooms[i].ID) loc.Type = "room" loc.Alias = site.Rooms[i].Alias if site.Rooms[i].Type != nil { loc.SubType = *site.Rooms[i].Type } if site.Rooms[i].Area != nil { loc.ParentID = model.ID(*site.Rooms[i].Area) } locations = append(locations, loc) } return locations, nil } func (VinculumRegistryStore) GetThingById(Id model.ID) (*model.Thing, error) { //log.Warn("GetThingById NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetThingByAddress(technology string, address string) (*model.Thing, error) { //log.Warn("GetThingByAddress NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetThingExtendedViewByAddress(technology string, address string) (*model.ThingExtendedView, error) { //log.Warn("GetThingExtendedViewByAddress NOT implemented !!!!") return nil, errors.New("not implemented") } func (r *VinculumRegistryStore) GetThingsByLocationId(locationId model.ID) ([]model.Thing, error) { site, err := r.vApi.GetSite(true) if err != nil { return nil, err } var things []model.Thing //err := st.db.Select(q.Eq("LocationId", locationId)).Find(&things) //return things, err for i := range site.Things { if site.Things[i].RoomID == int(locationId) { thing, err := r.GetThingById(model.ID(site.Things[i].RoomID)) if err != nil { things = append(things, *thing) } } } return things, nil } func (VinculumRegistryStore) GetThingByIntegrationId(id string) (*model.Thing, error) { //log.Warn("GetThingByIntegrationId NOT implemented !!!!") return nil, errors.New("not implemented") } func (r *VinculumRegistryStore) GetAllDevices() ([]model.Device, error) { site, err := r.vApi.GetSite(true) if err != nil { return nil, err } vDevices := site.Devices var devices []model.Device for i := range vDevices { device := model.Device{} device.ID = model.ID(vDevices[i].ID) if vDevices[i].Client.Name != nil { device.Alias = *vDevices[i].Client.Name } if vDevices[i].Room != nil { device.LocationId = model.ID(*vDevices[i].Room) } if vDevices[i].ThingID != nil { device.ThingId = model.ID(*vDevices[i].ThingID) } var dtype, dsubtype string if vDevices[i].Type["type"] != nil { dtype, _ = vDevices[i].Type["type"].(string) } if vDevices[i].Type["subtype"] != nil { dsubtype, _ = vDevices[i].Type["subtype"].(string) dsubtype = "." + dsubtype } device.Type = fmt.Sprintf("%s%s", dtype, dsubtype) devices = append(devices, device) } return devices, nil } func (r *VinculumRegistryStore) GetExtendedDevices() ([]model.DeviceExtendedView, error) { devices, err := r.GetAllDevices() if err != nil { return nil, err } var extDevices []model.DeviceExtendedView for i := range devices { location, err := r.GetLocationById(devices[i].LocationId) var locationAlias string if err == nil && location != nil { locationAlias = fmt.Sprintf("%s(%s %s)", location.Alias, location.Type, location.SubType) } dev := model.DeviceExtendedView{ Device: devices[i], Services: nil, LocationAlias: locationAlias, } extDevices = append(extDevices, dev) } return extDevices, nil } func (VinculumRegistryStore) GetDeviceById(Id model.ID) (*model.DeviceExtendedView, error) { //log.Warn("GetThingByIntegrationId NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetDevicesByLocationId(locationId model.ID) ([]model.Device, error) { //log.Warn("GetThingByIntegrationId NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetDeviceByIntegrationId(id string) (*model.Device, error) { //log.Warn("GetThingByIntegrationId NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) GetLocationByIntegrationId(id string) (*model.Location, error) { //log.Warn("GetThingByIntegrationId NOT implemented !!!!") return nil, errors.New("not implemented") } func (VinculumRegistryStore) UpsertThing(thing *model.Thing) (model.ID, error) { log.Warn("UpsertThing NOT implemented !!!!") return 0, errors.New("not implemented") } func (VinculumRegistryStore) UpsertService(service *model.Service) (model.ID, error) { log.Warn("UpsertService NOT implemented !!!!") return 0, errors.New("not implemented") } func (VinculumRegistryStore) UpsertLocation(location *model.Location) (model.ID, error) { log.Warn("UpsertLocation NOT implemented !!!!") return 0, errors.New("not implemented") } func (VinculumRegistryStore) DeleteThing(id model.ID) error { log.Warn("DeleteThing NOT implemented !!!!") return errors.New("not implemented") } func (VinculumRegistryStore) DeleteService(id model.ID) error { log.Warn("DeleteService NOT implemented !!!!") return errors.New("not implemented") } func (VinculumRegistryStore) DeleteLocation(id model.ID) error { log.Warn("DeleteLocation NOT implemented !!!!") return errors.New("not implemented") } func (VinculumRegistryStore) ReindexAll() error { log.Warn("ReindexAll NOT implemented !!!!") return errors.New("not implemented") } func (r *VinculumRegistryStore) Sync() error { return r.vApi.ReloadSiteToCache(3) } func (VinculumRegistryStore) ClearAll() error { log.Warn("ClearAll NOT implemented !!!!") return errors.New("not implemented") } func (r *VinculumRegistryStore) GetConnection() interface{} { log.Warn("GetConnection NOT implemented !!!!") return errors.New("not implemented") } func (VinculumRegistryStore) GetState() string { return "RUNNING" } func (r *VinculumRegistryStore) LoadConfig(config interface{}) error { return nil } func (r *VinculumRegistryStore) Init() error { return nil } func (r *VinculumRegistryStore) Stop() { return }
[ 4 ]
package main /* * 题目 * 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 * 如果不存在最后一个单词,请返回 0 。 * 说明:一个单词是指由字母组成,但不包含任何空格的字符串。 * 示例: * 输入: "Hello World" * 输出: 5 */ func main() { str := "a " lengthOfLastWord(str) } /* * 思路 * 倒序查找,找到是否存在 * 耗时 * 执行用时 : 0 ms, 在Length of Last Word的Go提交中击败了100.00% 的用户 * 内存消耗 : 2.2 MB, 在Length of Last Word的Go提交中击败了39.13% 的用户 * 时间复杂度 * O(n) */ func lengthOfLastWord(s string) int { count := 0 for i := len(s) - 1; i >= 0 ;i-- { if s[i] != 32 { count++ } else { if count > 0 { return count } } } if count != 0 { return count } return 0 }
[ 4 ]
package main import ( "database/sql" "flag" "fmt" "github.com/BurntSushi/toml" _ "github.com/lib/pq" "io/ioutil" "log" "os" "os/signal" "syscall" "time" ) type postgresConfig struct { User string `toml:"user"` Password string `toml:"password"` Address string `toml:"address"` Port string `toml:"port"` Database string `toml:"database"` } type daemonConfig struct { AggregationInterval time.Duration `toml:"aggregationinterval"` CleanupInterval time.Duration `toml:"cleanupinterval"` DbCOnfig postgresConfig `toml:"postgres"` } var configFile = flag.String("config", "", "configuration file") var verbose = flag.Bool("v", false, "verbose output") var config daemonConfig var db *sql.DB type jobStatus struct { Err error Duration time.Duration } type job struct { Name string RunJob func(chan jobStatus) Interval time.Duration } func (j *job) Run() { ticker := time.NewTicker(j.Interval) status := make(chan jobStatus) defer func() { ticker.Stop() close(status) }() handleStatus := func(s jobStatus) { if s.Err != nil { log.Panicf("Error during job '%s': %s", j.Name, s.Err) } if *verbose { log.Printf("Job '%s' took %s", j.Name, s.Duration) } if s.Duration > config.AggregationInterval { log.Printf("WARNING: Job '%s' took longer than interval (%s)!", j.Name, s.Duration) } } for { if *verbose { log.Printf("Running job '%s'...", j.Name) } go j.RunJob(status) select { case <-ticker.C: s := <-status handleStatus(s) case s := <-status: handleStatus(s) <-ticker.C } } } func newDbFunc(query string) func(chan jobStatus) { return func(state chan jobStatus) { start := time.Now() tx, err := db.Begin() if err != nil { state <- jobStatus{err, time.Since(start)} return } defer func() { if err != nil { tx.Rollback() } }() _, err = tx.Exec(query) if err != nil { _ = tx.Rollback() state <- jobStatus{err, time.Since(start)} return } state <- jobStatus{tx.Commit(), time.Since(start)} return } } func openDb(sqlAddr, sqlPort, sqlDb, sqlUser, sqlPass string) (*sql.DB, error) { cfg := fmt.Sprintf("user=%s password=%s dbname=%s host=%s port=%s sslmode=disable", sqlUser, sqlPass, sqlDb, sqlAddr, sqlPort, ) postgres, err := sql.Open("postgres", cfg) if err != nil { return nil, err } return postgres, nil } func init() { flag.Parse() if *configFile == "" { log.Fatal("missing -config") } configData, err := ioutil.ReadFile(*configFile) if err != nil { log.Fatalf("could not read config file: %v", err.Error()) } if err := toml.Unmarshal(configData, &config); err != nil { log.Fatalf("could not load config file: %v", err.Error()) } if config.DbCOnfig.User == "" || config.DbCOnfig.Address == "" || config.DbCOnfig.Database == "" { log.Fatal("postgres config incomplete") } config.AggregationInterval = config.AggregationInterval * time.Minute config.CleanupInterval = config.CleanupInterval * time.Minute db, err = openDb(config.DbCOnfig.Address, config.DbCOnfig.Port, config.DbCOnfig.Database, config.DbCOnfig.User, config.DbCOnfig.Password) if err != nil { log.Fatal("error opening user db: ", err) } } func main() { defer db.Close() if config.AggregationInterval != 0 { aggrJob := job{Name: "Aggregation", RunJob: newDbFunc(`SELECT do_aggregate()`), Interval: config.AggregationInterval} go aggrJob.Run() } else { if *verbose { log.Println("Aggregation interval not set or 0, not starting aggregation job.") } } if config.CleanupInterval != 0 { aggrJob := job{Name: "Cleanup", RunJob: newDbFunc(`SELECT do_remove_old_values()`), Interval: config.CleanupInterval} go aggrJob.Run() } else { if *verbose { log.Println("Cleanup interval not set or 0, not starting cleanup job.") } } c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) <-c log.Println("Exiting...") }
[ 4 ]
package rediscomm import ( "gylib/common/redispack" "encoding/json" "gylib/common/datatype" "github.com/garyburd/redigo/redis" ) type RedisComm_pool struct { Key string RdPack *redispack.RedisPack clinet redis.Conn is_con bool Field string Common_exec string Timeout int Re_prefix string Data interface{} } func NewRedisComm_pool(action string) (*RedisComm_pool) { this := new(RedisComm_pool) this.RdPack=redispack.Redis_mui_init(action) this.clinet=this.RdPack.Get_redis_pool().Get() this.is_con=true this.Re_prefix = this.RdPack.Rp_data["redis_perfix"] this.Timeout = 3600 this.Common_exec = "SET" return this } func (this *RedisComm_pool) GetPool(){ if(!this.is_con){ this.clinet=this.RdPack.Get_redis_pool().Get() }else { if (this.clinet == nil) { this.clinet = this.RdPack.Get_redis_pool().Get() } } } func (this *RedisComm_pool)ClosePool(){ this.clinet.Close() this.is_con=false } func (this *RedisComm_pool) Flushdb() { client := this.clinet client.Do("FLUSHDB") } func (this *RedisComm_pool) HasKey() (bool) { client := this.clinet hasok, err := client.Do("EXISTS", this.Key) if (err != nil) { return false } if (datatype.Type2int(hasok) == 0) { return false } else { return true } } func (this *RedisComm_pool) DelKey() (bool) { client := this.clinet _, err := client.Do("DEL", this.Key) if (err != nil) { return false } return true } func (this *RedisComm_pool) GetRawValue() (interface{}) { client := this.clinet raw, err := client.Do("GET", this.Key) if (err != nil) { return nil } if (raw == nil) { return nil } return raw } func (this *RedisComm_pool) SetRawValue() { client := this.clinet if (this.Common_exec == "SETEX") { client.Do("SETEX", this.Key, this.Timeout, this.Data) } else { client.Do("SET", this.Key, this.Data) } } func(this *RedisComm_pool)Getkey()(string){ return this.Key } func (this *RedisComm_pool) SetKey(key string) (*RedisComm_pool) { if (this.Re_prefix != "") { strlen := len(this.Re_prefix) if(len(key)<strlen){ this.Key = this.Re_prefix + key return this } if (key[:strlen] == this.Re_prefix) { this.Key = key } else { this.Key = this.Re_prefix + key } } else { this.Key = key } //fmt.Println(this.Key,key) return this } func (this *RedisComm_pool) GetHmapLen()(int){ client := this.clinet raw, err := client.Do("HLEN", this.Key) if(err!=nil){ return 0 }else { return datatype.Type2int(raw) } } func (this *RedisComm_pool) SetFiled(key string) (*RedisComm_pool) { this.Field = key return this } func (this *RedisComm_pool) SetExec(key string) (*RedisComm_pool) { this.Common_exec = key return this } func (this *RedisComm_pool) SetTime(timect int) (*RedisComm_pool) { this.Timeout = timect return this } func (this *RedisComm_pool) SetData(data interface{}) (*RedisComm_pool) { this.Data = data return this } func (this *RedisComm_pool) Get_value() (interface{}) { client := this.clinet raw, err := client.Do("GET", this.Key) if (err != nil) { return nil } if (raw == nil) { return nil } //var data interface{} err = json.Unmarshal(raw.([]byte), &this.Data) if (err != nil) { return nil } return this.Data } func (this *RedisComm_pool) Set_value() { client := this.clinet raw, _ := json.Marshal(&this.Data) if (this.Common_exec == "SETEX") { client.Do("SETEX", this.Key, this.Timeout, raw) } else { client.Do("SET", this.Key, raw) } } func (this *RedisComm_pool) SetList() { client := this.clinet raw, _ := json.Marshal(&this.Data) client.Do("LPUSH", this.Key, raw) } func (this *RedisComm_pool) GetList() (interface{}) { client := this.clinet raw, err := client.Do("RPOP", this.Key) if (err != nil) { return nil } if (raw == nil) { return nil } //var data interface{} err = json.Unmarshal(raw.([]byte), &this.Data) if (err != nil) { return nil } return this.Data } func (this *RedisComm_pool) Hset_map() { client := this.clinet raw, _ := json.Marshal(&this.Data) client.Do("HSET", this.Key, this.Field, raw) } func (this *RedisComm_pool) Hset_raw() { client := this.clinet raw:= this.Data client.Do("HSET", this.Key, this.Field, raw) } func (this *RedisComm_pool) Hdel_map() { client := this.clinet client.Do("HDEL", this.Key, this.Field) } func (this *RedisComm_pool) HEXISTS() (bool) { client := this.clinet hasok, err := client.Do("HEXISTS", this.Key,this.Field) if (err != nil) { return false } if (datatype.Type2int(hasok) == 0) { return false } else { return true } } func (this *RedisComm_pool) Hget_map() (interface{}) { client := this.clinet raw, err := client.Do("HGET", this.Key, this.Field) if (err != nil) { return nil } if (raw == nil) { return nil } //var data interface{} //fmt.Println("raw=",string(raw.([]byte))) err = json.Unmarshal(raw.([]byte), &this.Data) if (err != nil) { //fmt.Println(this.Key,this.Field,err) return nil } return this.Data } func (this *RedisComm_pool) Hget_raw() (interface{}) { client := this.clinet raw, err := client.Do("HGET", this.Key, this.Field) if (err != nil) { return nil } if (raw == nil) { return nil } return raw } func (this *RedisComm_pool) Push(channel_name, message string) (int) { //发布者 client := this.clinet raw, _ := client.Do("PUBLISH", channel_name, message) return datatype.Type2int(raw) } func(this *RedisComm_pool) Hincby(n int){ client := this.clinet client.Do("HINCRBY", this.Key,this.Field,n) }
[ 4 ]
package db import ( "github.com/diaohaha/termite/dal" "github.com/diaohaha/termite/stable" ) func GetTermiteWorkConfigs() (ret []dal.TermiteWorkConfig, err error) { err = RODB.Find(&ret).Error return ret, err } func GetTermiteWorkConfig(workKey string) (ret dal.TermiteWorkConfig, err error) { err = RODB.Where("work_key = ?", workKey).First(&ret).Error return ret, err } func GetTermiteFlowConfigs() (ret []dal.TermiteFlowConfig, err error) { err = RODB.Find(&ret).Error return ret, err } func GetTermiteFlowConfig(flowKey string) (ret dal.TermiteFlowConfig, err error) { err = RODB.Where("flow_key = ?", flowKey).First(&ret).Error return ret, err } func UpdateTermiteFlowConfig(config dal.TermiteFlowConfig) error { err := WTDB.Save(&config).Error return err } func UpdateTermiteWorkConfig(config dal.TermiteWorkConfig) error { err := WTDB.Save(&config).Error return err } func DeleteTermiteFlowConfig(flow_key string) { WTDB.Delete(dal.TermiteFlowConfig{}, "flow_key = ?", flow_key) } func DeleteTermiteWorkConfig(work_key string) { WTDB.Delete(dal.TermiteWorkConfig{}, "work_key = ?", work_key) } func QueryTermiteFlowConfigs(vflow string, search string, pageIndex int, pageSize int) (flowConfigs []dal.TermiteFlowConfig, count int, err error) { // 查询工作流配置 query := RODB.Model(dal.TermiteFlowConfig{}) if vflow != "" { query = query.Where("flow_key = ?", vflow) } else { if search != "" { query = query.Where("flow_key like ?", "%"+search+"%") } } err = query.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&flowConfigs).Error if err != nil { stable.Logger.Error("QueryTermiteFlowConfigs Error") } err = query.Count(&count).Error if err != nil { stable.Logger.Error("QueryTermiteFlowConfigs Error") } return } func QueryTermiteWorkConfigs(vwork string, search string, pageIndex int, pageSize int) (workConfigs []dal.TermiteWorkConfig, count int, err error) { // 查询工作配置 query := RODB.Model(dal.TermiteWorkConfig{}) if vwork != "" { query = query.Where("work_key = ?", vwork) } else { if search != "" { query = query.Where("work_key like ?", "%"+search+"%") } } err = query.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&workConfigs).Error if err != nil { stable.Logger.Error("QueryTermiteWorkConfigs Error") } err = query.Count(&count).Error if err != nil { stable.Logger.Error("QueryTermiteWorkConfigs Error") } return } func UpdateFlowSwitch(vflow string, iswitch int) (err error) { // 更新工作流开关 var flowConfig dal.TermiteFlowConfig err = RODB.Model(dal.TermiteFlowConfig{}).Where("flow_key = ?", vflow).Find(&flowConfig).Error if err != nil { stable.Logger.Error("UpdateFlowSwitch Error") return } flowConfig.Switch = iswitch err = WTDB.Save(&flowConfig).Error if err != nil { stable.Logger.Error("UpdateFlowSwitch Error") return } return }
[ 4 ]
package commands import ( "github.com/abiosoft/ishell" "github.com/bwhaley/ssmsh/parameterstore" ) const getUsage string = ` get usage: get parameter ... Get one or more parameters. ` // Get parameters func get(c *ishell.Context) { if len(c.Args) >= 1 { var params []parameterstore.ParameterPath for _, p := range c.Args { params = append(params, parsePath(p)) } paramsByRegion := groupByRegion(params) for region, params := range paramsByRegion { resp, err := ps.Get(params, region) if err != nil { shell.Println("Error: ", err) } else { if len(resp) >= 1 { printResult(resp) } } } } else { shell.Println(getUsage) } }
[ 4 ]