Skip to content

Commit

Permalink
开放源码
Browse files Browse the repository at this point in the history
  • Loading branch information
lisijie committed Aug 5, 2016
1 parent 27ad623 commit 1a1a028
Show file tree
Hide file tree
Showing 216 changed files with 10,714 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
gopub*
data/*
logs/*.log
build.tar.gz
*.bak
161 changes: 161 additions & 0 deletions app/controllers/agent.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
package controllers

import (
"errors"
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/validation"
"github.com/lisijie/gopub/app/entity"
"github.com/lisijie/gopub/app/libs"
"github.com/lisijie/gopub/app/service"
"strconv"
)

type AgentController struct {
BaseController
}

// 列表
func (this *AgentController) List() {
page, _ := strconv.Atoi(this.GetString("page"))
if page < 1 {
page = 1
}
count, err := service.ServerService.GetTotal(service.SERVER_TYPE_AGENT)
this.checkError(err)
serverList, err := service.ServerService.GetAgentList(page, this.pageSize)
this.checkError(err)

this.Data["count"] = count
this.Data["list"] = serverList
this.Data["pageBar"] = libs.NewPager(page, int(count), this.pageSize, beego.URLFor("AgentController.List"), true).ToString()
this.Data["pageTitle"] = "跳板机列表"
this.display()
}

// 添加
func (this *AgentController) Add() {
if this.isPost() {
server := &entity.Server{}
server.TypeId = service.SERVER_TYPE_AGENT
server.Ip = this.GetString("server_ip")
server.Area = this.GetString("area")
server.SshPort, _ = this.GetInt("ssh_port")
server.SshUser = this.GetString("ssh_user")
server.SshPwd = this.GetString("ssh_pwd")
server.SshKey = this.GetString("ssh_key")
server.WorkDir = this.GetString("work_dir")
server.Description = this.GetString("description")
err := this.validServer(server)
this.checkError(err)
err = service.ServerService.AddServer(server)
this.checkError(err)
//service.ActionService.Add("add_agent", this.auth.GetUserName(), "server", server.Id, server.Ip)
this.redirect(beego.URLFor("AgentController.List"))
}

this.Data["pageTitle"] = "添加跳板机"
this.display()
}

// 编辑
func (this *AgentController) Edit() {
id, _ := this.GetInt("id")
server, err := service.ServerService.GetServer(id, service.SERVER_TYPE_AGENT)
this.checkError(err)

if this.isPost() {
server.Ip = this.GetString("server_ip")
server.Area = this.GetString("area")
server.SshPort, _ = this.GetInt("ssh_port")
server.SshUser = this.GetString("ssh_user")
server.SshPwd = this.GetString("ssh_pwd")
server.SshKey = this.GetString("ssh_key")
server.WorkDir = this.GetString("work_dir")
server.Description = this.GetString("description")
err := this.validServer(server)
this.checkError(err)
err = service.ServerService.UpdateServer(server)
this.checkError(err)
//service.ActionService.Add("edit_agent", this.auth.GetUserName(), "server", server.Id, server.Ip)
this.redirect(beego.URLFor("AgentController.List"))
}

this.Data["pageTitle"] = "编辑跳板机"
this.Data["server"] = server
this.display()
}

// 删除
func (this *AgentController) Del() {
id, _ := this.GetInt("id")

_, err := service.ServerService.GetServer(id, service.SERVER_TYPE_AGENT)
this.checkError(err)

err = service.ServerService.DeleteServer(id)
this.checkError(err)
//service.ActionService.Add("del_agent", this.auth.GetUserName(), "server", id, "")

this.redirect(beego.URLFor("AgentController.List"))
}

// 项目列表
func (this *AgentController) Projects() {
id, _ := this.GetInt("id")
server, err := service.ServerService.GetServer(id, service.SERVER_TYPE_AGENT)
this.checkError(err)
envList, err := service.EnvService.GetEnvListByServerId(id)
this.checkError(err)

result := make(map[int]map[string]interface{})
for _, env := range envList {
if _, ok := result[env.ProjectId]; !ok {
project, err := service.ProjectService.GetProject(env.ProjectId)
if err != nil {
continue
}
row := make(map[string]interface{})
row["projectId"] = project.Id
row["projectName"] = project.Name
row["envName"] = env.Name
result[env.ProjectId] = row
} else {
result[env.ProjectId]["envName"] = result[env.ProjectId]["envName"].(string) + ", " + env.Name
}
}

this.Data["list"] = result
this.Data["server"] = server
this.Data["pageTitle"] = server.Ip + " 下的项目列表"
this.display()
}

func (this *AgentController) validServer(server *entity.Server) error {
valid := validation.Validation{}
valid.Required(server.Ip, "ip").Message("请输入服务器IP")
valid.Range(server.SshPort, 1, 65535, "ssh_port").Message("SSH端口无效")
valid.Required(server.SshUser, "ssh_user").Message("SSH用户名不能为空")
valid.Required(server.WorkDir, "work_dir").Message("工作目录不能为空")
valid.IP(server.Ip, "ip").Message("服务器IP无效")
if valid.HasErrors() {
for _, err := range valid.Errors {
return errors.New(err.Message)
}
}
if server.SshKey != "" && !libs.IsFile(libs.RealPath(server.SshKey)) {
return errors.New("SSH Key不存在:" + server.SshKey)
}

addr := fmt.Sprintf("%s:%d", server.Ip, server.SshPort)
serv := libs.NewServerConn(addr, server.SshUser, server.SshKey)

if err := serv.TryConnect(); err != nil {
return errors.New("无法连接到跳板机: " + err.Error())
} else if _, err := serv.RunCmd("mkdir -p " + server.WorkDir); err != nil {
return errors.New("无法创建跳板机工作目录: " + err.Error())
}
serv.Close()

return nil
}
191 changes: 191 additions & 0 deletions app/controllers/base.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
package controllers

import (
"encoding/json"
"github.com/astaxie/beego"
"github.com/beego/i18n"
"github.com/lisijie/gopub/app/service"
"io/ioutil"
"strings"
)

const (
MSG_OK = 0 // ajax输出错误码,成功
MSG_ERR = -1 // 错误
MSG_REDIRECT = -2 // 重定向
)

type BaseController struct {
beego.Controller
auth *service.AuthService // 验证服务
userId int // 当前登录的用户id
controllerName string // 控制器名
actionName string // 动作名
pageSize int // 默认分页大小
lang string // 当前语言环境
}

// 重写GetString方法,移除前后空格
func (this *BaseController) GetString(name string, def ...string) string {
return strings.TrimSpace(this.Controller.GetString(name, def...))
}

func (this *BaseController) Prepare() {
this.Ctx.Output.Header("X-Powered-By", "GoPub/"+beego.AppConfig.String("version"))
this.Ctx.Output.Header("X-Author-By", "lisijie")
controllerName, actionName := this.GetControllerAndAction()
this.controllerName = strings.ToLower(controllerName[0 : len(controllerName)-10])
this.actionName = strings.ToLower(actionName)
this.pageSize = 20
this.initAuth()
this.initLang()
this.getMenuList()
}

func (this *BaseController) initLang() {
this.lang = "zh-CN"
this.Data["lang"] = this.lang
if !i18n.IsExist(this.lang) {
if err := i18n.SetMessage(this.lang, beego.AppPath+"/conf/locale_"+this.lang+".ini"); err != nil {
beego.Error("Fail to set message file: " + err.Error())
return
}

}
}

//登录验证
func (this *BaseController) initAuth() {
token := this.Ctx.GetCookie("auth")
this.auth = service.NewAuth()
this.auth.Init(token)
this.userId = this.auth.GetUserId()

if !this.auth.IsLogined() {
if this.controllerName != "main" ||
(this.controllerName == "main" && this.actionName != "logout" && this.actionName != "login") {
this.redirect(beego.URLFor("MainController.Login"))
}
} else {
if !this.auth.HasAccessPerm(this.controllerName, this.actionName) {
this.showMsg("您没有执行该操作的权限", MSG_ERR)
}
}
}

//渲染模版
func (this *BaseController) display(tpl ...string) {
var tplname string
if len(tpl) > 0 {
tplname = tpl[0] + ".html"
} else {
tplname = this.controllerName + "/" + this.actionName + ".html"
}

this.Layout = "layout/layout.html"
this.TplName = tplname

this.LayoutSections = make(map[string]string)
this.LayoutSections["Header"] = "layout/sections/header.html"
this.LayoutSections["Footer"] = "layout/sections/footer.html"
this.LayoutSections["Navbar"] = "layout/sections/navbar.html"
this.LayoutSections["Sidebar"] = "layout/sections/sidebar.html"

user := this.auth.GetUser()

this.Data["version"] = beego.AppConfig.String("version")
this.Data["curRoute"] = this.controllerName + "." + this.actionName
this.Data["loginUserId"] = user.Id
this.Data["loginUserName"] = user.UserName
this.Data["loginUserSex"] = user.Sex
this.Data["menuList"] = this.getMenuList()
}

// 重定向
func (this *BaseController) redirect(url string) {
if this.IsAjax() {
this.showMsg("", MSG_REDIRECT, url)
} else {
this.Redirect(url, 302)
this.StopRun()
}
}

// 是否POST提交
func (this *BaseController) isPost() bool {
return this.Ctx.Request.Method == "POST"
}

// 提示消息
func (this *BaseController) showMsg(msg string, msgno int, redirect ...string) {
out := make(map[string]interface{})
out["status"] = msgno
out["msg"] = msg
out["redirect"] = ""
if len(redirect) > 0 {
out["redirect"] = redirect[0]
}

if this.IsAjax() {
this.jsonResult(out)
} else {
for k, v := range out {
this.Data[k] = v
}
this.display("error/message")
this.Render()
this.StopRun()
}
}

//获取用户IP地址
func (this *BaseController) getClientIp() string {
if p := this.Ctx.Input.Proxy(); len(p) > 0 {
return p[0]
}
return this.Ctx.Input.IP()
}

// 功能菜单
func (this *BaseController) getMenuList() []Menu {
var menuList []Menu
allMenu := make([]Menu, 0)
content, err := ioutil.ReadFile("conf/menu.json")
if err == nil {
err := json.Unmarshal(content, &allMenu)
if err != nil {
beego.Error(err.Error())
}
}
menuList = make([]Menu, 0)
for _, menu := range allMenu {
subs := make([]SubMenu, 0)
for _, sub := range menu.Submenu {
route := strings.Split(sub.Route, ".")
if this.auth.HasAccessPerm(route[0], route[1]) {
subs = append(subs, sub)
}
}
if len(subs) > 0 {
menu.Submenu = subs
menuList = append(menuList, menu)
}
}
//menuList = allMenu

return menuList
}

// 输出json
func (this *BaseController) jsonResult(out interface{}) {
this.Data["json"] = out
this.ServeJSON()
this.StopRun()
}

// 错误检查
func (this *BaseController) checkError(err error) {
if err != nil {
this.showMsg(err.Error(), MSG_ERR)
}
}
Loading

0 comments on commit 1a1a028

Please sign in to comment.