diff --git a/go.work.sum b/go.work.sum index 9a9e97a3..482c7678 100644 --- a/go.work.sum +++ b/go.work.sum @@ -2,6 +2,7 @@ github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbi github.com/Masterminds/semver v1.4.2 h1:WBLTQ37jOCzSLtXNdoo8bNM8876KhNqOKvrlGITgsTc= github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= +github.com/cockroachdb/cockroach-go v0.0.0-20181001143604-e0a95dfd547c h1:2zRrJWIt/f9c9HhNHAgrRgq0San5gRRUJTBXLkchal0= github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= github.com/go-co-op/gocron v1.28.1 h1:z2+Y094RkGriilTVdGq6IeNbTkZbGMTQSxK4zITogo0= @@ -23,12 +24,15 @@ github.com/gobuffalo/helpers v0.6.5/go.mod h1:LA4zcc89tkZsfKpJIWsXLibiqTgZQ4EvDs github.com/gobuffalo/here v0.6.6/go.mod h1:C4JZL5PsXWKzP/CAchaIzuUWlaae6CaAiMYQ0ieY62M= github.com/gobuffalo/httptest v1.5.1/go.mod h1:uEeEFF2BRyTMNAATqFQAKYvpHrWWPNoJbIB3YPuANNM= github.com/gobuffalo/logger v1.0.6/go.mod h1:J31TBEHR1QLV2683OXTAItYIg8pv2JMHnF/quuAbMjs= +github.com/gobuffalo/makr v1.1.5 h1:lOlpv2iz0dNa4qse0ZYQgbtT+ybwVxWEAcOZbcPmeYc= github.com/gobuffalo/meta v0.3.2/go.mod h1:qTZ/9n499kXeJ49PHHoSQr63R+kWNpQKiYD62C+AtHI= github.com/gobuffalo/mw-csrf v0.0.0-20180802151833-446ff26e108b h1:A13B4mhcFQcjPJ1GFBrh61B4Qo87fZa82FfTt9LX/QU= github.com/gobuffalo/mw-csrf v1.0.1/go.mod h1:JAbogWdDR+194rn3Rt8/qf/9RTmFvml9FXEGGAAJ9WU= github.com/gobuffalo/mw-i18n v0.0.0-20181027200759-09e0c99be4d3 h1:ACN4mEXAmv7u1H8niLxZOzuKymMj5rvBmZqShrXOVf0= github.com/gobuffalo/nulls v0.4.1/go.mod h1:pp8e1hWTRJZFpMl4fj/CVbSMlaxjeGKkFq4RuBZi3w8= github.com/gobuffalo/packd v1.0.1/go.mod h1:PP2POP3p3RXGz7Jh6eYEf93S7vA2za6xM7QT85L4+VY= +github.com/gobuffalo/packd v1.0.2 h1:Yg523YqnOxGIWCp69W12yYBKsoChwI7mtu6ceM9Bwfw= +github.com/gobuffalo/packr v1.19.0 h1:3UDmBDxesCOPF8iZdMDBBWKfkBoYujIMIZePnobqIUI= github.com/gobuffalo/plush v3.7.22+incompatible h1:SJxTrFxizR3wCxb7GOYf1ZUjo3mfAczK4B/FYROZg00= github.com/gobuffalo/plush/v4 v4.1.13/go.mod h1:s3hUyj/JlwEiJ039OBJevojq9xT40D1pgekw0o88CVU= github.com/gobuffalo/pop v4.8.8+incompatible h1:att8VCpyFCwEghYseiPqYcxOEh9TjL+DgM2WyKTTrNg= @@ -42,10 +46,12 @@ github.com/gobuffalo/uuid v2.0.5+incompatible h1:c5uWRuEnYggYCrT9AJm0U2v1QTG7OVD github.com/gobuffalo/validate v2.0.3+incompatible h1:6f4JCEz11Zi6iIlexMv7Jz10RBPvgI795AOaubtCwTE= github.com/gobuffalo/validate/v3 v3.3.2/go.mod h1:jiEEw+N7KbAP2aInFxGnfitI0g7HjXqcp5hDD6TaQDU= github.com/gofrs/uuid v4.1.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/jackc/chunkreader v1.0.0 h1:4s39bBR8ByfqH+DKm8rQA3E1LHZWB9XWcrz8fqaZbe0= +github.com/jackc/fake v0.0.0-20150926172116-812a484cc733 h1:vr3AYkKovP8uR8AvSGGUK1IDqRa5lAAvEkZG1LKaCRc= github.com/jackc/pgconn v1.12.1/go.mod h1:ZkhRC59Llhrq3oSfrikvwQ5NaxYExr6twkdkMLaKono= github.com/jackc/pgproto3 v1.1.0 h1:FYYE4yRw+AgI8wXIinMlNjBbp/UitDJwfj5LqqewP1A= github.com/jackc/pgproto3/v2 v2.3.0/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= @@ -58,6 +64,8 @@ github.com/karrick/godirwalk v1.16.1/go.mod h1:j4mkqPuvaLI8mp1DroR3P6ad7cyYd4c1q github.com/lib/pq v1.10.6/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/markbates/going v1.0.2 h1:uNQHDDfMRNOUmuxDbPbvatyw4wr4UOSUZkGkdkcip1o= github.com/markbates/grift v1.5.0/go.mod h1:1ssFm5gSGmzTkhi3Wfh/nqlU74J73TlAjoDMttQbpfY= +github.com/markbates/inflect v1.0.4 h1:5fh1gzTFhfae06u3hzHYO9xe3l3v3nW5Pwt3naLTP5g= +github.com/markbates/oncer v0.0.0-20181014194634-05fccaae8fc4 h1:Mlji5gkcpzkqTROyE4ZxZ8hN7osunMb2RuGVrbvMvCc= github.com/markbates/oncer v1.0.0/go.mod h1:Z59JA581E9GP6w96jai+TGqafHPW+cPfRxz2aSZ0mcI= github.com/markbates/refresh v1.12.0/go.mod h1:Vpwi1+q+2U1VxE7C0Ilj6r2/+TigRzQcLez6XM3bPLc= github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= @@ -70,6 +78,7 @@ github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= +github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g= @@ -80,26 +89,28 @@ go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0= golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE= golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= golang.org/x/tools v0.1.11/go.mod h1:SgwaegtQh8clINPpECJMqnxLv9I09HLqnW3RMqW0CA4= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/tools v0.16.1 h1:TLyB3WofjdOEepBHAU20JdNC1Zbg87elYofWYAY5oZA= golang.org/x/tools v0.16.1/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= diff --git a/mc_web_console_api/actions/_old/adminconfig.go b/mc_web_console_api/actions/_old/adminconfig.go deleted file mode 100644 index fdb82ae4..00000000 --- a/mc_web_console_api/actions/_old/adminconfig.go +++ /dev/null @@ -1,503 +0,0 @@ -package actions - -import ( - "log" - "mc_web_console_api/handler" - "mc_web_console_api/models" - "net/http" - - "github.com/gobuffalo/buffalo" - "github.com/gobuffalo/pop/v6" - "github.com/gofrs/uuid" - "github.com/pkg/errors" -) - -// @Summary RegionGroup 리스트 조회 -// @Description [RegionGroupList] providerId 와 regionGroupName 을 받아 RegionGroupList를 반환합니다. -// @Tags adminconfig -// @Produce json -// @Param provider query string true "provider" -// @Param regionGroupName query string true "regionGroupName" -// @Success 200 {string} string "{"message":"success","status":respStatus.StatusCode,"regionGroup":regionGroupList,}" -// @Failure 400 {string} string "{'error':'respStatus.Message','error':'respStatus.Message'}" -// @Router /api/adminconfig/regiongroup/ [get] -func RegionGroupList(c buffalo.Context) error { - - providerId := c.Params().Get("provider") //id - regionGroupName := c.Params().Get("regionGroupName") //name - - paramRegionGroup := models.RegionGroup{} - paramRegionGroup.ProviderID = providerId - paramRegionGroup.RegionGroupName = regionGroupName - - regionGroupList, respStatus := handler.RegionGroupList(paramRegionGroup) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "regionGroupList": regionGroupList, - })) -} - -// @Summary RegionGroup 단건 Vpc 조회 -// @Description [GetRegionGroup] regionGroupId와 providerId, regionGroupName, regionId 중 한개를 받아 regionGroup을 반환합니다. -// @Tags adminconfig -// @Produce json -// @Param regionGroupId path string true "regionGroupId" -// @Param providerId query string false "providerId" -// @Param regionGroupName query string false "regionGroupName" -// @Param regionId query string false "regionId" -// @Success 200 {string} string "{"message":"success","status":respStatus.StatusCode,"regionGroup":regionGroup,}" -// @Failure 500 {string} string "{'error':'err.Error()','status':'500'}" -// @Router /api/adminconfig/regiongroup/{regionGroupId} [get] -func GetRegionGroup(c buffalo.Context) error { - - regionGroupId := c.Param("regionGroupId") - providerId := c.Params().Get("provider") //id - //regionGroupId := c.Params().Get("regionGroupId") - regionGroupName := c.Params().Get("regionGroupName") //name - regionId := c.Params().Get("regionId") - - paramRegionGroup := models.RegionGroup{} - if regionGroupId != "" { - id, err := uuid.FromString(regionGroupId) - if err != nil { - log.Println("regionGroupId ", regionGroupId) - log.Println("uuid ", err) - return c.Render(500, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": 500, - })) - } - paramRegionGroup.ID = id - } - paramRegionGroup.ProviderID = providerId - paramRegionGroup.RegionGroupName = regionGroupName - if regionId != "" { - rid, err := uuid.FromString(regionId) - if err != nil { - log.Println("regionId ", regionId) - log.Println("uuid ", err) - return c.Render(500, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": 500, - })) - } - paramRegionGroup.RegionID = rid - } - - regionGroup, respStatus := handler.GetRegionGroup(paramRegionGroup) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - log.Println("GetRegionGroup err ", respStatus) - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "regionGroup": regionGroup, - })) -} - -// @Summary Region Group 등록 -// @Description [RegRegionGroup] 리전 그룹을 등록합니다. -// @Tags adminconfig -// @Accept json -// @Produce json -// @Param regionGroup body models.RegionGroup true "models.RegionGroup" -// @Success 200 {string} string "{'message': 'success', 'status': respStatus.StatusCode}" -// @Failure 500 {string} string "{'error':'respStatus.Message','status':respStatus.StatusCode}" -// @Router /api/adminconfig/regiongroup/ [post] -func RegRegionGroup(c buffalo.Context) error { - - regionGroup := &models.RegionGroup{} - if err := c.Bind(regionGroup); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - resultRegionGroup, respStatus := handler.SaveRegionGroup(regionGroup, c) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - log.Println("reg regionGroup ", resultRegionGroup) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - })) -} - -// @Summary Region Group 삭제 -// @Description [DelRegionGroup] 리전 그룹을 삭제합니다. -// @Tags adminconfig -// @Accept json -// @Produce json -// @Param regionGroup body models.RegionGroup true "models.RegionGroup" -// @Success 200 {string} string "{'message': 'success', 'status': respStatus.StatusCode}" -// @Failure 500 {string} string "{'error':'respStatus.Message','status':respStatus.StatusCode}" -// @Router /api/adminconfig/regiongroup/ [delete] -func DelRegionGroup(c buffalo.Context) error { - - regionGroup := &models.RegionGroup{} - if err := c.Bind(regionGroup); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - resultRegionGroup, respStatus := handler.DeleteRegionGroup(regionGroup, c) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - log.Println("reg regionGroup ", resultRegionGroup) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - })) -} - -// @Summary Category 등록 -// @Description [CategoryReg] 카테고리를 등록합니다. -// @Tags adminconfig -// @Accept json -// @Produce json -// @Param Category body models.Category true "models.Category" -// @Success 200 {string} string "{'message': 'success', 'status': 200}" -// @Router /api/adminconfig/category/ [post] -func CategoryReg(c buffalo.Context) error { - category := &models.Category{} - if err := c.Bind(category); err != nil { - return errors.WithStack(err) - } - - tx := c.Value("tx").(*pop.Connection) - err := tx.Save(category) - - if err != nil { - return errors.WithStack(err) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - })) -} - -// @Summary Category 삭제 -// @Description [CategoryDel] 카테고리를 삭제합니다. -// @Tags adminconfig -// @Accept json -// @Produce json -// @Param Category body models.Category true "models.Category" -// @Success 200 {string} string "{'message': 'success', 'status': 200}" -// @Router /api/adminconfig/category/ [delete] -func CategoryDel(c buffalo.Context) error { - category := &models.Category{} - if err := c.Bind(category); err != nil { - return errors.WithStack(err) - } - - tx := c.Value("tx").(*pop.Connection) - err := tx.Destroy(category) - - if err != nil { - return errors.WithStack(err) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - })) -} - -// @Summary Category 리스트 조회 -// @Description [CategoryList] categoryName을 받아 categoryList를 반환합니다. -// @Tags adminconfig -// @Produce json -// @Param categoryName query string true "categoryName" -// @Success 200 {string} string "{"message":"success","status":respStatus.StatusCode,"regionGroup":categoryList,}" -// @Failure 400 {string} string "{'error':'respStatus.Message','error':'respStatus.Message'}" -// @Security CSRFTokenHeader -// @Router /api/adminconfig/category/ [get] -func CategoryList(c buffalo.Context) error { - categoryList := []models.Category{} - - categoryName := c.Params().Get("categoryName") - query := models.DB.Q() - - if categoryName != "" { - query = query.Where("category_name = ?", categoryName) - } - err := query.All(&categoryList) - if err != nil { - log.Println("categoryList err", err) - return errors.WithStack(err) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "categoryList": categoryList, - })) -} - -// @Summary Category 단건 조회 -// @Description [CategoryGet] categoryName을 받아 category 단건을 반환합니다. -// @Tags adminconfig -// @Produce json -// @Param categoryName query string true "categoryName" -// @Success 200 {string} string "{'message':'success','status':'200','category':'category',}" -// @Failure 400 {string} string "{'error':'errors.WithStack(err)'}" -// @Security CSRFTokenHeader -// @Router /api/adminconfig/category/id/{categoryName}/ [get] -func CategoryGet(c buffalo.Context) error { - category := models.Category{} - - categoryName := c.Params().Get("categoryName") - query := models.DB.Q() - - query = query.Where("category_name = ?", categoryName) - - err := query.First(&category) - if err != nil { - log.Println("category err", err) - return errors.WithStack(err) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "category": category, - })) -} - -// @Summary Menu 등록 -// @Description [RegMenu] models.Menu를 받아 메뉴를 단건 등록합니다. -// @Tags adminconfig -// @Produce json -// @Param menu body models.Menu true "models.Menu" -// @Success 200 {string} string "{'message':'success','status':'200'}" -// @Failure 400 {string} string "{'error':'errors.WithStack(err)'}" -// @Router /api/adminconfig/menu/ [post] -func RegMenu(c buffalo.Context) error { - menu := &models.Menu{} - if err := c.Bind(menu); err != nil { - return errors.WithStack(err) - } - - tx := c.Value("tx").(*pop.Connection) - err := tx.Create(menu) - - if err != nil { - return errors.WithStack(err) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - })) -} - -// @Summary Menu 업데이트 -// @Description [UpdateMenu] models.Menu를 받아 메뉴를 단건 업데이트합니다. -// @Tags adminconfig -// @Produce json -// @Param menu body models.Menu true "models.Menu" -// @Success 200 {string} string "{'message':'success','status':'200'}" -// @Failure 400 {string} string "{'error':'errors.WithStack(err)'}" -// @Router /api/adminconfig/menu/ [put] -func UpdateMenu(c buffalo.Context) error { - menu := &models.Menu{} - if err := c.Bind(menu); err != nil { - return errors.WithStack(err) - } - - tx := c.Value("tx").(*pop.Connection) - err := tx.Update(menu) - - if err != nil { - return errors.WithStack(err) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - })) -} - -// @Summary Menu 삭제 -// @Description [DelMenu] models.Menu를 받아 메뉴를 단건 삭제합니다. -// @Tags adminconfig -// @Produce json -// @Param menu body models.Menu true "models.Menu" -// @Success 200 {string} string "{'message':'success','status':'200'}" -// @Failure 400 {string} string "{'error':'errors.WithStack(err)'}" -// @Router /api/adminconfig/menu/ [delete] -func DelMenu(c buffalo.Context) error { - menu := &models.Menu{} - if err := c.Bind(menu); err != nil { - return errors.WithStack(err) - } - - tx := c.Value("tx").(*pop.Connection) - err := tx.Destroy(menu) - - if err != nil { - return errors.WithStack(err) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - })) -} - -// @Summary Menu 리스트 조회 -// @Description [MenuList] menuId, menuName, menuAlias, categoryId 중 순서로 마지막 한개를 받아 메뉴 리스트를 반환합니다. -// @Tags adminconfig -// @Produce json -// @Param menuId query string false "menuId" -// @Param menuName query string false "menuName" -// @Param menuAlias query string false "menuAlias" -// @Param categoryId query string false "categoryId" -// @Success 200 {string} string "{'message':'success','status':'200', 'menuList': 'menuList'}" -// @Failure 400 {string} string "{'error':'errors.WithStack(err)'}" -// @Router /api/adminconfig/menu/ [get] -func MenuList(c buffalo.Context) error { - menuList := []models.Menu{} - - menuId := c.Params().Get("menuId") - menuName := c.Params().Get("menuName") - menuAlias := c.Params().Get("menuAlias") - categoryId := c.Params().Get("categoryId") - - query := models.DB.Q() - - if menuId != "" { - query = query.Where("id = ?", menuId) - } - if menuName != "" { - query = query.Where("name = ?", menuName) - } - if menuAlias != "" { - query = query.Where("alias = ?", menuAlias) - } - if categoryId != "" { - query = query.Where("category_id = ?", categoryId) - } - - err := query.All(&menuList) - if err != nil { - log.Println("categoryList err", err) - return errors.WithStack(err) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "menuList": menuList, - })) -} - -// @Summary Menu 조회 -// @Description [GetMenu] menuId와 menuName, menuAlias, categoryId 중 순서로 마지막 한개를 받아 메뉴를 반환합니다. -// @Tags adminconfig -// @Produce json -// @Param menuId path string true "menuId" -// @Param menuName query string false "menuName" -// @Param menuAlias query string false "menuAlias" -// @Param categoryId query string false "categoryId" -// @Success 200 {string} string "{'message':'success','status':'200', 'menu': 'menu'}" -// @Failure 400 {string} string "{'error':'errors.WithStack(err)'}" -// @Router /api/adminconfig/menu/id/{menuId}/ [get] -func GetMenu(c buffalo.Context) error { - menu := models.Menu{} - - menuId := c.Param("menuId") - menuName := c.Params().Get("menuName") - menuAlias := c.Params().Get("menuAlias") - categoryId := c.Params().Get("categoryId") - query := models.DB.Q() - query = query.Where("id = ?", menuId) - - if menuName != "" { - query = query.Where("menu_name = ?", menuName) - } - if menuAlias != "" { - query = query.Where("alias = ?", menuAlias) - } - if categoryId != "" { - query = query.Where("category_id = ?", categoryId) - } - - err := query.First(&menu) - if err != nil { - log.Println("menu err", err) - return errors.WithStack(err) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "menu": menu, - })) -} - -// @Summary Menu Tree 조회 -// @Description [MenuTree] category, menu구조를 tree형태로 쿼리하여 반환합니다. -// @Tags adminconfig -// @Produce json -// @Success 200 {string} string "{'message':'success','status':'200', 'menutree': 'menutree'}" -// @Failure 400 {string} string "{'error':'errors.WithStack(err)'}" -// @Router /api/adminconfig/menu/tree/ [get] -func MenuTree(c buffalo.Context) error { - - menutree, respStatus := handler.MenuTree() - if respStatus.StatusCode == 500 { - return c.Render(http.StatusOK, r.JSON(respStatus)) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "menutree": menutree, - })) -} - -// @Summary Api Search swagger : todo : 삭제 -// @Description [ApiSearch] Api 핸들러를 찾아 Swagger 로 이동합니다. -// @Tags debug -// @Produce html -// @Success 200 {html} html "redirect" -// @Router /api/test/apitest/searchapi/ [post] -func ApiSearch(c buffalo.Context) error { - - route := &models.RouteInfo{} - - if err := c.Bind(route); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - resultroute := models.RouteInfo{} - query := models.DB.Q() - query = query.Where("path = ?", route.Path) - err := query.First(&resultroute) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "status": err, - "Method": resultroute.Method, - "Path": resultroute.Path, - "ResourceName": resultroute.ResourceName, - })) -} diff --git a/mc_web_console_api/actions/_old/clustermng.go b/mc_web_console_api/actions/_old/clustermng.go deleted file mode 100644 index dd7762ce..00000000 --- a/mc_web_console_api/actions/_old/clustermng.go +++ /dev/null @@ -1,208 +0,0 @@ -package actions - -import ( - "log" - "mc_web_console_api/fwmodels/tumblebug/mcis" - "mc_web_console_api/handler" - "mc_web_console_api/util" - "net/http" - - "github.com/gobuffalo/buffalo" -) - -func ClusterList(c buffalo.Context) error { - namespaceID := c.Param("nsId") - - optionParam := c.Params().Get("option") - log.Println("=========clusterlist") - if optionParam == "id" { - clusterList, respStatus := handler.ClusterIDList(namespaceID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "ClusterList": clusterList, - })) - } else { - clusterList, respStatus := handler.ClusterList(namespaceID, optionParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "ClusterList": clusterList, - })) - } -} - -func ClusterReg(c buffalo.Context) error { - namespaceID := c.Param("nsId") - optionParam := c.Params().Get("option") - clusterReq := &mcis.TbClusterReq{} - if err := c.Bind(clusterReq); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - go handler.CreateCluster(namespaceID, optionParam, clusterReq) - // 원래는 호출 결과를 return하나 go routine으로 바꾸면서 요청성공으로 return - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -func DelCluster(c buffalo.Context) error { - namespaceID := c.Param("nsId") - clusterID := c.Param("clusterId") - - taskKey := namespaceID + "||" + "mcks" + "||" + clusterID - handler.StoreWebsocketMessage(util.TASK_TYPE_MCKS, taskKey, util.TUMBLEBUG, util.TASK_STATUS_REQUEST, c) // session에 작업내용 저장 - - go handler.DelCluster(namespaceID, clusterID) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -func RegNodeGroup(c buffalo.Context) error { - - namespaceID := c.Param("nsId") - - clusterName := c.Param("mcksName") - - nodeRegReq := &mcis.TbNodeGroupReq{} - if err := c.Bind(nodeRegReq); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - - nodeInfo, respStatus := handler.AddNodeGroup(namespaceID, clusterName, nodeRegReq) - log.Println("RegNode service returned") - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "NodeGroupInfo": nodeInfo, - })) -} - -// del all cluster -func DelAllCluster(c buffalo.Context) error { - namespaceID := c.Param("nsId") - matchParam := c.Params().Get("match") - - go handler.DelAllCluster(namespaceID, matchParam) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -// remove a nodegroup -func DelNodeGroup(c buffalo.Context) error { - - namespaceID := c.Param("nsId") - clusterID := c.Param("clusterId") - nodeGroupName := c.Param("nodeGroupName") - - resultStatusInfo, respStatus := handler.DelNodeGroup(namespaceID, clusterID, nodeGroupName) - log.Println("DelNodeGroup service returned") - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "StatusInfo": resultStatusInfo, - })) -} - -// change a nodegroup's autoscale size -func EditNodeGroupAutoscalesize(c buffalo.Context) error { - nameSpaceID := c.Param("nsId") - clusterID := c.Param("clusterId") - nodeGroupName := c.Param("nodeGroupName") - - resultNodegroupAutoscalesize, respStatus := handler.EditNodeGroupAutoscalesize(nameSpaceID, clusterID, nodeGroupName) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "StatusInfo": resultNodegroupAutoscalesize, - })) - -} - -// set a nodegrouop's autoscaling on/off - -func EditAutoscaling(c buffalo.Context) error { - nameSpaceID := c.Param("nsId") - clusterID := c.Param("clusterId") - nodeGroupName := c.Param("nodeGroupName") - - resultAutoscaling, respStatus := handler.EditAutoscaling(nameSpaceID, clusterID, nodeGroupName) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "StatusInfo": resultAutoscaling, - })) - -} - -// upgrage a cluster's version - -func EditClusterVersion(c buffalo.Context) error { - nameSpaceID := c.Param("nsId") - clusterID := c.Param("clusterId") - - resultClusterVersion, respStatus := handler.UpgradeClusterVersion(nameSpaceID, clusterID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "StatusInfo": resultClusterVersion, - })) - -} diff --git a/mc_web_console_api/actions/_old/connection.go b/mc_web_console_api/actions/_old/connection.go deleted file mode 100644 index 5c3c77a5..00000000 --- a/mc_web_console_api/actions/_old/connection.go +++ /dev/null @@ -1,1232 +0,0 @@ -package actions - -import ( - "context" - "fmt" - "log" - "net/http" - "strings" - - "github.com/davecgh/go-spew/spew" - "github.com/gobuffalo/buffalo" - "github.com/gobuffalo/pop/v6" - "github.com/pkg/errors" - - "mc_web_console_api/fwmodels" - "mc_web_console_api/fwmodels/spider" - "mc_web_console_api/fwmodels/tumblebug/mcis" - "mc_web_console_api/handler" - "mc_web_console_api/models" - "mc_web_console_api/models/views" -) - -// CloudConnectionAllList -// -// @Summary 모든 connection 조회 -// @Description [CloudConnectionAllList] 모든 connection을 조회합니다. -// @Tags debug -// @Accept json -// @Produce json -// @Success 200 {object} models.CloudConnections -// @Router /api/test/connection/list/ [GET] -func CloudConnectionAllList(c buffalo.Context) error { - cloudConnections := models.CloudConnections{} - err := models.DB.All(&cloudConnections) - - if err != nil { - return errors.WithStack(err) - } - - spew.Dump("context connection list", cloudConnections) - - ctx := context.WithValue(c, "connection_list", cloudConnections) - cd := ctx.Value("connection_list").(models.CloudConnections) - - spew.Dump("context connection list", cd) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "cloudConnectionList": cloudConnections, - })) -} - -// connection 목록 조회 -// -// @Summary CloudConnection 리스트 조회 -// @Description [CloudConnectionList] connection 리스트를 조회합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Param providerId query string true "providerId" -// @Param regionName query string true "regionName" -// @Param zoneName query string true "zoneName" -// @Success 200 {object} models.CloudConnections -// @Router /api/settings/connection/ [GET] -func CloudConnectionList(c buffalo.Context) error { - paramProviderId := c.Params().Get("providerId") - paramRegionName := c.Params().Get("regionName") - paramZoneName := c.Params().Get("zoneName") - - cloudConnections, err := handler.GetConnectionList(paramProviderId, paramRegionName, paramZoneName, c) - - if err != nil { - return errors.WithStack(err) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "ConnectionConfig": cloudConnections, - })) - -} - -// connection 단건 조회 -// -// @Summary connection 단건 조회 -// @Description [CloudConnectionGet] connection 단건 조회합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Param connectionId path string true "connectionId" -// @Success 200 {object} models.CloudConnections -// @Router /api/settings/connection/id/{connectionId}/ [GET] -func CloudConnectionGet(c buffalo.Context) error { - paramConnectionName := c.Param("connectionId") - - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ConnectionName = paramConnectionName - cloudConnection, err := handler.GetViewConnection(paramViewConnection) - if err != nil { - return errors.WithStack(err) - } - return c.Render(http.StatusOK, r.JSON(cloudConnection)) -} - -// driver 목록 조회 -// -// @Summary Driver 리스트 조회 -// @Description [DriverList] driver 리스트 조회합니다. -- swagger TEST 오류 확인함. -// @Tags connection -// @Accept json -// @Produce json -// @Success 200 {array} models.Driver -// @Router /api/settings/connection/driver/ [get] -func DriverList(c buffalo.Context) error { - drivers := []models.Driver{} - - paramDriver := &models.Driver{} - if err := c.Bind(paramDriver); err != nil { - return errors.WithStack(err) - } - - tx := c.Value("tx").(*pop.Connection) - err := tx.Eager().All(&drivers) - if err != nil { - return errors.WithStack(err) - } - - return c.Render(http.StatusOK, r.JSON(drivers)) -} - -// driver 삭제 -// -// @Summary Driver 삭제 -// @Description [DriverDelete] Driver를 삭제합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Param paramDriver body models.Driver true "models.Driver" -// @Success 200 {object} models.Driver -// @Router /api/settings/connection/driver/ [delete] -func DriverDelete(c buffalo.Context) error { - paramDriver := &models.Driver{} - if err := c.Bind(paramDriver); err != nil { - return errors.WithStack(err) - } - - tx := c.Value("tx").(*pop.Connection) - err := tx.Destroy(paramDriver) - - if err != nil { - return errors.WithStack(err) - } - - return c.Render(http.StatusOK, r.JSON("success")) -} - -// RegionAllList 전체목록 조회 -// -// @Summary Region 모든 리스트를 조회 -// @Description [RegionAllList] Region의 모든 리스트를 조회합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Success 200 {array} models.Region -// @Router /api/settings/connection/region/all [get] -func RegionAllList(c buffalo.Context) error { - regions := []models.Region{} - paramRegion := &models.Region{} - if err := c.Bind(paramRegion); err != nil { - return errors.WithStack(err) - } - query := models.DB - - err := query.All(®ions) - if err != nil { - return errors.WithStack(err) - } - return c.Render(http.StatusOK, r.JSON(regions)) -} - -// RegionDelete 삭제 -// -// @Summary Region 삭제 -// @Description [RegionDelete] Region을 삭제합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Param paramRegion body models.Region true "models.Region" -// @Success 200 {object} models.Driver -// @Router /api/settings/connection/region/ [delete] -func RegionDelete(c buffalo.Context) error { - paramRegion := &models.Region{} - if err := c.Bind(paramRegion); err != nil { - return errors.WithStack(err) - } - - tx := c.Value("tx").(*pop.Connection) - err := tx.Destroy(paramRegion) - - if err != nil { - return errors.WithStack(err) - } - - return c.Render(http.StatusOK, r.JSON("success")) -} - -// credential 삭제 -// -// @Summary Credential 삭제 -// @Description [CredentialDelete] Credential 삭제합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Param paramCredential body models.Credential true "models.Credential" -// @Success 200 {string} string "success" -// @Router /api/settings/connection/credential/ [delete] -func CredentialDelete(c buffalo.Context) error { - paramCredential := &models.Credential{} - if err := c.Bind(paramCredential); err != nil { - return errors.WithStack(err) - } - - tx := c.Value("tx").(*pop.Connection) - err := tx.Destroy(paramCredential) - - if err != nil { - return errors.WithStack(err) - } - - return c.Render(http.StatusOK, r.JSON("success")) -} - -// //////////////SPIDER 조회////////////////////////// -// SPIDER ConnectionList 목록조회 -// -// @Summary SPIDER ConnectionList 목록조회 -// @Description [SpiderConnectionList] SPIDER connection 리스트를 조회합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Success 200 {string} string {'message':'success','status':'respStatus','ConnectionConfig': 'cloudConnectionConfigList',} -// @Router /api/settings/connection/spider/ [GET] -func SpiderConnectionList(c buffalo.Context) error { - cloudConnectionConfigList, respStatus := handler.GetCloudConnectionConfigList() - if respStatus.StatusCode == 500 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "ConnectionConfig": cloudConnectionConfigList, - })) -} - -// SPIDER ConnectionGet 단건조회 -// -// @Summary SPIDER Connection 단건조회 -// @Description [SpiderConnectionGet] SPIDER connection 단건을 조회합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Param connectionId path string true "connectionId" -// @Success 200 {string} string {'message':'success','status':'respStatus','ConnectionConfig': 'connectionInfo',} -// @Router /api/settings/connection/spider/id/{connectionId}/ [GET] -func SpiderConnectionGet(c buffalo.Context) error { - paramConfigName := c.Param("connectionId") - - connectionInfo, respStatus := handler.GetCloudConnectionConfigData(paramConfigName) - - if respStatus.StatusCode == 500 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "ConnectionConfig": connectionInfo, - })) -} - -// ConnectionReg 등록 후 connection 목록조회 -// SpiderConnectionReg -> CloudConnectionCreate로 변경 -// -// @Summary CloudConnection 생성 -// @Description [CloudConnectionCreate] ConnectionReg 등록 후 connection 목록조회 -// @Description ---- SpiderConnectionReg -> CloudConnectionCreate로 변경 -// @Description ---- is_cb 가 아니면 connection 등록 후 db 저장하도록 보완할 것. -// @Description ---- TODO : SpiderCloudConnectionConfigReg 로 변경할 것 -// @Description ---- TODO : cloud_connections 저장 MconRegCloudConnection -> 저장실패시 생성한 connection 삭제하도록 -// @Description ---- TODO : cloud_connections table 조회하도록 변경할 것. : MconCloudConnectionList() -// @Description ---- TODO : SpiderCloudConnectionConfigList 로 변경할 것. -// @Tags connection -// @Accept json -// @Produce json -// @Param is_cb query string true "is_cb" -// @Success 200 {string} string {'message':'success','status':'respStatus','ConnectionConfig': 'connectionInfo',} -// @Router /api/settings/connection/ [post] -func CloudConnectionCreate(c buffalo.Context) error { - - is_cb := c.Params().Get("is_cb") - - connectionInfo := new(spider.CloudConnectionConfigInfo) - if err := c.Bind(connectionInfo); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - if is_cb == "N" { - // is_cb 가 아니면 connection 등록 후 db 저장하도록 보완할 것. - respBody, respStatus := handler.RegCloudConnectionConfig(connectionInfo) // TODO : SpiderCloudConnectionConfigReg 로 변경할 것 - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - fmt.Println("=============respBody =============", respBody) - - // TODO : cloud_connections 저장 MconRegCloudConnection -> 저장실패시 생성한 connection 삭제하도록 - - // 등록 후 목록 조회 - // TODO : cloud_connections table 조회하도록 변경할 것. : MconCloudConnectionList() - cloudConnectionList, cloudConnectionConfigErr := handler.GetCloudConnectionConfigList() // TODO : SpiderCloudConnectionConfigList 로 변경할 것. - if cloudConnectionConfigErr.StatusCode != 200 && cloudConnectionConfigErr.StatusCode != 201 { - return c.Render(cloudConnectionConfigErr.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "ConnectionConfig": cloudConnectionList, - })) - } - - respBody, respStatus := handler.RegCloudConnectionConfig(connectionInfo) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - fmt.Println("=============respBody =============", respBody) - - cloudConnectionList, cloudConnectionConfigErr := handler.GetCloudConnectionConfigList() - if cloudConnectionConfigErr.StatusCode != 200 && cloudConnectionConfigErr.StatusCode != 201 { - return c.Render(cloudConnectionConfigErr.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "ConnectionConfig": cloudConnectionList, - })) -} - -// ConnectionDelete 삭제 -// SpiderConnectionDelete -> CloudConnectionDel로 변경 -// -// @Summary Connection 삭제 -// @Description [CloudConnectionDelete] Connection을 삭제합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Param paramConfigName path string true "paramConfigName" -// @Param is_cb query string true "is_cb" -// @Success 200 {string} string "success" -// @Router /api/settings/connection/id/{configName}/ [delete] -func CloudConnectionDelete(c buffalo.Context) error { - is_cb := c.Params().Get("is_cb") - paramConfigName := c.Param("configName") - - respBody, respStatus := handler.DelCloudConnectionConfig(paramConfigName) - fmt.Println("=============respBody =============", respBody) - if respStatus.StatusCode == 500 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - if is_cb == "N" { - // TODO : DB(cloud_connections)에서 connection 삭제처리 - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - })) -} - -// SpiderConnectionMod -> CloudConnectionUpdate -// -// @Summary Cloud Connection을 업데이트 -- not implementated yet -// @Description [CloudConnectionUpdate] Cloud Connection을 수정합니다. -- not implementated yet -// @Tags connection -// @Accept json -// @Produce json -// @Success 200 {string} string "{'message': 'success','status': 'not implementated yet',}" -// @Router /api/settings/connection/ [PUT] -func CloudConnectionUpdate(c buffalo.Context) error { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "not implementated yet", - })) -} - -// SpiderDriverList default implementation. -// -// @Summary Spider Driver 리스트 조회 -// @Description [SpiderDriverList] Spider Driver 리스트를 조회합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Success 200 {string} string "{'message': 'success','status': 'respStatus','Driver': 'driverList',}" -// @Router /api/settings/connection/driver/spider/ [get] -func SpiderDriverList(c buffalo.Context) error { - driverList, respStatus := handler.GetDriverList() - if respStatus.StatusCode == 500 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "Driver": driverList, - })) -} - -// @Summary Driver 단건 조회 -// @Description [DriverGet] Driver를 단건 조회합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Param driver path string true "driver" -// @Param is_cb query string true "is_cb" -// @Success 200 {string} string "{'message': 'success','status': 'respStatus','Driver': 'driverInfo',}" -// @Router /api/settings/connection/driver/id/{driverId}/ [get] -func DriverGet(c buffalo.Context) error { - is_cb := c.Params().Get("is_cb") - paramDriver := c.Param("driver") - - if is_cb == "N" { - mconDriver, err := handler.MconDriverGet(c) - if err != nil { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": 500, - })) - } - - driverInfo := spider.DriverInfo{} - driverInfo.ProviderName = mconDriver.ProviderID - driverInfo.DriverName = mconDriver.DriverName - driverInfo.DriverLibFileName = mconDriver.LibFileName - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "Driver": driverInfo, - })) - - } - - driverInfo, respStatus := handler.SpiderDriverGet(paramDriver) // TODO : SpiderDriverGet - - if respStatus.StatusCode == 500 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "Driver": driverInfo, - })) -} - -// SpiderDriverForm default implementation. -// -// @Summary Driver 생성 -// @Description [DriverCreate] Driver를 생성합니다. -// @Description SpiderDriverReg 등록 -> DriverCreate 로 변경 /settings/connection/driver -// @Tags connection -// @Accept json -// @Produce json -// @Param paramdriverInfoDriver body spider.DriverInfo true "spider.DriverInfo" -// @Param is_cb query string true "is_cb" -// @Success 200 {json} {"message": "success","status": "respStatus",} -// @Failure 201 {json} {"error": respStatus.Message,"status": respStatus.StatusCode,} -// @Failure 500 {json} {"error": err.Error(),"status": 500,}" -// @Router /api/settings/connection/driver/ [post] -func DriverCreate(c buffalo.Context) error { - is_cb := c.Params().Get("is_cb") - - driverInfo := new(spider.DriverInfo) - err := c.Bind(driverInfo) - if err != nil { - return errors.WithStack(err) - } - - log.Println(driverInfo) - respBody, respStatus := handler.RegDriver(driverInfo) // TODO : SpiderDriverReg 로 변경할 것. - fmt.Println("=============respBody =============", respBody) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - if is_cb == "N" { - paramDriver := &models.Driver{} - paramDriver.Provider.ProviderID = driverInfo.ProviderName - paramDriver.DriverName = driverInfo.DriverName - paramDriver.LibFileName = driverInfo.DriverLibFileName - - //if err := c.Bind(paramDriver); err != nil { - // return errors.WithStack(err) - //} - - err := handler.MconDriverCreate(paramDriver, c) - if err != nil { - // TODO : 저장실패면 삭제 DelDriver 호출 추가 - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": 500, - })) - } - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - })) -} - -// SpiderDriverDelete 삭제 -// -// @Summary Spider Driver 삭제 -// @Description [SpiderDriverDelete] Spider Driver를 삭제합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Param driver path string true "driver" -// @Success 200 {string} string "{'message': 'success','status': 'respStatus'}" -// @Router /api/settings/connection/driver/spider/id/{driver}/ [delete] -func SpiderDriverDelete(c buffalo.Context) error { - paramDriver := c.Param("driver") - - respBody, respStatus := handler.DelDriver(paramDriver) - fmt.Println("=============respBody =============", respBody) - if respStatus.StatusCode == 500 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - })) -} - -// @Summary Credential 리스트 조회 -// @Description [CredentialList] Credential 리스트를 조회합니다. -// @Description SpiderCredentialList -> CredentialList 으로 변경 GET -// @Tags connection -// @Accept json -// @Produce json -// @Param is_cb query string true "is_cb" -// @Success 200 {json} {"message":"success","status":"200","Credential": credentialList,} -// @Failure 500 {json} {"error": err.Error(),"status": "500",} -// @Router /api/settings/connection/credential/ [get] -func CredentialList(c buffalo.Context) error { - is_cb := c.Params().Get("is_cb") - - if is_cb == "N" { - paramCredential := &models.Credential{} - if err := c.Bind(paramCredential); err != nil { - return errors.WithStack(err) - } - - credentialList, err := handler.MconCredentialList(paramCredential, c) - if err != nil { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - // TODO : credentialList 를 기존 사용하던 양식에 맞게 형태 변경 필요 - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "Credential": credentialList, - })) - } - - credentialList, respStatus := handler.GetCredentialList() - if respStatus.StatusCode == 500 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "Credential": credentialList, - })) -} - -// CredentialGet 단건조회 -// -// @Summary Credential 단건 조회 -// @Description [CredentialGet] Credential 단건 조회합니다 -// @Tags connection -// @Accept json -// @Produce json -// @Param credential path string true "iscredential_cb" -// @Param is_cb query string true "is_cb" -// @Success 200 {string} string "{'message':'success','status':'200','Credential': 'credentialInfo',}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/credential/id/{credential}/ [get] -func CredentialGet(c buffalo.Context) error { - is_cb := c.Params().Get("is_cb") - paramCredential := c.Param("credential") - - if is_cb == "N" { - paramCredential := &models.Credential{} - if err := c.Bind(paramCredential); err != nil { - return errors.WithStack(err) - } - credentialInfo, err := handler.MconCredentialGet(paramCredential) - if err != nil { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - // TODO : credentialInfo를 기존에 사용하던 형태로 변경 필요 - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "Credential": credentialInfo, - })) - } - - credentialInfo, respStatus := handler.GetCredentialData(paramCredential) - if respStatus.StatusCode == 500 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "Credential": credentialInfo, - })) -} - -// CredentialCreate 등록 -// -// @Summary Credential 생성 -// @Description [CredentialCreate] Credential을 생성합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Param credentialInfo body spider.CredentialInfo true "spider.CredentialInfo" -// @Success 200 {string} string "{'message':'success','status':'200',}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/credential/ [post] -func CredentialCreate(c buffalo.Context) error { - credentialInfo := new(spider.CredentialInfo) - err := c.Bind(credentialInfo) - if err != nil { - return errors.WithStack(err) - } - log.Println(credentialInfo) - respBody, respStatus := handler.RegCredential(credentialInfo) // TODO : SpiderCredentialCreate로 이름 변경할 것 - fmt.Println("=============respBody =============", respBody) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - is_cb := c.Params().Get("is_cb") - - if is_cb == "N" { - paramCredential := &models.Credential{} - if err := c.Bind(paramCredential); err != nil { - return errors.WithStack(err) - } - - err := handler.MconCredentialCreate(paramCredential, c) - if err != nil { - // TODO : 저장 실패면 spiderCredentialDel 로 지우는 것 추가할것. - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - })) -} - -// ProviderRegionList 목록 -// -// @Summary Region 리스트 조회 -// @Description [RegionList] Region 리스트를 조회합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Param is_cb query string true "is_cb" -// @Param filterKeyParam query string true "filterKeyParam" -// @Param filterValParam query string true "filterValParam" -// @Success 200 {string} string "{'message':'success','status':'200','Region':'regionList'}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/region/ [get] -func RegionList(c buffalo.Context) error { - is_cb := c.Params().Get("is_cb") - filterKeyParam := c.Params().Get("filterKey") - filterValParam := c.Params().Get("filterVal") - log.Println("filterKeyParam", filterKeyParam) - log.Println("filterValParam", filterValParam) - - if is_cb == "N" { - paramRegion := &models.Region{} - - if filterKeyParam == "providerId" { - paramRegion.ProviderID = filterValParam - } - // if err := c.Bind(paramRegion); err != nil { - // return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - // "error": err.Error(), - // "status": "500", - // })) - // } - regions, err := handler.MconRegionList(paramRegion, c) - if err != nil { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - - // 가져온 게 있으면 return 형태를 spider에서 가져온 형태와 맞춰주기 - // 가져온 게 있으면 return 형태를 spider에서 가져온 형태와 맞춰주기 - returnRegionList := []spider.RegionInfo{} - if len(regions) > 0 { - for _, region := range regions { - spiderRegionInfo := spider.RegionInfo{} - spKeyValueList := spider.SpKeyValueList{} - regionName := "" - for _, keyval := range region.RegionKeyValue { - spiderKeyValue := spider.SpKeyValueInfo{} - spiderKeyValue.Key = keyval.Key - spiderKeyValue.Value = keyval.Value - spKeyValueList = append(spKeyValueList, spiderKeyValue) - - if strings.ToLower(keyval.Key) == "region" || strings.ToLower(keyval.Key) == "location" { - regionName = keyval.Value - } - } - spiderRegionInfo.ProviderName = region.ProviderID - //spiderRegionInfo.RegionName = region.RegionName - spiderRegionInfo.RegionName = regionName - spiderRegionInfo.KeyValueInfoList = spKeyValueList - - returnRegionList = append(returnRegionList, spiderRegionInfo) - } - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "Region": returnRegionList, - })) - } - - //MconRegionList - regionList, respStatus := handler.GetRegionList() // TODO : SpiderRegionList 로 이름 변경 필요 - if respStatus.StatusCode == 500 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "Region": regionList, - })) -} - -// ProviderRegionList 목록 -// -// @Summary Region 단건 조회 -// @Description [RegionGet] Region 단건 조회합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Param paramRegion path string true "paramRegion" -// @Param is_cb query string true "is_cb" -// @Success 200 {string} string "{'message':'success','status':'respStatus','Region':'resionInfo'}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/region/id/{paramRegion}/ [get] -func RegionGet(c buffalo.Context) error { - is_cb := c.Params().Get("is_cb") - paramRegion := c.Param("region") - - if is_cb == "N" { - paramRegion := &models.Region{} - if err := c.Bind(paramRegion); err != nil { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - region, err := handler.MconRegionGet(paramRegion) - if err != nil { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - - // TODO : region 을 사용하는 형태로 추출 필요 - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "Region": region, - })) - } - - resionInfo, respStatus := handler.GetRegionData(paramRegion) // TODO : SpiderRegionGet 으로 변경할 것 - - if respStatus.StatusCode == 500 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "Region": resionInfo, - })) -} - -// @Summary Region 생성 -// @Description [RegionCreate] Region을 생성합니다. -// @Tags connection -// @Accept json -// @Produce json -// @Param regionInfo body spider.RegionInfo true "spider.RegionInfo" -// @Param is_cb query string true "is_cb" -// @Success 200 {string} string "{'message':'success','status':'200',}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/region/ [post] -func RegionCreate(c buffalo.Context) error { - is_cb := c.Params().Get("is_cb") - regionInfo := new(spider.RegionInfo) - err := c.Bind(regionInfo) - if err != nil { - return errors.WithStack(err) - } - log.Println(regionInfo) - respBody, respStatus := handler.RegRegion(regionInfo) // TODO : SpiderRegionReg 로 이름 변경할 것 - fmt.Println("=============respBody =============", respBody) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - if is_cb == "N" { - paramRegion := &models.Region{} - if err := c.Bind(paramRegion); err != nil { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - - err := handler.MconRegionCreate(paramRegion, c) - if err != nil { - // TODO : 저장 실패시 region 삭제 호출 필요 - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - })) -} - -// CloudProviderList 목록 -// -// @Summary Cloud Provider 리스트 조회 -// @Description [CloudProviderList] Cloud Provider 리스트를 조회합니다. -// @Description DB에서 가져오게 할 것인가? -// @Description SpiderProviderList 삭제 함 23.07.06 -// @Tags connection -// @Accept json -// @Produce json -// @Success 200 {string} string "{'message':'success','status':'respStatus','Region':'resionInfo'}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/providers/ [get] -func CloudProviderList(c buffalo.Context) error { - cloudOsList, respStatus := handler.GetCloudOSList() - if respStatus.StatusCode == 500 { - return c.Render(http.StatusOK, r.JSON(respStatus)) - } - - return c.Render(http.StatusOK, r.JSON(cloudOsList)) -} - -// 사용가능한 connection config 목록 조회 -// Check avaiable ConnectionConfig list for creating MCIS Dynamically -// -// @Summary 사용가능한 Cloud Connection 리스트 조회 -// @Description [AvailableCloudConnectionList] 사용가능한 Cloud Connection 목록을 조회합니다. Check avaiable ConnectionConfig list for creating MCIS Dynamically -// @Tags connection -// @Accept json -// @Produce json -// @Success 200 {string} string "{'message':'success','status':'respStatus'}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/available/ [get] -func AvailableCloudConnectionList(c buffalo.Context) error { - mcisReq := new(mcis.McisConnectionConfigCandidatesReq) - checkMcisDynamicReqInfo, respStatus := handler.GetMcisDynamicCheckList(mcisReq) - if respStatus.StatusCode == 500 { - return c.Render(http.StatusOK, r.JSON(respStatus)) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": respStatus.Message, - "status": respStatus.StatusCode, - "mcisDynamicInfo": checkMcisDynamicReqInfo, - })) -} - -// @Summary credential로 가능한 Connection 조회 -// @Description [TestCloudConnection] credential로 가능한 Connection 조회합니다. -// @Tags debug -// @Accept json -// @Produce json -// @Param credential body models.Credentials true "models.Credentials" -// @Success 200 {string} string "{'message':'success','status':'respStatus'}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/test/connection/list/bycred [post] -func TestCloudConnection(c buffalo.Context) error { - tx := c.Value("tx").(*pop.Connection) - credential := &models.Credentials{} - err := tx.Eager().All(credential) - spew.Dump("======credential=======") - spew.Dump(credential) - spew.Dump("======credential=======") - - if err != nil { - return err - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -// CB 조회내역을 DB 에 저장 -// -// @Summary CloudProvider 동기화 -// @Description [SyncCloudProvider] CB 조회내역을 DB 에 저장합니다. CloudProvider 동기화[handler.SyncCloudProvider(c)] -// @Tags connection -// @Accept json -// @Produce json -// @Success 200 {string} string "{'message':'success','status':'respStatus'}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/provider/sync/ [get] -func SyncCloudProvider(c buffalo.Context) error { - err := handler.SyncCloudProvider(c) - if err != nil { - return err - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -// @Summary Driver 동기화 -// @Description [SyncDriver] CB 조회내역을 DB 에 저장합니다. Driver 동기화[handler.SyncDriver(c)] -// @Tags connection -// @Accept json -// @Produce json -// @Success 200 {string} string "{'message':'success','status':'respStatus'}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/driver/sync/ [get] -func SyncDriver(c buffalo.Context) error { - err := handler.SyncDriver(c) - if err != nil { - return err - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -// @Summary Region 동기화 -// @Description [SyncRegion] CB 조회내역을 DB 에 저장합니다. Region 동기화[handler.SyncRegion(c)] -// @Tags connection -// @Accept json -// @Produce json -// @Success 200 {string} string "{'message':'success','status':'respStatus'}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/region/sync/ [get] -func SyncRegion(c buffalo.Context) error { - err := handler.SyncRegion(c) - if err != nil { - return err - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -// @Summary Credential 동기화 -// @Description [SyncCredential] CB 조회내역을 DB 에 저장합니다. Credential 동기화[handler.SyncCredential(c)] -// @Tags connection -// @Accept json -// @Produce json -// @Success 200 {string} string "{'message':'success','status':'respStatus'}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/credential/sync/ [get] -func SyncCredential(c buffalo.Context) error { - err := handler.SyncCredential(c) - if err != nil { - return err - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -// @Summary Connection 동기화 -// @Description [SyncConnection] CB 조회내역을 DB 에 저장합니다. Connection 동기화[handler.SyncConnection(c)] -// @Tags connection -// @Accept json -// @Produce json -// @Success 200 {string} string "{'message':'success','status':'respStatus'}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/sync/ [get] -func SyncConnection(c buffalo.Context) error { - err := handler.SyncConnection(c) - if err != nil { - return err - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -// @Summary credential 별 지정 Provider 모든 region 생성 -// @Description [GenerateConnectionsByCredential] credential 별로 지정 Provider의 모든 region에 대해 connection 생성. -// @Tags connection -// @Accept json -// @Produce json -// @Param providerId query string true "providerId" -// @Param credentialName query string true "credentialName" -// @Success 200 {string} string "{'message':'success','status':'respStatus'}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/generate/bycredential [get] -func GenerateConnectionsByCredential(c buffalo.Context) error { - paramProviderID := c.Params().Get("providerId") - paramCredentialName := c.Params().Get("credentialName") - - log.Println(c.Params()) - log.Println("paramProviderID ", paramProviderID) - log.Println("paramCredentialName ", paramCredentialName) - err := handler.GenerateConnectionsByCredential(paramProviderID, paramCredentialName, c) - if err != nil { - return err - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -// @Summary credential 별 모든 region connection 생성 -// @Description [GenerateConnectionsByAllCredential] credential 별로 지정 Provider의 모든 region에 대해 connection 생성. -// @Description - 모든 credential에 대해 connection 생성 genconnection -// @Description - handler.GetCredentialList() -// @Description - (현재 설정된 credential 목록 : 목록에서는 key의 value는 ...으로 표시) -// @Tags connection -// @Accept json -// @Produce json -// @Success 200 {string} string "{'message':'success','status':'respStatus'}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/generate/all/bycredential [get] -func GenerateConnectionsByAllCredential(c buffalo.Context) error { - - credentialList, respStatus := handler.GetCredentialList() - if respStatus.StatusCode == 500 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - for _, credential := range credentialList { - - err := handler.GenerateConnectionsByCredential(credential.ProviderName, credential.CredentialName, c) - if err != nil { - log.Println("credential", credential) - log.Println("Connection Create failed", err) - } - break - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -// @Summary Framework Health Check -// @Description [FrameworkHealthCheck] 프레임워크 헬스체크 -// @Description - c.Params().Get("framework") -// @Description - DF의 response 에서 return결과가 ""으로 들어와 204를 return 함. -// @Description - DF에서 정상적인 message 보내라고 할 것. -// @Tags connection -// @Accept json -// @Produce json -// @Success 200 {string} string "{'message':'success','status':'respStatus'}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/healthcheck/framework/ [get] -func FrameworkHealthCheck(c buffalo.Context) error { - framework := c.Params().Get("framework") - - respStatus := fwmodels.WebStatus{} - - if strings.EqualFold(framework, "SPIDER") { - respStatus = handler.GetSpiderHealthCheck() - } else if strings.EqualFold(framework, "TUMBLEBUG") { - respStatus = handler.GetTumblebugHealthCheck() - } else if strings.EqualFold(framework, "LADYBUG") { - } else if strings.EqualFold(framework, "DRAGONFLY") { - respStatus = handler.GetDragonflyHealthCheck() - } - - // DF의 response 에서 return결과가 ""으로 들어와 204를 return 함. -> DF에서 정상적인 message 보내라고 할 것. - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 && respStatus.StatusCode != 204 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": framework + respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": framework + " success", - "status": respStatus.StatusCode, - })) -} - -// MCIS 또는 VM 에 agent 상태 확인 -// -// @Summary Agent Health Check -- TODO -// @Description [AgentHealthCheck] MCIS 또는 VM 에 agent 상태 확인 -// @Tags connection -// @Accept json -// @Produce json -// @Success 200 {string} string "{'message':'success','status':'respStatus'}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/connection/healthcheck/agent/ [get] -func AgentHealthCheck(c buffalo.Context) error { - // MCIS / MCKS - - //namespaceID := c.Session().Get("current_namespace_id").(string) - - //serviceType := c.Param("serviceType") - //serviceId := c.Param("serviceId") - //log.Println("mcisId= " + mcisID) - //optionParam := c.Params().Get("option") - serviceType := c.Params().Get("serviceType") - //serviceId := c.Params().Get("serviceId") - - //TB: benchmark agent, DF :monitoring agent(port:8888) - - //handler.GetAgentStatus(namespaceID, serviceType, serviceId) - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": serviceType + " success", - "status": "200", - })) -} diff --git a/mc_web_console_api/actions/_old/customMiddleware.go b/mc_web_console_api/actions/_old/customMiddleware.go deleted file mode 100644 index 5c8312f8..00000000 --- a/mc_web_console_api/actions/_old/customMiddleware.go +++ /dev/null @@ -1,236 +0,0 @@ -package actions - -import ( - "log" - "strings" - - "github.com/gobuffalo/buffalo" - "github.com/gofrs/uuid" - - "github.com/pkg/errors" - - _ "mc_web_console_api/docs" //mcone의 경우 - "mc_web_console_api/handler" -) - -/* - app.go 에서 사용하는 미들웨어를 따로 모아놓음. - middleware moved to middleware.go - 2023-06-28 -*/ - -// 경로에 따른 middle ware 설정 -// "/" 는 루트이므로 skip -// "/user/new" 신규 사용자용으로 skip -// "/signin/", "/logout/" 로그인용으로 skip -// "/api" 는 SetCurrentUser skip. (공유 ns 목록조회로 화면에 표시하는 용도임.) -func SkipMiddlewareByRoutePath(next buffalo.Handler) buffalo.Handler { - return func(c buffalo.Context) error { - log.Println("RouteMiddleware ***************", c.Request().URL.Path) - if c.Request().URL.Path == "/" { - log.Println("this path is root ", c.Request().URL.Path) - return next(c) - } - - if c.Request().URL.Path == "/users/new/" || c.Request().URL.Path == "/auth/signin/mngform/" || c.Request().URL.Path == "/api/auth/logout/" { - //if c.Request().URL.Path == "/main/" || c.Request().URL.Path == "/users/new/" || c.Request().URL.Path == "/signin/" || c.Request().URL.Path == "/logout/" { - log.Println("this path skips auth ", c.Request().URL.Path) - return next(c) - } - - // '/api'로 시작하는 경로에 대해 SetCurrentUser 미들웨어를 건너뛰도록 설정합니다. - if strings.HasPrefix(c.Request().URL.Path, "/api/") { - log.Println("this path for api ", c.Request().URL.Path) - return next(c) - } - - if strings.HasPrefix(c.Request().URL.Path, "/ws/") { - log.Println("this path for websocket ", c.Request().URL.Path) - return next(c) - } - - if strings.HasPrefix(c.Request().URL.Path, "/route/") { - log.Println("this path for router ", c.Request().URL.Path) - return next(c) - } - - // 세션이 없으면 로그인화면으로 - if uid := c.Session().Get("current_user_id"); uid == nil { - - c.Session().Set("redirectURL", c.Request().URL.String()) - err := c.Session().Save() - if err != nil { - log.Println("Authorize session err ", err) - return errors.WithStack(err) - } - - c.Flash().Add("danger", "You must be authorized to see that page") - log.Println("Flash().Add ~~~~~~ c.Redirect") - //return c.Redirect(302, "/signin/mngform/") - //return c.Redirect(302, "/auth/signin/mngform/") - // return RedirectTool(c, "authNewFormPath") - } - - return SetCurrentUser(next)(c) - } -} - -// provider를 미들웨어로 만들어서 세션에 저장하고 -// html tempalte에서 사용할 수 있게 만들자. -func SetCloudProviderList(next buffalo.Handler) buffalo.Handler { - return func(c buffalo.Context) error { - log.Println("SetCloudProviderList ~~~~") - if cloudOsList := c.Session().Get("cloud_os_list"); cloudOsList == nil { // 존재하지 않으면 조회 - cloudOsList, respStatus := handler.GetCloudOSList() - if respStatus.StatusCode == 500 { - return next(c) - } - c.Session().Set("cloud_os_list", cloudOsList) - c.Set("cloud_os_list", cloudOsList) - log.Println("##########cloud_os_list###########") - log.Println(cloudOsList) - log.Println("#########cloud_os_list############") - err := c.Session().Save() - if err != nil { - return errors.WithStack(err) - } - } else { - log.Println("Reuse cloudOsList *** ") - c.Set("cloud_os_list", cloudOsList) // 화면에서 cloud_os_list 사용을 위해 - } - - return next(c) - } -} - -// SetCurrentUser attempts to find a user based on the current_user_id -// in the session. If one is found it is set on the context. -func SetCurrentUser(next buffalo.Handler) buffalo.Handler { - return func(c buffalo.Context) error { - log.Println("SetCurrentUser~~~~~~~~~~~~~~~~~~~") - // uid := c.Session().Get("current_user_id") - // if uid == nil { - // c.Session().Clear() - // spew.Dump("session current_user_id error uid is nil ") - // return c.Redirect(302, "/signin") - // } - - // u := &models.User{} - // tx := c.Value("tx").(*pop.Connection) - // err := tx.Find(u, uid) - // if err != nil { - // c.Session().Clear() - // spew.Dump("user Find error : ", &err) - // return c.Redirect(302, "/signin") - // } - - if uid := c.Session().Get("current_user_id"); uid != nil { - // u := &models.User{} - // tx := c.Value("tx").(*pop.Connection) - // err := tx.Find(u, uid) - // if err != nil { - // c.Session().Clear() - // spew.Dump("user Find error : ", &err) - // return c.Redirect(302, "/") - // //return errors.WithStack(err) - // } - u, _ := handler.GetUserById(uid.(uuid.UUID)) - - if current_namespace_id := c.Session().Get("current_namespace_id"); current_namespace_id == nil { - ns, _ := handler.GetNamespaceById(u.DefaultNamespace) - c.Set("current_namespace", ns.NsName) - c.Set("current_namespace_id", ns.ID) - - } else { - current_namespace := c.Session().Get("current_namespace") - c.Set("current_namespace", current_namespace) - c.Set("current_namespace_id", current_namespace_id) - - } - - //shared_ns_list := GetSharedNamespaceList(u.ID, tx) - sharedNamespaceList, err := handler.SharedNamespaceList(u.ID) - if err != nil { - log.Println("err ", err) - } - - //c.Session().Set("shared_ns_list", shared_ns_list) - - c.Set("shared_ns_list", sharedNamespaceList) - c.Set("current_user", u) - c.Set("current_user_id", u.Email) - c.Set("current_user_level", u.UserLevel) - c.Set("current_credential", u.DefaultCredential) - log.Println("shared_ns_list length ", sharedNamespaceList) - } - - // Menu Tree - menutree, respStatus := handler.MenuTree() - log.Print(respStatus) - //menutree, respStatus := handler.MenuTree() - //if respStatus.StatusCode == 500 { - // return c.Redirect(302, "/") - //} - c.Set("menutree", menutree) - - //log.Println("menutree length ", len(*menutree)) - log.Println("menutree ", menutree) - //for _, item := range *menutree { - // log.Println("menutree ", item) - //} - - return next(c) - } -} - -// func CheckAdmin(next buffalo.Handler) buffalo.Handler { -// return func(c buffalo.Context) error { -// if admin := c.Session().Get("current_user_level"); admin != "admin" { -// c.Flash().Add("danger", "You must be authorized to see that page") -// //return c.Redirect(302, "/") -// return RedirectTool(c, "homeFormPath") -// } -// return next(c) -// } -// } - -// // Authorize require a user be logged in before accessing a route -// func Authorize(next buffalo.Handler) buffalo.Handler { -// return func(c buffalo.Context) error { -// log.Println("Authorize ~~~~") -// if uid := c.Session().Get("current_user_id"); uid == nil { - -// if c.Request().URL.Path == "/auth/signin/mngform/" { -// next(c) -// } - -// c.Session().Set("redirectURL", c.Request().URL.String()) -// err := c.Session().Save() -// if err != nil { -// log.Println("Authorize session err ", err) -// return errors.WithStack(err) -// } - -// c.Flash().Add("danger", "You must be authorized to see that page") -// log.Println("Flash().Add ~~~~~~ c.Redirect") -// //return c.Redirect(302, "/auth/signin/mngform/") -// return RedirectTool(c, "authNewFormPath") - -// } -// return next(c) -// } -// } - -// func SkipMiddleware(next buffalo.Handler) buffalo.Handler { -// return func(c buffalo.Context) error { - -// // 특정 경로와 하위 경로를 건너뛰고자 하는 조건을 체크합니다. -// if strings.HasPrefix(c.Request().URL.Path, "/api/") { -// log.Println("c.RequestURL.Path ", c.Request().URL.Path) -// // 건너뛰고자 하는 경우에는 다음 미들웨어나 핸들러를 호출하지 않고 종료합니다. -// return nil -// } - -// return next(c) -// } -// } diff --git a/mc_web_console_api/actions/_old/datadisk.go b/mc_web_console_api/actions/_old/datadisk.go deleted file mode 100644 index 3b996c65..00000000 --- a/mc_web_console_api/actions/_old/datadisk.go +++ /dev/null @@ -1,448 +0,0 @@ -package actions - -import ( - //"log" - //"mc_web_console_api/handler" - //"mc_web_console_api/models" - //"mc_web_console_api/models/views" - - "log" - "mc_web_console_api/handler" - "mc_web_console_api/models" - "mc_web_console_api/models/views" - "net/http" - - tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - "mc_web_console_api/fwmodels/webconsole" - - "github.com/gobuffalo/buffalo" - "github.com/gofrs/uuid" -) - -// @Summary DataDisk 생성 -// @Description [DataDiskReg] Data Disk를 생성합니다. -// @Tags datadisk -// @Accept json -// @Produce json -// @Param dataDiskRegInfo body mcir.TbDataDiskReq true "tbmcir.TbDataDiskReq" -// @Success 200 {string} string "{'message':'success','status':'200',}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/resources/datadisk/ [post] -func DataDiskReg(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - dataDiskRegInfo := &tbmcir.TbDataDiskReq{} - if err := c.Bind(dataDiskRegInfo); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - // connection 조회 : namespace와 무관 . 얘도 bind 써도 되나? - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ProviderID = dataDiskRegInfo.ProviderID - paramViewConnection.RegionName = dataDiskRegInfo.RegionName - paramViewConnection.ZoneName = dataDiskRegInfo.ZoneName - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - - // 사용할 connection set - dataDiskRegInfo.ConnectionName = viewConnection.ConnectionName - - // TB 등록 - resultDataDiskInfo, respStatus := handler.RegDataDisk(namespaceID, dataDiskRegInfo) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - // DB 등록 - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.Status = "C" - connectionMapping.ResourceType = "datadisk" - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - connectionMapping.ResourceID = resultDataDiskInfo.ID - connectionMapping.ResourceName = resultDataDiskInfo.Name - connectionMapping.CloudConnectionID = viewConnection.ID - connectionMapping.CredentialID = viewConnection.CredentialID - err = handler.SaveConnectionMapping(connectionMapping, c) - if err != nil { - // 실패시 생성한 Resource 제거 - _, respStatus := handler.DelDataDisk(namespaceID, resultDataDiskInfo.ID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(500, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DataDiskInfo": resultDataDiskInfo, - })) -} - -// @Summary Data Disk CRD 한번에 -// @Description [DataDiskMng] Data Disk Mng(CRD) 합니다. -// @Description Create, Update, Delete가 한번에 일어나는 경우 사용 -// @Description ex) table에 addRow로 추가하고 delet로 삭제한 것들을 한번에 저장할 때. -// @Tags datadisk -// @Accept json -// @Produce json -// @Param dataDiskRegInfo body webtool.DataDiskMngReq true "webtool.DataDiskMngReq" -// @Success 200 {string} string "{'message':'success','status':'200',}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/resources/datadisk/mngdata/ [post] -func DataDiskMng(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - log.Println("DataDiskMng in") - dataDiskRegInfo := &webconsole.DataDiskMngReq{} - if err := c.Bind(dataDiskRegInfo); err != nil { - log.Println("DataDiskMng err ", err) - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - mcisID := c.Params().Get("mcisId") - vmID := c.Params().Get("vmId") - - changedResourceCount := 0 - - // create data disk list - if dataDiskRegInfo.CreateDataDiskList != nil { - for _, createDataDisk := range dataDiskRegInfo.CreateDataDiskList { - // 생성 후 attach 할 vm이 있으면 attach 한다. - // disk생성의 경우 delay가 충분히 있어야 한다. - go handler.AsyncRegDataDisk(namespaceID, &createDataDisk, c) - changedResourceCount++ - } - - } - - // detach data disk list - if dataDiskRegInfo.DetachDataDiskList != nil { - if mcisID != "" && vmID != "" { - for _, detachDataDisk := range dataDiskRegInfo.DetachDataDiskList { - - // 2. vm에서 detach. optionParam 의 기본값은 attach임. detach라고 하는 항목만 삭제 됨. - optionParam := "detach" - attachDetachDataDiskReq := new(tbmcir.TbAttachDetachDataDiskReq) - attachDetachDataDiskReq.DataDiskId = detachDataDisk - - go handler.AsyncAttachDetachDataDiskToVM(namespaceID, mcisID, vmID, optionParam, attachDetachDataDiskReq, c) - changedResourceCount++ - } - } - } - - // attach data disk list - if dataDiskRegInfo.AttachDataDiskList != nil { - if mcisID != "" && vmID != "" { - for _, attachDataDisk := range dataDiskRegInfo.AttachDataDiskList { - optionParam := "attach" - attachDetachDataDiskReq := new(tbmcir.TbAttachDetachDataDiskReq) - attachDetachDataDiskReq.DataDiskId = attachDataDisk - go handler.AsyncAttachDetachDataDiskToVM(namespaceID, mcisID, vmID, optionParam, attachDetachDataDiskReq, c) - changedResourceCount++ - } - } - } - - // delete data disk list - if dataDiskRegInfo.DeleteDataDiskList != nil { - for _, delDataDisk := range dataDiskRegInfo.DeleteDataDiskList { - go handler.AsyncDelDataDisk(namespaceID, delDataDisk, c) - changedResourceCount++ - } - } - - if changedResourceCount == 0 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "failed. No data has been changed.", - "status": 500, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -// @Summary Data Disk List 조회 -// @Description [DataDiskList] Data Disk List를 조회합니다. -// @Tags datadisk -// @Accept json -// @Produce json -// @Param option query string true "option" -// @Param filterKey query string true "filterKey" -// @Param filterVal query string true "filterVal" -// @Success 200 {string} string "{'message':'success','status':'200','defaultNameSpaceID': namespaceID,'status': respStatus.StatusCode,}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/resources/datadisk/ [get] -func DataDiskList(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - optionParam := c.Params().Get("option") - filterKeyParam := c.Params().Get("filterKey") - filterValParam := c.Params().Get("filterVal") - - if optionParam == "id" { - dataDiskInfoList, respStatus := handler.GetDataDiskListByID(namespaceID, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "defaultNameSpaceID": namespaceID, - "dataDiskInfoList": dataDiskInfoList, - })) - } else { - dataDiskInfoList, respStatus := handler.GetDataDiskListByOption(namespaceID, optionParam, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "defaultNameSpaceID": namespaceID, - "dataDiskInfoList": dataDiskInfoList, - })) - } -} - -// @Summary Data Disk List 조회 (connection) -// @Description [DataDiskListByRegion] Data Disk List를 connection으로 조회합니다. -// @Description 해당리전에 등록 된 DataDisk 목록. connection 필요 -// @Description UI 에서 용이하게 쓰기 위함 (콤보 선택용) -// @Tags datadisk -// @Accept json -// @Produce json -// @Param option query string true "option" -// @Param filterValParam query string true "connectionName" -// @Success 200 {string} string "{'message':'success','status':'200','defaultNameSpaceID': namespaceID,'dataDiskInfoList': dataDiskInfoList,}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/resources/datadisk/region/ [get] -func DataDiskListByRegion(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - optionParam := c.Params().Get("option") - filterKeyParam := "connectionName" - filterValParam := c.Params().Get("connectionName") - - dataDiskInfoList, respStatus := handler.GetDataDiskListByOption(namespaceID, optionParam, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "defaultNameSpaceID": namespaceID, - "dataDiskInfoList": dataDiskInfoList, - })) -} - -// @Summary Data Disk 단건 조회 -// @Description [DataDiskGet] Data Disk를 dataDiskId로 조회합니다. -// @Tags datadisk -// @Accept json -// @Produce json -// @Param dataDiskId path string true "dataDiskId" -// @Success 200 {string} string "{'message':'success','status':'200','dataDiskInfo': dataDiskInfo}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/resources/datadisk/id/{dataDiskId}/ [get] -func DataDiskGet(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - paramDataDiskId := c.Param("dataDiskId") - - dataDiskInfo, respStatus := handler.DataDiskGet(namespaceID, paramDataDiskId) - - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ConnectionName = dataDiskInfo.ConnectionName - viewConnection, err := handler.GetViewConnection(paramViewConnection) - if err != nil { - // cb에서 정보는 가져왔으니 오류로 뱉지는 않기. - } else { - dataDiskInfo.ProviderID = viewConnection.ProviderID - dataDiskInfo.RegionName = viewConnection.RegionName - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "dataDiskInfo": dataDiskInfo, - })) -} - -// @Summary Data Disk 변경 -// @Description [DataDiskPut] Data Disk를 변경합니다. -// @Tags datadisk -// @Accept json -// @Produce json -// @Param dataDiskId path string true "dataDiskId" -// @Param dataDiskUpsizeReq body mcir.TbDataDiskUpsizeReq true "tbmcir.TbDataDiskUpsizeReq" -// @Success 200 {string} string "{'message':'success','status':'200','DataDiskInfo': DataDiskInfo}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/resources/datadisk/id/{dataDiskId}/ [put] -func DataDiskPut(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - paramDataDiskyId := c.Param("dataDiskId") - dataDiskUpsizeReq := &tbmcir.TbDataDiskUpsizeReq{} - if err := c.Bind(dataDiskUpsizeReq); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - resultDataDiskInfo, respStatus := handler.DataDiskPut(namespaceID, paramDataDiskyId, dataDiskUpsizeReq) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DataDiskInfo": resultDataDiskInfo, - })) -} - -// @Summary Data Disk 삭제 -// @Description [DataDiskDel] Data Disk를 삭제합니다. -// @Tags datadisk -// @Accept json -// @Produce json -// @Param dataDiskId path string true "dataDiskId" -// @Success 200 {string} string "{'message':'success','status':'200'}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/resources/datadisk/id/{dataDiskId}/ [DELETE] -func DataDiskDel(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - paramDataDiskId := c.Param("dataDiskId") - - respMessage, respStatus := handler.DelDataDisk(namespaceID, paramDataDiskId) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - // DB 등록 : mapping에 D로 저장할 때 사용된 connection 정보가 필요하여 조회 - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.ResourceType = "datadisk" - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - connectionMapping.ResourceID = paramDataDiskId - - usedConnectionMapping, err := handler.GetUsedConnection(connectionMapping) - if err != nil { - // TODO : mapping table에 없을 때, 에러로 처리할 것인가? - // return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - // "error": respStatus.Message, - // "status": respStatus.StatusCode, - // })) - } else { - // 삭제 Row 추가 - usedConnectionMapping.Status = "D" - usedConnectionMapping.ID = uuid.UUID{} - err = handler.SaveConnectionMapping(usedConnectionMapping, c) - if err != nil { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": respMessage.Message, - "status": respMessage.StatusCode, - })) -} - -// @Summary Available Data Disk List 조회 -// @Description [AvailableDataDiskTypeList] Provider, Region에서 사용가능한 DiskType 조회(DiskLookup) -// @Description spider의 cloudos_meta.yaml 참조 -// @Tags datadisk -// @Accept json -// @Produce json -// @Param providerId query string true "providerId" -// @Param regionName query string true "regionName" -// @Success 200 {string} string "{'message':'success','status':'200','DiskInfoList':availableDiskTypeList}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/resources/datadisk/lookup/ [get] -func AvailableDataDiskTypeList(c buffalo.Context) error { - //namespaceID := c.Session().Get("current_namespace_id").(string) - - paramProviderID := c.Params().Get("providerId") - paramRegionName := c.Params().Get("regionName") - - availableDiskTypeList, err := handler.AvailableDiskTypeByProviderRegion(paramProviderID, paramRegionName) - if err != nil { - - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "success", - "DiskInfoList": availableDiskTypeList, - })) -} - -// @Summary Mcis Vm Available Data Disk List 조회 -// @Description [McisVmAvailableDataDiskList] VM 이사용가능한 DataDisk Id 목록 조회 -// @Tags datadisk -// @Accept json -// @Produce json -// @Param mcisId query string true "mcisId" -// @Param vmID query string true "vmID" -// @Success 200 {string} string "{'message':'success','status':'200','dataDiskInfoList':dataDiskInfoList}" -// @Failure 500 {string} string "{'error': err.Error(),'status': '500',}" -// @Router /api/settings/resources/datadisk/availabledisk/ [get] -func McisVmAvailableDataDiskList(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisID := c.Params().Get("mcisId") - vmID := c.Params().Get("vmId") - - //nameSpaceID string, mcisID string, vmID string - dataDiskList, respStatus := handler.GetAvailableDataDiskListForVM(namespaceID, mcisID, vmID) - log.Println("GetAvailableDataDiskListForVM result") - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - "dataDiskInfoList": dataDiskList, - })) - -} diff --git a/mc_web_console_api/actions/_old/globaldashboard.go b/mc_web_console_api/actions/_old/globaldashboard.go deleted file mode 100644 index 0f3a37f3..00000000 --- a/mc_web_console_api/actions/_old/globaldashboard.go +++ /dev/null @@ -1 +0,0 @@ -package actions diff --git a/mc_web_console_api/actions/_old/home.go b/mc_web_console_api/actions/_old/home.go deleted file mode 100644 index aa5ed4ed..00000000 --- a/mc_web_console_api/actions/_old/home.go +++ /dev/null @@ -1,52 +0,0 @@ -package actions - -import ( - "log" - "net/http" - - "github.com/gobuffalo/buffalo" -) - -// func HomeForm(c buffalo.Context) error { -// return RedirectTool(c, "mainFormPath") -// } - -// @Summary 경로정보 -// @Description [RouteList] 경로정보를 반환 합니다. -// @Tags debug -// @Produce html -// @Success 200 {string} string "{'message':'success','status':'200', 'routes': app.Routes()}" -// @Router /api/test/routelist/ [get] -func RouteList(c buffalo.Context) error { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "routes": app.Routes(), - })) -} - -// 특정 help의 route정보 return -func GetRoute(c buffalo.Context) error { - // Get the route name from the UI - helperName := c.Param("helper") - - // Get the path of the specific route by name - //routePath := app.RoutePath(helperName) - - routes := app.Routes() - for _, route := range routes { - if route.PathName == helperName { - log.Println(route) - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "route": route, - })) - } - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "Path not found", - "status": "301", - })) -} diff --git a/mc_web_console_api/actions/_old/mcismng.go b/mc_web_console_api/actions/_old/mcismng.go deleted file mode 100644 index f844d534..00000000 --- a/mc_web_console_api/actions/_old/mcismng.go +++ /dev/null @@ -1,652 +0,0 @@ -package actions - -import ( - "fmt" - "log" - "mc_web_console_api/fwmodels/dragonfly" - tbmcis "mc_web_console_api/fwmodels/tumblebug/mcis" - "mc_web_console_api/fwmodels/webconsole" - "mc_web_console_api/handler" - "mc_web_console_api/models/views" - "mc_web_console_api/util" - "net/http" - "strings" - - "github.com/gobuffalo/buffalo" -) - -// McismngList 목록조회 -func McisList(c buffalo.Context) error { - - // namespace - // namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceID := c.Params().Get("namespaceid") - optionParam := c.Params().Get("option") - filterKeyParam := c.Params().Get("filterKey") - filterValParam := c.Params().Get("filterVal") - if optionParam == "id" { - mcisIdList, respStatus := handler.GetMcisListByID(namespaceID, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "McisList": mcisIdList, - })) - } else { - mcisList, respStatus := handler.GetMcisListByOption(namespaceID, optionParam, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - providerID := c.Params().Get("providerId") - connectionName := c.Params().Get("connection") - vnetID := c.Params().Get("vnet") - subGroupID := c.Params().Get("subgroup") - returnMcisList := []tbmcis.TbMcisInfo{} - if providerID != "" || connectionName != "" || vnetID != "" || subGroupID != "" { - for _, mcis := range mcisList { - vmList := mcis.Vm - - returnVmList := []tbmcis.TbVmInfo{} - fmt.Println(returnVmList) - for _, vm := range vmList { - - if connectionName != "" && connectionName != vm.ConnectionName { - continue - } - - if vnetID != "" && vnetID != vm.VNetID { - continue - } - - if subGroupID != "" && subGroupID != vm.SubGroupID { - continue - } - returnVmList = append(returnVmList, vm) - } - - if len(returnVmList) == 0 { - continue - } - - mcis.Vm = returnVmList - returnMcisList = append(returnMcisList, mcis) - } - } else { - returnMcisList = mcisList - } - log.Println(" mcisList return ", returnMcisList) - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "McisList": returnMcisList, - })) - } -} - -// McismngGet 단건조회 -func McisGet(c buffalo.Context) error { - //namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceID := c.Param("nsid") - mcisID := c.Param("mcisid") - log.Println("mcisId= " + mcisID) - optionParam := c.Params().Get("option") - - log.Println("optionParam= " + optionParam) - - if optionParam == "id" { - resultMcisInfo, _ := handler.GetMcisDataByID(namespaceID, mcisID) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - "McisInfo": resultMcisInfo, - })) - - } else if optionParam == "status" { - resultMcisStatusInfo, _ := handler.GetMcisDataByStatus(namespaceID, mcisID, optionParam) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - "McisStatusInfo": resultMcisStatusInfo, - })) - } - - resultMcisInfo, _ := handler.GetMcisData(namespaceID, mcisID) - - providerIdParam := c.Params().Get("providerId") - if providerIdParam != "" { - - } - - connectionNameParam := c.Params().Get("connection") - if connectionNameParam != "" { - - } - - vnetIDParam := c.Params().Get("vnet") - if vnetIDParam != "" { - - } - - subGroupIDParam := c.Params().Get("subgroup") - if subGroupIDParam != "" { - - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - "McisInfo": resultMcisInfo, - })) -} - -func McisReg(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisReqInfo := &tbmcis.TbMcisReq{} - if err := c.Bind(mcisReqInfo); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - // vm이 사용할 connection 조회 -> 화면에서 넘기도록 변경함. - // vmRegList := mcisReqInfo.Vm - // connectionMap := map[string]string{} - // for idx, regVm := range vmRegList { - // useConnectionName := "" - // val, exists := connectionMap[regVm.ProviderID+"|"+regVm.RegionName] - // if exists { - // useConnectionName = val - // } else { - // // connection 조회 : vm마다 다를 수 있음 - // paramViewConnection := views.ViewCloudConnection{} - // paramViewConnection.ProviderID = regVm.ProviderID - // paramViewConnection.RegionName = regVm.RegionName - // paramViewConnection.ZoneName = regVm.ZoneName - // viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - // if err != nil { - // return c.Render(500, r.JSON(map[string]interface{}{ - // "error": "there is no available connection", - // "status": "500", - // })) - // } - // useConnectionName = viewConnection.ConnectionName - // connectionMap[regVm.ProviderID+"|"+regVm.RegionName] = useConnectionName - // } - - // if strings.Compare(useConnectionName, "") == 0 { - // return c.Render(500, r.JSON(map[string]interface{}{ - // "error": "there is no available connection info", - // "status": "500", - // })) - // } - - // log.Println("useConnectionName", useConnectionName) - // // 사용할 connection set - // //regVm.ConnectionName = useConnectionName - // vmRegList[idx].ConnectionName = useConnectionName - // } - - // log.Println("connectionMap", connectionMap) - - // MCIS 생성 시 notification 정보 set - taskKey := namespaceID + "||" + "mcis" + "||" + mcisReqInfo.Name // TODO : 공통 function으로 뺄 것. - handler.StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, util.MCIS_LIFECYCLE_CREATE, util.TASK_STATUS_REQUEST, c) // session에 작업내용 저장 - - // 생성 요청 비동기. - go handler.RegMcisByAsync(namespaceID, mcisReqInfo, c) - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -// McisDynamicReg -// /ns/{nsId}/loadDefaultResource 로 해당 namespace에 기본 리소스(vnet, sg, sshkey) 를 가져오는 작업이 선행되어야 함. 없으면 에러 -// error message : cannot find the key /ns/workation/resources/vNet/workation-systemdefault-gcp-asia-northeast1 -func McisDynamicReg(c buffalo.Context) error { - log.Println("McisDynamicReg") - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisReqInfo := &tbmcis.TbMcisDynamicReq{} - if err := c.Bind(mcisReqInfo); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - log.Println("mcisReqInfo", mcisReqInfo) - - // MCIS 생성 시 notification 정보 set - taskKey := namespaceID + "||" + "mcis" + "||" + mcisReqInfo.Name // TODO : 공통 function으로 뺄 것. - handler.StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, util.MCIS_LIFECYCLE_CREATE, util.TASK_STATUS_REQUEST, c) // session에 작업내용 저장 - - // vm의 connection 정보 추출 - // vm이 사용할 connection 조회 - vmRegList := mcisReqInfo.Vm - connectionMap := map[string]string{} - for idx, regVm := range vmRegList { - useConnectionName := "" - val, exists := connectionMap[regVm.ProviderID+"|"+regVm.RegionName] - log.Println("val", val) - log.Println("exists", exists) - if exists { - useConnectionName = val - } else { - // connection 조회 : vm마다 다를 수 있음 - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ProviderID = strings.ToUpper(regVm.ProviderID) - paramViewConnection.RegionName = regVm.RegionName - paramViewConnection.ZoneName = regVm.ZoneName - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - useConnectionName = viewConnection.ConnectionName - connectionMap[regVm.ProviderID+"|"+regVm.RegionName] = useConnectionName - } - log.Println("useConnectionName=", useConnectionName) - if strings.Compare(useConnectionName, "") == 0 { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection info", - "status": "500", - })) - } - - log.Println("useConnectionName", useConnectionName) - // 사용할 connection set - //regVm.ConnectionName = useConnectionName - //vmRegList[idx].ConnectionName = useConnectionName - vmRegList[idx].ConnectionName = "" // for the test - } - log.Println("before RegMcisDynamicByAsync ") - // 생성 요청 비동기. - go handler.RegMcisDynamicByAsync(namespaceID, mcisReqInfo, c) - log.Println("after RegMcisDynamicByAsync ") - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -func McisDel(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisID := c.Param("mcisId") - optionParam := c.Params().Get("option") - - log.Println("mcisID= " + mcisID) - _, respStatus := handler.DelMcis(namespaceID, mcisID, optionParam) - log.Println("RegMcis service returned") - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - })) -} - -// MCIS의 status변경 -func McisLifeCycle(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisLifeCycle := &webconsole.McisLifeCycle{} - if err := c.Bind(mcisLifeCycle); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - - if namespaceID != mcisLifeCycle.NameSpaceID { - // 변경할 Namespace 정보가 다르므로 변경 불가 - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "선택된 Namespace가 아닙니다. Namespace를 임의로 변경하여 호출하면 안됨.", - "status": "400", // TODO : custom으로 만드는 resultCode 정리 필요 - })) - } - - taskKey := namespaceID + "||" + "mcis" + "||" + mcisLifeCycle.McisID // TODO : 공통 function으로 뺄 것. - handler.StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, mcisLifeCycle.Action, util.TASK_STATUS_REQUEST, c) // session에 작업내용 저장 - - go handler.McisLifeCycleByAsync(mcisLifeCycle, c) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "action": mcisLifeCycle.Action, - })) -} - -// VM의 LifeCycle status변경 -func McisVmLifeCycle(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - vmLifeCycle := &webconsole.VmLifeCycle{} - if err := c.Bind(vmLifeCycle); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - - vmLifeCycle.NameSpaceID = namespaceID - - taskKey := namespaceID + "||" + "vm" + "||" + vmLifeCycle.McisID + "||" + vmLifeCycle.VmID - handler.StoreWebsocketMessage(util.TASK_TYPE_VM, taskKey, vmLifeCycle.Action, util.TASK_STATUS_REQUEST, c) - - go handler.McisVmLifeCycleByAsync(vmLifeCycle, c) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "action": vmLifeCycle.Action, - })) -} - -// Mcis 내 특정 VM 조회 -func McisVmGet(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisID := c.Param("mcisId") - vmID := c.Param("vmId") - - returnVmInfo, respStatus := handler.GetVMofMcisData(namespaceID, mcisID, vmID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - // VM 정보에는 connection 관련정보가 빠져있어 추가로 조회. TODO : 필요없으면 제거할 것. - connectionName := returnVmInfo.ConnectionName - cloudConnectionConfigInfo, _ := handler.GetCloudConnectionConfigData(connectionName) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": respStatus.Message, - "status": respStatus.StatusCode, - "VmInfo": returnVmInfo, - "ConnectionConfigInfo": cloudConnectionConfigInfo, - })) -} - -// Mcis 의 subgroup 목록 조회 : id만 return -func McisSubGroupList(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisID := c.Param("mcisId") - - returnSubgroupList, respStatus := handler.McisSubGroupList(namespaceID, mcisID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": respStatus.Message, - "status": respStatus.StatusCode, - "SubgroupList": returnSubgroupList, - })) -} - -// Mcis 의 subgroup 조회 : 해당 subgroup VM 목록 ID 만 반환 -func McisSubgroupGet(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisID := c.Param("mcisId") - subgroupID := c.Param("subgroupId") - - returnSubgroupVmIdList, respStatus := handler.VmIdListBySubgroupID(namespaceID, mcisID, subgroupID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": respStatus.Message, - "status": respStatus.StatusCode, - "McisSubgroupId": returnSubgroupVmIdList, - })) -} - -// Mcis 내 특정 VM 모니터링 조회 -func McisVmMonitoring(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace").(string) - - // mcisID := c.Param("mcisID") - // vmID := c.Param("vmID") - - vmMonitoring := &dragonfly.VmMonitoringReq{} - if err := c.Bind(vmMonitoring); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - vmMonitoring.NameSpaceID = namespaceID - - returnVMMonitoringInfo, respStatus := handler.GetVmMonitoring(vmMonitoring) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "VMMonitoringInfo": returnVMMonitoringInfo[vmMonitoring.Metric], - })) -} - -// 특정 resource를 사용하는 mcis와 그안의 vm 들을 filter 하여 return -func McisListByResource(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - filterKeyParam := c.Params().Get("filterKey") - filterValParam := c.Params().Get("filterVal") - - mcisIdList, respStatus := handler.GetMcisListByID(namespaceID, "", "") - - returnMcisList := []tbmcis.TbMcisInfo{} - for _, mcisId := range mcisIdList { - mcisInfo, _ := handler.GetMcisData(namespaceID, mcisId) - vmList := mcisInfo.Vm - - returnVmList := []tbmcis.TbVmInfo{} - fmt.Println(returnVmList) - for _, vm := range vmList { - if strings.EqualFold("vpc", filterKeyParam) { - if filterValParam != "" && filterValParam != vm.VNetID { - continue - } - } - // security group은 배열이라 - // if strings.EqualFold("securitygroup", filterKeyParam){ - // if filterValParam != "" && filterValParam != vm.SecurityGroupIDs[] { - // continue - // } - // } - returnVmList = append(returnVmList, vm) - } - - if len(returnVmList) == 0 { - continue - } - - mcisInfo.Vm = returnVmList - returnMcisList = append(returnMcisList, *mcisInfo) - - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": respStatus.Message, - "status": respStatus.StatusCode, - "McisList": returnMcisList, - })) -} - -// MCIS의 특정 vnet을 사용하는 vm 들만 추출 -func McisVmListByVnet(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - // TODO : post로 넘어오면 bind 해야하는지 확인 필요 - mcisID := c.Param("mcisID") - vnetID := c.Param("vnetID") - - resultMcisInfo, respStatus := handler.GetMcisData(namespaceID, mcisID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - vmList := resultMcisInfo.Vm - resultVmList := []tbmcis.TbVmInfo{} - for _, vm := range vmList { - if vm.VNetID == vnetID { - resultVmList = append(resultVmList, vm) - } - } - resultMcisInfo.Vm = resultVmList - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": respStatus.Message, - "status": respStatus.StatusCode, - "McisInfo": resultMcisInfo, - })) -} - -// MCIS에 VM 목록으로 추가 등록 -func McisAppendVmListReg(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisID := c.Param("mcisId") - - mcisReqInfo := &tbmcis.TbMcisReq{} - if err := c.Bind(mcisReqInfo); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - - vms := mcisReqInfo.Vm - for _, vmInfo := range vms { - //taskKey := namespaceID + "||" + "vm" + "||" + mcisID + "||" + vmInfo.Name - //handler.StoreWebsocketMessage(util.TASK_TYPE_VM, taskKey, util.VM_LIFECYCLE_CREATE, util.TASK_STATUS_REQUEST, c) - - // go 루틴 호출 : return 값은 session에 저장 - go handler.AsyncRegVm(namespaceID, mcisID, &vmInfo, c) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -// MCIS에 VM 추가 등록 -func McisAppendVmReg(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisID := c.Param("mcisId") - - vmInfo := &tbmcis.TbVmReq{} - if err := c.Bind(vmInfo); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - - // taskKey := namespaceID + "||" + "vm" + "||" + mcisID + "||" + vmInfo.Name - // handler.StoreWebsocketMessage(util.TASK_TYPE_VM, taskKey, util.VM_LIFECYCLE_CREATE, util.TASK_STATUS_REQUEST, c) - - // go 루틴 호출 : return 값은 session에 저장 - go handler.AsyncRegVm(namespaceID, mcisID, vmInfo, c) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -// 등록되지 않은 CSP의 VM을 system에 등록. namespace 지정 필요 -func RegisterCspVm(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisReq := &tbmcis.TbMcisReq{} - if err := c.Bind(mcisReq); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - - resultMcisInfo, respStatus := handler.RegCspVm(namespaceID, mcisReq) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - "McisInfo": resultMcisInfo, - })) -} - -// VmDynamicReg -func McisVmDynamicReg(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisID := c.Param("mcisId") - - mcisReqInfo := &tbmcis.TbMcisDynamicReq{} - if err := c.Bind(mcisReqInfo); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - vmReqList := mcisReqInfo.Vm - for _, vmReqInfo := range vmReqList { - taskKey := namespaceID + "||" + "vm" + "||" + vmReqInfo.Name // TODO : 공통 function으로 뺄 것. - // VM 생성 시 notification 정보 set - handler.StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, util.MCIS_LIFECYCLE_CREATE, util.TASK_STATUS_REQUEST, c) - go handler.RegVmDynamicByAsync(namespaceID, mcisID, &vmReqInfo, c) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -// GetMcisRecommendVmSpecList -// TODO : spec 조회 부분이니 spec으로 옮겨야 하나 -// GetMcisRecommendVmSpecList move to RecommendVmSpecList in vmspec.go diff --git a/mc_web_console_api/actions/_old/mcismonitoring.go b/mc_web_console_api/actions/_old/mcismonitoring.go deleted file mode 100644 index c1971126..00000000 --- a/mc_web_console_api/actions/_old/mcismonitoring.go +++ /dev/null @@ -1,204 +0,0 @@ -package actions - -import ( - "log" - "mc_web_console_api/fwmodels" - "mc_web_console_api/fwmodels/dragonfly" - "mc_web_console_api/handler" - "net/http" - - "github.com/gobuffalo/buffalo" -) - -func McisMonitoringDurationMetric(c buffalo.Context) error { - log.Println("McisMonitoringData") - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisMonitoring := &dragonfly.McisMonitoringOnDemandInfoReq{} - if err := c.Bind(mcisMonitoring); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - mcisMonitoring.NameSpaceID = namespaceID - - returnMcisMonitoringInfo, respStatus := handler.GetMcisMonitoringDurationInfo(mcisMonitoring.NameSpaceID, mcisMonitoring.McisID, mcisMonitoring.MetricName) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "McisMonitoringInfo": returnMcisMonitoringInfo, - })) -} - -// MCIS의 monitoring data 조회 : 가져오는 것은 GET이지만 설정 항목이 많아 POST로 받음 -// 모니터링정보는 DF를 호출하지만 해당기능이 DF에 완전하지 않아 TB에 있는 API 호출 -func McisMonitoringOndemandMetric(c buffalo.Context) error { - log.Println("McisMonitoringData") - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisMonitoring := &dragonfly.McisMonitoringOnDemandInfoReq{} - if err := c.Bind(mcisMonitoring); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - - mcisMonitoring.NameSpaceID = namespaceID - - returnVMMonitoringInfo, respStatus := handler.GetMcisOnDemandMonitoringMetricInfo(mcisMonitoring) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "McisVMMonitoringInfo": returnVMMonitoringInfo, - })) -} - -// MCIS내 특정 vm monitoring data 조회 : 가져오는 것은 GET이지만 설정 항목이 많아 POST로 받음 -// option 으로 구분 ( 이전에는 3개의 다른 function이었음) -func McisVmMonitoringOndemand(c buffalo.Context) error { - log.Println("McisVmMonitoringOndemand") - namespaceID := c.Session().Get("current_namespace_id").(string) - - optionParam := c.Params().Get("option") - - vmMonitoringReq := &dragonfly.VmMonitoringReq{} - if err := c.Bind(vmMonitoringReq); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - - returnVMMonitoringInfo := &dragonfly.VmMonitoringOnDemandInfo{} - respStatus := fwmodels.WebStatus{} - - vmMonitoringReq.NameSpaceID = namespaceID - - if optionParam == "NetworkPacket" { - returnVMMonitoringInfo, respStatus = handler.GetMcisVmOnDemandMonitoringMetricInfo(vmMonitoringReq) - } else if optionParam == "Metric" { - returnVMMonitoringInfo, respStatus = handler.GetMcisVmOnDemandMonitoringMetricInfo(vmMonitoringReq) - } else if optionParam == "ProcessUsage" { - returnVMMonitoringInfo, respStatus = handler.GetMcisVmOnDemandMonitoringMetricInfo(vmMonitoringReq) - } else { - respStatus.Message = "optionParam is invalid " + optionParam - respStatus.StatusCode = 500 - } - - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "McisVMMonitoringInfo": returnVMMonitoringInfo, - })) -} - -// MCIS내 특정 vm monitoring data 조회 : 가져오는 것은 GET이지만 설정 항목이 많아 POST로 받음 -// func McisVmMonitoringOndemandMetric(c buffalo.Context) error { -// log.Println("McisVmMonitoringData") -// namespaceID := c.Session().Get("current_namespace_id").(string) - -// vmMonitoringReq := &dragonfly.VmMonitoringReq{} -// if err := c.Bind(vmMonitoringReq); err != nil { -// log.Println(err) -// return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ -// "message": "fail", -// "status": "fail", -// })) -// } - -// vmMonitoringReq.NameSpaceID = namespaceID - -// returnVMMonitoringInfo, respStatus := handler.GetMcisVmOnDemandMonitoringMetricInfo(vmMonitoringReq) -// if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { -// return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ -// "error": respStatus.Message, -// "status": respStatus.StatusCode, -// })) -// } -// return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ -// "message": "success", -// "status": respStatus.StatusCode, -// "McisVMMonitoringInfo": returnVMMonitoringInfo, -// })) -// } - -// func McisVmMonitoringOndemandNetworkPacket(c buffalo.Context) error { -// log.Println("McisVmMonitoringOndemandNetworkPacket") -// namespaceID := c.Session().Get("current_namespace_id").(string) - -// vmMonitoringReq := &dragonfly.VmMonitoringReq{} -// if err := c.Bind(vmMonitoringReq); err != nil { -// log.Println(err) -// return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ -// "message": "fail", -// "status": "fail", -// })) -// } - -// vmMonitoringReq.NameSpaceID = namespaceID - -// returnVMMonitoringInfo, respStatus := handler.GetMcisVmOnDemandMonitoringMetricInfo(vmMonitoringReq) -// if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { -// return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ -// "error": respStatus.Message, -// "status": respStatus.StatusCode, -// })) -// } -// return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ -// "message": "success", -// "status": respStatus.StatusCode, -// "McisVMMonitoringInfo": returnVMMonitoringInfo, -// })) -// } - -// func McisVmMonitoringOndemandProcessUsage(c buffalo.Context) error { -// log.Println("McisVmMonitoringOndemandProcessUsage") -// namespaceID := c.Session().Get("current_namespace_id").(string) - -// vmMonitoringReq := &dragonfly.VmMonitoringReq{} -// if err := c.Bind(vmMonitoringReq); err != nil { -// log.Println(err) -// return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ -// "message": "fail", -// "status": "fail", -// })) -// } - -// vmMonitoringReq.NameSpaceID = namespaceID - -// returnVMMonitoringInfo, respStatus := handler.GetMcisVmOnDemandMonitoringMetricInfo(vmMonitoringReq) -// if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { -// return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ -// "error": respStatus.Message, -// "status": respStatus.StatusCode, -// })) -// } -// return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ -// "message": "success", -// "status": respStatus.StatusCode, -// "McisVMMonitoringInfo": returnVMMonitoringInfo, -// })) -// } diff --git a/mc_web_console_api/actions/_old/mcksmng.go b/mc_web_console_api/actions/_old/mcksmng.go deleted file mode 100644 index b2783782..00000000 --- a/mc_web_console_api/actions/_old/mcksmng.go +++ /dev/null @@ -1,267 +0,0 @@ -package actions - -import ( - "log" - "mc_web_console_api/fwmodels/ladybug" - "mc_web_console_api/handler" - "mc_web_console_api/models/views" - "mc_web_console_api/util" - "net/http" - "strings" - - "github.com/gobuffalo/buffalo" -) - -// McksmngGet default implementation. -// todo : mcks 가져오는 로직으로 변경할것것 -func McksGet(c buffalo.Context) error { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "not implement", - })) -} - -// McksmngList default implementation. -func McksList(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - optionParam := c.Params().Get("option") - - if optionParam == "id" { - mcksList, respStatus := handler.GetClusterListByID(namespaceID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "McksList": mcksList, - })) - } else { - mcksList, respStatus := handler.GetClusterList(namespaceID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "McksList": mcksList, - })) - } -} - -func McksReg(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - clusterReq := &ladybug.ClusterRegReq{} - if err := c.Bind(clusterReq); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - // ControlPlane 이 사용할 connection 조회 - controlPlaneList := clusterReq.ControlPlane - connectionMap := map[string]string{} - for idx, controlPlane := range controlPlaneList { - useConnectionName := "" - val, exists := connectionMap[controlPlane.ProviderID+"|"+controlPlane.RegionName] - if exists { - useConnectionName = val - } else { - // connection 조회 : vm마다 다를 수 있음 - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ProviderID = controlPlane.ProviderID - paramViewConnection.RegionName = controlPlane.RegionName - paramViewConnection.ZoneName = controlPlane.ZoneName - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - useConnectionName = viewConnection.ConnectionName - connectionMap[controlPlane.ProviderID+"|"+controlPlane.RegionName] = useConnectionName - } - - if strings.Compare(useConnectionName, "") == 0 { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection info", - "status": "500", - })) - } - - log.Println("useConnectionName", useConnectionName) - // 사용할 connection set - //regVm.ConnectionName = useConnectionName - controlPlaneList[idx].Connection = useConnectionName - } - - // Worker들이 사용할 connection 조회 - workerList := clusterReq.Worker - workerConnectionMap := map[string]string{} - for idx, worker := range workerList { - useConnectionName := "" - val, exists := workerConnectionMap[worker.ProviderID+"|"+worker.RegionName] - if exists { - useConnectionName = val - } else { - // connection 조회 : vm마다 다를 수 있음 - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ProviderID = worker.ProviderID - paramViewConnection.RegionName = worker.RegionName - paramViewConnection.ZoneName = worker.ZoneName - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - useConnectionName = viewConnection.ConnectionName - workerConnectionMap[worker.ProviderID+"|"+worker.RegionName] = useConnectionName - } - - if strings.Compare(useConnectionName, "") == 0 { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection info", - "status": "500", - })) - } - - log.Println("useConnectionName", useConnectionName) - // 사용할 connection set - //regVm.ConnectionName = useConnectionName - workerList[idx].Connection = useConnectionName - } - - // Async로 변경 - // taskKey := namespaceID + "||" + "mcks" + "||" + clusterReq.Name // TODO : 공통 function으로 뺄 것. - // handler.StoreWebsocketMessage(util.TASK_TYPE_MCKS, taskKey, util.MCKS_LIFECYCLE_CREATE, util.TASK_STATUS_REQUEST, c) // session에 작업내용 저장 - go handler.RegClusterByAsync(namespaceID, clusterReq, c) - // 원래는 호출 결과를 return하나 go routine으로 바꾸면서 요청성공으로 return - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -func McksDel(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - //clusterUID := c.Param("clusterUID") - mcksName := c.Param("mcksName") - log.Println("mcksName= " + mcksName) - - taskKey := namespaceID + "||" + "mcks" + "||" + mcksName - handler.StoreWebsocketMessage(util.TASK_TYPE_MCKS, taskKey, util.MCKS_LIFECYCLE_DELETE, util.TASK_STATUS_REQUEST, c) // session에 작업내용 저장 - - go handler.DelClusterByAsync(namespaceID, mcksName, c) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) -} - -// Node 등록 처리 -func McksNodeReg(c buffalo.Context) error { - - namespaceID := c.Session().Get("current_namespace_id").(string) - - clusterName := c.Param("mcksName") - - nodeRegReq := &ladybug.NodeRegReq{} - if err := c.Bind(nodeRegReq); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - - // Worker들이 사용할 connection 조회 - workerList := nodeRegReq.Worker - workerConnectionMap := map[string]string{} - for idx, worker := range workerList { - useConnectionName := "" - val, exists := workerConnectionMap[worker.ProviderID+"|"+worker.RegionName] - if exists { - useConnectionName = val - } else { - // connection 조회 : vm마다 다를 수 있음 - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ProviderID = worker.ProviderID - paramViewConnection.RegionName = worker.RegionName - paramViewConnection.ZoneName = worker.ZoneName - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - useConnectionName = viewConnection.ConnectionName - workerConnectionMap[worker.ProviderID+"|"+worker.RegionName] = useConnectionName - } - - if strings.Compare(useConnectionName, "") == 0 { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection info", - "status": "500", - })) - } - - log.Println("useConnectionName", useConnectionName) - // 사용할 connection set - //regVm.ConnectionName = useConnectionName - workerList[idx].Connection = useConnectionName - } - - nodeInfo, respStatus := handler.RegNode(namespaceID, clusterName, nodeRegReq) - log.Println("RegNode service returned") - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "NodeInfo": nodeInfo, - })) -} - -// Node 삭제 처리 -func McksNodeDel(c buffalo.Context) error { - - namespaceID := c.Session().Get("current_namespace_id").(string) - - //clusterName := c.Param("clusterName") - mcksName := c.Param("mcksName") - nodeName := c.Param("nodeName") - - resultStatusInfo, respStatus := handler.DelNode(namespaceID, mcksName, nodeName) - log.Println("DelMCKS service returned") - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "StatusInfo": resultStatusInfo, - })) -} diff --git a/mc_web_console_api/actions/_old/myimage.go b/mc_web_console_api/actions/_old/myimage.go deleted file mode 100644 index d0824509..00000000 --- a/mc_web_console_api/actions/_old/myimage.go +++ /dev/null @@ -1,215 +0,0 @@ -package actions - -import ( - "log" - "mc_web_console_api/handler" - "mc_web_console_api/models" - "mc_web_console_api/models/views" - "net/http" - - tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - tbmcis "mc_web_console_api/fwmodels/tumblebug/mcis" - - "github.com/gobuffalo/buffalo" - "github.com/gofrs/uuid" -) - -func MyImageReg(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - myImageRegInfo := &tbmcir.TbCustomImageReq{} - if err := c.Bind(myImageRegInfo); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - // connection 조회 : namespace와 무관 . 얘도 bind 써도 되나? - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ProviderID = myImageRegInfo.ProviderID - paramViewConnection.RegionName = myImageRegInfo.RegionName - paramViewConnection.ZoneName = myImageRegInfo.ZoneName - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - // 사용할 connection set - myImageRegInfo.ConnectionName = viewConnection.ConnectionName - - resultMyImageInfo, respStatus := handler.RegCspCustomImageToMyImage(namespaceID, myImageRegInfo) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - // db setting sshkey status: C - //namespace ID add - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.Status = "C" - connectionMapping.ResourceType = "myimage" - connectionMapping.ResourceID = resultMyImageInfo.ID - connectionMapping.ResourceName = resultMyImageInfo.Name - connectionMapping.CloudConnectionID = viewConnection.ID - connectionMapping.CredentialID = viewConnection.CredentialID - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - err = handler.SaveConnectionMapping(connectionMapping, c) - if err != nil { - // 실패시 생성한 vpc Resource 제거 - _, respStatus := handler.DelMyImage(namespaceID, resultMyImageInfo.ID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(500, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "MyImageInfo": resultMyImageInfo, - })) -} - -func MyImageList(c buffalo.Context) error { - log.Println("MyImageList : ") - namespaceID := c.Session().Get("current_namespace_id").(string) - // TODO : defaultNameSpaceID 가 없으면 설정화면으로 보낼 것 - log.Println("session get namespace id : ", namespaceID) - optionParam := c.Params().Get("option") - filterKeyParam := c.Params().Get("filterKey") - filterValParam := c.Params().Get("filterVal") - - if optionParam == "id" { - log.Println("option param : id") - myImageInfoList, respStatus := handler.GetMyImageListByID(namespaceID, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "defaultNameSpaceID": namespaceID, - "myImageInfoList": myImageInfoList, - })) - } else { - myImageInfoList, respStatus := handler.GetMyImageListByOption(namespaceID, optionParam, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "myImageInfoList": myImageInfoList, - })) - } -} - -func MyImageGet(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - myImageID := c.Param("myImageId") - - myImageInfo, respStatus := handler.MyImageGet(namespaceID, myImageID) - - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ConnectionName = myImageInfo.ConnectionName - viewConnection, err := handler.GetViewConnection(paramViewConnection) - if err != nil { - // cb에서 정보는 가져왔으니 오류로 뱉지는 않기. - } else { - myImageInfo.ProviderID = viewConnection.ProviderID - myImageInfo.RegionName = viewConnection.RegionName - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "myImageInfo": myImageInfo, - })) -} - -func MyImageDel(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - paramMyImageID := c.Param("myImageId") - - respMessage, respStatus := handler.DelMyImage(namespaceID, paramMyImageID) - - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - // DB 등록 : mapping에 D로 저장할 때 사용된 connection 정보가 필요하여 조회 - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.ResourceType = "myimage" - connectionMapping.ResourceID = paramMyImageID - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - - usedConnectionMapping, err := handler.GetUsedConnection(connectionMapping) - if err != nil { - // TODO : mapping table에 없을 때, 에러로 처리할 것인가? - // return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - // "error": respStatus.Message, - // "status": respStatus.StatusCode, - // })) - } else { - // 삭제 Row 추가 - usedConnectionMapping.Status = "D" - usedConnectionMapping.ID = uuid.UUID{} - err = handler.SaveConnectionMapping(usedConnectionMapping, c) - if err != nil { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": respMessage.Message, - "status": respMessage.StatusCode, - })) -} - -func VmSnapshotReg(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - vmSnapshotReq := new(tbmcis.TbVmSnapshotReq) - if err := c.Bind(vmSnapshotReq); err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "failed to create vm snapshot", - "status": "500", - })) - } - - mcisID := c.Param("mcisId") - vmID := c.Param("vmId") - go handler.AsyncRegVmSnapshot(namespaceID, mcisID, vmID, vmSnapshotReq, c) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - })) -} diff --git a/mc_web_console_api/actions/_old/namespace.go b/mc_web_console_api/actions/_old/namespace.go deleted file mode 100644 index 2971ad89..00000000 --- a/mc_web_console_api/actions/_old/namespace.go +++ /dev/null @@ -1,413 +0,0 @@ -package actions - -import ( - "log" - "math/rand" - "mc_web_console_api/fwmodels" - "mc_web_console_api/handler" - "mc_web_console_api/models" - "net/http" - "time" - - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - "mc_web_console_api/fwmodels/webconsole" - - "github.com/davecgh/go-spew/spew" - "github.com/gobuffalo/buffalo" - "github.com/gobuffalo/pop/v6" - "github.com/gofrs/uuid" - "github.com/pkg/errors" -) - -// const CHARSET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" -// namespace 제약조건 : "The first character of name must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash." -const NSCHARSET = "abcdefghijklmnopqrstuvwxyz0123456789" - -// 첫번째 문자는 무조건 영문 소문자 여야 한다. -const FCHARSET = "abcdefghijklmnopqrstuvwxyz" - -// Tumble에 등록된 모든 namespace 목록 조회 -// db에서 사용하는 namespace model에는 사용자 정보가 들어가 있어서 -// 가져온 값 그대로 return -func NamespaceAllList(c buffalo.Context) error { - nsList, nsStatus := handler.GetNameSpaceList() - if nsStatus.StatusCode == 500 { - return c.Render(http.StatusOK, r.JSON(nsStatus)) - } - - return c.Render(http.StatusOK, r.JSON(nsList)) -} - -// 해당 user의 namespace 목록 조회 - -// NamespaceList -// - -func NamespaceList(c buffalo.Context) error { - //내가 생성한 NS외에 내가 share받은 NS를 가져와야 함으로 - // user_namespaces 에서 가져와야 함. - // 아니다 내가 생성한것 만 조히하고 싶을 수도 있겠다. - // 공유 받은 NS호출때는 GetsharedNamespace를 호출하자 - ns := &models.Namespaces{} - - if uid := c.Session().Get("current_user_id"); uid != nil { - - tx := c.Value("tx").(*pop.Connection) - - q := tx.Eager().Where("user_id = ?", uid) - - err := q.All(ns) - - if err != nil { - return errors.WithStack(err) - } - } - c.Set("ns_list", ns) - return c.Render(http.StatusOK, r.JSON(ns)) -} - -// 해당 user의 namespace 목록 조회 -// NamespaceGet -// - -func NamespaceGet(c buffalo.Context) error { - ns := &models.Namespace{} - c.Set("ns", ns) - - err := c.Bind(ns) - if err != nil { - return errors.WithStack(err) - } - - if uid := c.Session().Get("current_user_id"); uid != nil { - - tx := c.Value("tx").(*pop.Connection) - - q := tx.Eager().Where("user_id = ? and ns_name = ? ", uid, ns.NsName) - err := q.All(ns) - - if err != nil { - return errors.WithStack(err) - } - } - return c.Render(http.StatusOK, r.JSON(ns)) -} - -// NamespaceUpdate - 미구현 -// - -func NamespaceUpdate(c buffalo.Context) error { - return c.Render(http.StatusBadRequest, r.JSON(fwmodels.WebStatus{StatusCode: 500, Message: "not implementated yet"})) -} - -// SetAssignNamespace -// - -func SetAssignNamespace(c buffalo.Context) error { - obj := &webconsole.UserNamespaceReq{} - - err := c.Bind(obj) - - if err != nil { - return errors.WithStack(err) - } - - tx := c.Value("tx").(*pop.Connection) - - herr := handler.RegUserNamespace(obj, tx) - if herr != nil { - return c.Render(http.StatusInternalServerError, r.JSON(map[string]interface{}{ - "error": "Create User namespace error", - "status": 500, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) - -} - -// SetDeAssignNamespace -// - -func SetDeAssignNamespace(c buffalo.Context) error { - obj := &webconsole.UserNamespaceReq{} - - err := c.Bind(obj) - - if err != nil { - return errors.WithStack(err) - } - - tx := c.Value("tx").(*pop.Connection) - - herr := handler.DelUserNamespace(obj, tx) - if herr != nil { - return c.Render(http.StatusInternalServerError, r.JSON(map[string]interface{}{ - "error": "Delete User namespace error", - "status": 500, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "delete success", - "status": 200, - })) - -} - -// GetSharedNamespace -// - -func GetSharedNamespace(c buffalo.Context) error { - tx := c.Value("tx").(*pop.Connection) - - // Selected USER ID - request_param := c.Param("UID") - var uid uuid.UUID - if request_param == "" { - uid = c.Session().Get("current_user_id").(uuid.UUID) - } else { - uid = uuid.Must(uuid.FromString(request_param)) - } - - uns := models.UserNamespaces{} - err := tx.Eager().Where("user_id = ?", uid).All(&uns) - if err != nil { - return errors.WithStack(err) - } - - return c.Render(http.StatusOK, r.JSON(uns)) - -} - -// Namespace 생성 -// - -func NamespaceReg(c buffalo.Context) error { - //form 에서 그냥 네임 값 가져 올때 - //ts := c.Request().FormValue("input name") - ns := &models.Namespace{} - err := c.Bind(ns) - if err != nil { - log.Println(ns) - log.Println("err ", err) - return errors.WithStack(err) - } - log.Println("Namespace Bind@@@@@@@@@@@= ") - - // 0. check dupe ns name - // dupe_err := CheckDupeNamespaceName(c, ns.NsName) - - // if dupe_err != nil { - // return dupe_err - // } - - // 1.중복체크 - // tb에서 모든 namespace를 조회한다. - tbNamespaceList, nsStatus := handler.GetNameSpaceList() - if nsStatus.StatusCode == 500 { - return c.Render(http.StatusMovedPermanently, r.JSON(map[string]interface{}{ - "error": nsStatus.Message, - "status": nsStatus.StatusCode, - })) - } - log.Println("tbNamespaceList@@@@@@@@@@@= ") - for _, tbns := range tbNamespaceList { - if tbns.ID == ns.ID { - return c.Render(http.StatusMovedPermanently, r.JSON(map[string]interface{}{ - "error": "namespace exists", - "status": 500, - })) - } - } - - c.Set("ns", ns) // bind 이후로 이전 by yhnoh. - - tx := c.Value("tx").(*pop.Connection) - - //현재 사용자 값 가져 오기 - u := c.Value("current_user").(*models.User) - if u.ID == uuid.Nil { - c.Flash().Add("warning", "Cannot Find User") - - //return c.Redirect(301, "/") - // return RedirectTool(c, "homeFormPath") - } - - ns.User = u - ns.UserID = u.ID - ns.ID = StringWithCharset() - //namespace create - verrs, err := ns.Create(tx) - if err != nil { - return errors.WithStack(err) - } - if verrs.HasAny() { - spew.Dump("validate error", verrs) - c.Set("errors", verrs) - } - - // 이쪽을 따로 때어서 권한 관리와 같이 엮어서 처리 - // user_namespace create - un := &models.UserNamespace{} - - //if ns.ID == "" {// ns의 ID는 stringWithCharset로 생성하므로 의미없음 by yhnoh - if ns.NsName == "" { - c.Flash().Add("warning", "cannot find namespace") - //return c.Redirect(301, "/")// ajax로 넘어오므로 redirect는 의미 없음 by yhnoh - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": "cannot find namespace", - "status": "301", - })) - } - - un.NamespaceID = ns.ID - un.UserID = u.ID - un.Namespace = ns - un.User = u - - verr, err := un.Create(tx) - - if verr.HasAny() { - spew.Dump("user_namespace", *verr) - //return c.Redirect(200, "/namespace/list/")// ajax로 넘어오므로 redirect는 의미 없음 by yhnoh - return c.Render(http.StatusMovedPermanently, r.JSON(map[string]interface{}{ - "error": verr.Error, - "status": "301", - })) - } - if err != nil { - spew.Dump("user_namespace", un) - //return errors.WithStack(err) - return c.Render(http.StatusMovedPermanently, r.JSON(map[string]interface{}{ - "error": err.Error, - "status": "301", - })) - } - //spew.Dump("namespace create before redirect") - - //return c.Redirect(301, "/namespace/list") - - // 2. TB에 namespace 생성 - nameSpaceInfo := &tbcommon.TbNsInfo{} - //nameSpaceInfo.ID = ns.ID - nameSpaceInfo.Name = ns.ID - tbNamespace, nsStatus := handler.RegNameSpace(nameSpaceInfo) - if nsStatus.StatusCode == 500 { - return c.Render(http.StatusMovedPermanently, r.JSON(map[string]interface{}{ - "error": nsStatus.Message, - "status": nsStatus.StatusCode, - })) - } - log.Println("tbNamespace!!!!!!!!!!!!!!!!!!!= ", tbNamespace) - - // 3. 해당 user의 namespace 목록 조회 - userNamespaceList, nsStatus := handler.UserNameSpaceListFromDB(u.ID, tx) - if nsStatus.StatusCode != 200 && nsStatus.StatusCode != 201 { - log.Println("UserNameSpaceListFromDB !!!!= ", nsStatus) - return c.Render(http.StatusMovedPermanently, r.JSON(map[string]interface{}{ - "error": nsStatus.Message, - "status": "301", - })) - } - log.Println("return nsList !!!!!!!!!!!!!!!!!!!= ", userNamespaceList) - return c.Render(http.StatusOK, r.JSON(userNamespaceList)) -} - -// stringWithCharset return of random string -// 라우팅 X -func StringWithCharset() string { - var seededRand *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano())) - - b := make([]byte, 8) - f := make([]byte, 2) - - for i := range b { - b[i] = NSCHARSET[seededRand.Intn(len(NSCHARSET))] - } - for i := range f { - f[i] = FCHARSET[seededRand.Intn(len(FCHARSET))] - } - fb := string(f) + string(b) - return fb -} - -// namespace Name dupe check -func CheckDupeNamespaceName(c buffalo.Context, ns_name string) error { - tx := c.Value("tx").(*pop.Connection) - ns := &models.Namespace{} - ns.NsName = ns_name - q := tx.Where("ns_name = ?", ns.NsName) - - b, err := q.Exists(ns) - - if b { - return c.Render(http.StatusMovedPermanently, r.JSON(map[string]interface{}{ - "error": "already Exist!!", - "status": "301", - })) - } - - if err != nil { - return errors.WithStack(err) - } - - return nil -} - -// TestUpdateNamespace -// - -func estUpdateNamespace(c buffalo.Context) error { - ns := &models.Namespace{} - description := "test update Namespace" - nsName := "update-ns-name" - // check_err := CheckDupeNamespaceName(c, nsName) - // if check_err != nil { - // spew.Dump("---------error--------") - // spew.Dump(check_err) - // spew.Dump("---------error--------") - // return check_err - // } - //err := c.Bind(ns) - ns_id := "u9cznc87dp" - tx := c.Value("tx").(*pop.Connection) - //ferr := tx.Find(ns, ns_id) - ferr := tx.Eager().Where("id = ?", ns_id).First(ns) - if ferr != nil { - spew.Dump(ferr) - } - ns.NsName = nsName - ns.Description = description - spew.Dump("==============") - spew.Dump(ns) - //err := models.DB.Update(ns, "user_id") - verr, err := ns.ValidateUpdate(tx) - if verr.HasAny() { - spew.Dump("==============") - spew.Dump("=======true=====") - spew.Dump("==============") - spew.Dump(verr.String()) - - } - - if err != nil { - spew.Dump(err) - } - //err := q.All(u) - - return nil - -} - -func GetSharedNamespaceList(uid uuid.UUID, tx *pop.Connection) *models.UserNamespaces { - uns := &models.UserNamespaces{} - err := tx.Eager().Where("user_id = ?", uid).All(uns) - if err != nil { - errors.WithStack(err) - } - return uns -} diff --git a/mc_web_console_api/actions/_old/nlb.go b/mc_web_console_api/actions/_old/nlb.go deleted file mode 100644 index 5a468d08..00000000 --- a/mc_web_console_api/actions/_old/nlb.go +++ /dev/null @@ -1,228 +0,0 @@ -package actions - -import ( - "log" - "mc_web_console_api/fwmodels/tumblebug/mcis" - "mc_web_console_api/handler" - "mc_web_console_api/models" - "mc_web_console_api/models/views" - "mc_web_console_api/util" - "net/http" - - "github.com/gobuffalo/buffalo" - "github.com/gofrs/uuid" -) - -// namespace의 특정 mcis안에 있는 nlb 목록 조회 -func NlbList(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisID := c.Param("mcisId") - optionParam := c.Params().Get("option") - - if optionParam == "id" { - nlbList, respStatus := handler.GetNlbIdListByMcisID(namespaceID, mcisID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "NlbList": nlbList, - })) - } else { - nlbList, respStatus := handler.GetNlbListByOption(namespaceID, mcisID, optionParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "NlbList": nlbList, - })) - } -} - -func NlbDel(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisID := c.Param("mcisId") - nlbID := c.Param("nlbId") - - optionParam := c.Params().Get("option") - log.Println("nlbId= " + nlbID) - - resultNlbInfo, respStatus := handler.DelNlb(namespaceID, mcisID, nlbID, optionParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - // DB 등록 : mapping에 D로 저장할 때 사용된 connection 정보가 필요하여 조회 - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.ResourceType = "nlb" - connectionMapping.ResourceID = nlbID // CspNlbId 로 해야하나?? - connectionMapping.NamespaceID = namespaceID - - usedConnectionMapping, err := handler.GetUsedConnection(connectionMapping) - if err != nil { - // TODO : mapping table에 없을 때, 에러로 처리할 것인가? - // return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - // "error": respStatus.Message, - // "status": respStatus.StatusCode, - // })) - } else { - // 삭제 Row 추가 - usedConnectionMapping.Status = "D" - usedConnectionMapping.ID = uuid.UUID{} - err = handler.SaveConnectionMapping(usedConnectionMapping, c) - if err != nil { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "StatusInfo": resultNlbInfo, - })) -} - -func AllNlbListOfNamespace(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - //namespaceName := c.Session().Get("current_namespace").(string) - - mcisIdList, respStatus := handler.GetMcisListByID(namespaceID, "", "") - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - totalNlbList := []mcis.TbNLBInfo{} - for _, mcisID := range mcisIdList { - nlbList, respStatus := handler.GetNlbListByOption(namespaceID, mcisID, "") - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - continue - } - // mcisID set - for _, nlb := range nlbList { - nlb.McisID = mcisID - log.Println("nlb.McisID : ", nlb.McisID) - totalNlbList = append(totalNlbList, nlb) - } - //totalNlbList = append(totalNlbList, nlbList...) // mcisID가 set 안됨. - - } - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "NlbList": totalNlbList, - })) - -} - -func NlbReg(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - nlbReq := &mcis.TbNLBReq{} - if err := c.Bind(nlbReq); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "5001", - })) - } - paramViewConnection := views.ViewCloudConnection{} - - paramViewConnection.ProviderID = nlbReq.ProviderID - paramViewConnection.RegionName = nlbReq.RegionName - - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - - log.Println("*************nlbReq : ", nlbReq, "|*************namespaceID : ", namespaceID, "|**********viewconnection :", viewConnection, "|*************error : ", err) - - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - nlbReq.ConnectionName = viewConnection.ConnectionName - mcisID := c.Param("mcisId") - - // // socket의 key 생성 : ns + 구분 + id - taskKey := namespaceID + "||" + "nlb" + "||" + nlbReq.Name // TODO : 공통 function으로 뺄 것. - - handler.StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, util.MCIS_LIFECYCLE_CREATE, util.TASK_STATUS_REQUEST, c) // session에 작업내용 저장 - - // // go routin, channel - go handler.RegNlbByAsync(namespaceID, mcisID, nlbReq, c) // 오래걸리므로 요청여부만 return, 결과는 notice로 확인 - // 원래는 호출 결과를 return하나 go routine으로 바꾸면서 요청성공으로 return - log.Println("before return") - - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.Status = "T" - connectionMapping.ResourceType = "nlb" - connectionMapping.ResourceID = nlbReq.CspNlbId - connectionMapping.ResourceName = nlbReq.Name - connectionMapping.CloudConnectionID = viewConnection.ID - connectionMapping.CredentialID = viewConnection.CredentialID - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - err = handler.SaveConnectionMapping(connectionMapping, c) - if err != nil { - // 실패시 생성한 vpc Resource 제거 - _, respStatus := handler.DelNlb(namespaceID, mcisID, nlbReq.CspNlbId, nlbReq.Name) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(500, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - })) - -} - -func NlbGet(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - mcisID := c.Param("mcisId") - nlbID := c.Param("nlbId") - log.Println("nlbId= " + nlbID) - - resultNlbInfo, respStatus := handler.GetNlbData(namespaceID, mcisID, nlbID) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "NlbInfo": resultNlbInfo, - })) - -} diff --git a/mc_web_console_api/actions/_old/nsdashboard.go b/mc_web_console_api/actions/_old/nsdashboard.go deleted file mode 100644 index 0f3a37f3..00000000 --- a/mc_web_console_api/actions/_old/nsdashboard.go +++ /dev/null @@ -1 +0,0 @@ -package actions diff --git a/mc_web_console_api/actions/_old/oldauth.go b/mc_web_console_api/actions/_old/oldauth.go deleted file mode 100644 index eddb1e4a..00000000 --- a/mc_web_console_api/actions/_old/oldauth.go +++ /dev/null @@ -1,106 +0,0 @@ -package actions - -import ( - "database/sql" - "net/http" - "strings" - - "github.com/gobuffalo/buffalo" - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" - "github.com/pkg/errors" - "golang.org/x/crypto/bcrypt" - - "mc_web_console_api/handler" - "mc_web_console_api/models" -) - -// AuthCreate attempts to log the user in with an existing account. -// -// @Summary 로그인 -// @Description [AuthCreate] 존재하는 계정으로 로그인을 시도합니다. attempts to log the user in with an existing account. -// @Tags auth -// @Accept json -// @Produce json -// @Param Email formData string true "Email" -// @Param Password formData string true "Password" -// @Success 200 {string} string "{'message': 'success', 'user': 'u'}" -// @Failure 500 {string} string "{'error':'verrs','status':'http.StatusUnauthorized'}" -// @Router /api/auth/signin/ [post] -func AuthCreate(c buffalo.Context) error { - u := &models.User{} - //spew.Dump("buffalo context : ", c) - u.Email = c.Request().FormValue("Email") - u.Password = c.Request().FormValue("Password") - - // if err := c.Bind(u); err != nil { - // return errors.WithStack(err) - // } - - tx := c.Value("tx").(*pop.Connection) - - // find a user with the email - err := tx.Where("email = ?", strings.ToLower(strings.TrimSpace(u.Email))).First(u) - - // helper function to handle bad attempts - bad := func() error { - verrs := validate.NewErrors() - verrs.Add("email", "invalid email/password") - - c.Set("errors", verrs) - c.Set("user", u) - - return c.Render(http.StatusUnauthorized, r.JSON(map[string]interface{}{ - "error": verrs, - "status": http.StatusUnauthorized, - })) - } - - if err != nil { - if errors.Cause(err) == sql.ErrNoRows { - // couldn't find an user with the supplied email address. - return bad() - } - return errors.WithStack(err) - } - - // confirm that the given password matches the hashed password from the db - err = bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(u.Password)) - if err != nil { - return bad() - } - //_, ns := handler.GetNamespaceById(u.DefaultNamespace, tx) - ns, _ := handler.GetNamespaceById(u.DefaultNamespace) - c.Session().Session.Options.MaxAge = 20 - c.Session().Set("current_user_id", u.ID) - c.Session().Set("current_namespace_id", ns.ID) - c.Session().Set("current_namespace", ns.NsName) - c.Session().Set("current_credential", u.DefaultCredential) - c.Flash().Add("success", "Welcome Back to Buffalo!") - - // redirectURL := "/" - // if redir, ok := c.Session().Get("redirectURL").(string); ok && redir != "" { - // redirectURL = redir - // } - - return c.Render(200, r.JSON(map[string]interface{}{ - "status": 200, - "user": u, - })) -} - -// AuthDestroy clears the session and logs a user out -// -// @Summary 로그아웃 -// @Description [AuthDestroy] 로그아웃을 합니다. clears the session and logs a user out -// @Tags auth -// @Accept json -// @Produce json -// @Success 200 {string} string "{'success-Flash': 'You have been logged out!'}" -// @Router /api/auth/logout/ [get] -// func AuthDestroy(c buffalo.Context) error { -// c.Session().Clear() -// c.Flash().Add("success", "You have been logged out!") -// //return c.Redirect(302, "/auth/signin/mngform/") -// return RedirectTool(c, "authNewFormPath") -// } diff --git a/mc_web_console_api/actions/_old/pmksmng.go b/mc_web_console_api/actions/_old/pmksmng.go deleted file mode 100644 index c2e1e012..00000000 --- a/mc_web_console_api/actions/_old/pmksmng.go +++ /dev/null @@ -1,252 +0,0 @@ -package actions - -import ( - "log" - "mc_web_console_api/fwmodels/spider" - "mc_web_console_api/handler" - "mc_web_console_api/models" - "mc_web_console_api/models/views" - "mc_web_console_api/util" - "net/http" - "strings" - - "github.com/gobuffalo/buffalo" -) - -func PmksRegProc(c buffalo.Context) error { - - clusterReqInfo := &spider.ClusterReqInfo{} - if err := c.Bind(clusterReqInfo); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - log.Println(clusterReqInfo) - - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - clusterReqInfo.NameSpace = namespaceID - - paramViewConnection := views.ViewCloudConnection{} - - reqRegion := clusterReqInfo.ReqInfo.RegionName - reqProviderID := clusterReqInfo.ReqInfo.ProviderID - - paramViewConnection.ProviderID = reqProviderID - paramViewConnection.RegionName = reqRegion - - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - clusterReqInfo.ConnectionName = viewConnection.ConnectionName - - taskKey := namespaceID + "||" + "pmks" + "||" + clusterReqInfo.ReqInfo.Name // TODO : 공통 function으로 뺄 것. - handler.StoreWebsocketMessage(util.TASK_TYPE_PMKS, taskKey, util.PMKS_LIFECYCLE_CREATE, util.TASK_STATUS_REQUEST, c) // session에 작업내용 저장 - go handler.RegPmksClusterByAsync(clusterReqInfo, c) - // 원래는 호출 결과를 return하나 go routine으로 바꾸면서 요청성공으로 return - log.Println("before return") - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.Status = "T" //T : temporary 비동기는 T - connectionMapping.ResourceType = "pmkscluster" - //connectionMapping.ResourceID = resultVmSpecInfo.ID - connectionMapping.ResourceName = clusterReqInfo.ReqInfo.Name - connectionMapping.CloudConnectionID = viewConnection.ID - connectionMapping.CredentialID = viewConnection.CredentialID - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - err = handler.SaveConnectionMapping(connectionMapping, c) - if err != nil { - // 실패시 생성한 omks 제거 - _, respStatus := handler.DelPmksCluster(clusterReqInfo.ReqInfo.Name, *clusterReqInfo) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(500, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": http.StatusOK, - })) -} - -func PmksNodeGroupRegProc(c buffalo.Context) error { - log.Println("PmksNodeGroupRegProc : ") - - nodeGroupReqInfo := new(spider.NodeGroupReqInfo) - if err := c.Bind(nodeGroupReqInfo); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - clusterID := c.Param("clusterID") - - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - nodeGroupReqInfo.NameSpace = namespaceID - - paramViewConnection := views.ViewCloudConnection{} - - reqRegion := nodeGroupReqInfo.ReqInfo.RegionName - reqProviderID := nodeGroupReqInfo.ReqInfo.ProviderID - - paramViewConnection.ProviderID = reqProviderID - paramViewConnection.RegionName = reqRegion - - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - - nodeGroupReqInfo.ConnectionName = viewConnection.ConnectionName - - nodeInfo, respStatus := handler.RegPmksNodeGroup(clusterID, nodeGroupReqInfo) - - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.Status = "C" //T : temporary 비동기는 T - connectionMapping.ResourceType = "pmksnodegroup" - connectionMapping.ResourceID = nodeInfo.Name - connectionMapping.ResourceName = nodeGroupReqInfo.ReqInfo.Name - connectionMapping.CloudConnectionID = viewConnection.ID - connectionMapping.CredentialID = viewConnection.CredentialID - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - err = handler.SaveConnectionMapping(connectionMapping, c) - - if err != nil { - // 실패시 생성한 omks 제거 - _, respStatus := handler.DelPmksNodeGroup(clusterID, nodeGroupReqInfo.ReqInfo.Name, nodeGroupReqInfo) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(500, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - - log.Println("RegNodeGroup service returned") - - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - "NodeInfo": nodeInfo, - })) -} - -func PmksListOfNamespace(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - clusterReqInfo := spider.AllClusterReqInfo{} - clusterReqInfo.NameSpace = namespaceID - - // ","를 구분자로 하는 connectionNames 잘라서 다시 string 배열에 넣고 써야 함. - connectionNames := c.Params().Get("connectionNames") - if connectionNames != "" { - connNameArr := strings.Split(connectionNames, ",") - for _, connName := range connNameArr { - clusterReqInfo.ConnectionNames = append(clusterReqInfo.ConnectionNames, connName) - } - } - - // 임시 코드 - clusterReqInfo.ConnectionNames = append(clusterReqInfo.ConnectionNames, "ten-cortado-con") - - pmksList, respStatus := handler.GetPmksNamespaceClusterList(clusterReqInfo) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": respStatus.Message, - "status": "fail", - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - "DefaultNameSpaceID": namespaceID, - "PmksList": pmksList, - })) -} - -// PmksmngList default implementation. -func PmksMngList(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - optionParam := c.Params().Get("option") - - if optionParam == "id" { - pmksList, respStatus := handler.GetClusterListByID(namespaceID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "PmksList": pmksList, - })) - } else { - pmksList, respStatus := handler.GetClusterList(namespaceID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "PmksList": pmksList, - })) - } -} - -func GetPmksInfoData(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - paramClusterID := c.Param("clusterId") - log.Println("***********************************") - log.Println("clusterID= " + paramClusterID) - log.Println("***********************************") - paramConnectionName := c.Param("connectionName") - log.Println("***********************************") - log.Println("connectionName= " + paramConnectionName) - log.Println("***********************************") - clusterReqInfo := spider.ClusterReqInfo{} - clusterReqInfo.NameSpace = namespaceID - clusterReqInfo.ConnectionName = paramConnectionName - resultPmksInfo, _ := handler.GetPmksClusterData(paramClusterID, clusterReqInfo) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - "PmksInfo": resultPmksInfo, - })) -} diff --git a/mc_web_console_api/actions/_old/policy.go b/mc_web_console_api/actions/_old/policy.go deleted file mode 100644 index 38494f19..00000000 --- a/mc_web_console_api/actions/_old/policy.go +++ /dev/null @@ -1,243 +0,0 @@ -package actions - -import ( - "log" - "mc_web_console_api/fwmodels/dragonfly" - "mc_web_console_api/handler" - "net/http" - - "github.com/gobuffalo/buffalo" -) - -// Monitoring Config 정책 조회 -func MonitoringConfigPolicyData(c buffalo.Context) error { - - //MonitoringConfig - monitoringConfig, respStatus := handler.GetMonitoringConfig() - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "MonitoringConfig": monitoringConfig, - })) -} - -// Monitoring Config 정책 수정 -func MonitoringConfigPolicyUpdate(c buffalo.Context) error { - - monitoringConfigRegInfo := &dragonfly.MonitoringConfigReg{} - if err := c.Bind(monitoringConfigRegInfo); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": err.Error(), - "status": "5001", - })) - } - - resultMonitoringConfigInfo, respStatus := handler.PutMonigoringConfig(monitoringConfigRegInfo) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "MonitoringConfig": resultMonitoringConfigInfo, - })) -} - -// Monitoring alert 임계치 등록 처리 -func MonitoringAlertPolicyReg(c buffalo.Context) error { - log.Println("MonitoringAlertPolicyReg : ") - - monitoringAlertRegInfo := &dragonfly.VmMonitoringAlertInfo{} - if err := c.Bind(monitoringAlertRegInfo); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "5001", - })) - } - log.Println(monitoringAlertRegInfo) - - resultMonitoringAlertInfo, respStatus := handler.RegMonitoringAlert(monitoringAlertRegInfo) - log.Println("MonitoringAlertPolicyReg service returned") - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "MonitoringConfig": resultMonitoringAlertInfo, - })) -} - -// Monitoring alert 임계치 설정 목록 -func MonitoringAlertPolicyList(c buffalo.Context) error { - - // alarm 설정 목록 조회 - monitoringAlertPolicyList, respStatus := handler.GetMonitoringAlertList() - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - // 등록된 eventHandler 목록조회. 현재는 smtp, slack만 등록 가능(생성화면에서 추가로 등록해야 목록으로 조회 됨) - monitoringAlertEventHandlerList, _ := handler.GetMonitoringAlertEventHandlerList() - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "MonitoringAlertPolicyList": monitoringAlertPolicyList, - "MonitoringAlertEventHandlerList": monitoringAlertEventHandlerList, - })) -} - -func MonitoringAlertPolicyData(c buffalo.Context) error { - - monitoringAlertId := c.Param("monitoringAlertId") - - // 알람 설정 값 조회 - monitoringAlertPolicyInfo, respStatus := handler.GetMonitoringAlertData(monitoringAlertId) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - // 알람 발생 이력 조회 - paramLevel := "critical" - monitoringAlertLogList, respStatus := handler.GetMonitoringAlertLogList(monitoringAlertId, paramLevel) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "MonitoringAlertPolicyInfo": monitoringAlertPolicyInfo, - "MonitoringAlertLogList": monitoringAlertLogList, - })) -} - -func MonitoringAlertPolicyDel(c buffalo.Context) error { - log.Println("MonitoringAlertPolicyDelProc : ") - - paramMonitoringAlertID := c.Param("monitoringAlertId") - - // 글로벌한 설정이라 namespace 없이 호출 - respBody, respStatus := handler.DelMonitoringAlert(paramMonitoringAlertID) - log.Println("=============respBody =============", respBody) - - // if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - // return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - // "error": respStatus.Message, - // "status": respStatus.StatusCode, - // })) - // } - - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) -} - -// alarm 발생이력 조회 -// 설정한 alarm, 조회할 level(ok, warning, critical) -func MonitoringAlertLogList(c buffalo.Context) error { - //namespaceID := c.Session().Get("current_namespace_id").(string) - - monitoringAlertId := c.Param("monitoringAlertId") - paramLevel := c.Param("level") - - monitoringAlertLogList, respStatus := handler.GetMonitoringAlertLogList(monitoringAlertId, paramLevel) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "MonitoringAlertLogList": monitoringAlertLogList, - })) -} - -// Monitoring alert 를 전송할 매체 목록(smtp, slack) -func MonitoringAlertEventHandlerList(c buffalo.Context) error { - log.Println("GetMonitoringAlertEventHandlerList ************ : ") - - // Monitoring Alert Event Handler 호출 - monitoringAlertEventHandlerList, respStatus := handler.GetMonitoringAlertEventHandlerList() - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "MonitoringAlertEventHandlerList": monitoringAlertEventHandlerList, - })) -} - -// Monitoring Alert Event-Handler 등록 처리 -func MonitoringAlertEventHandlerReg(c buffalo.Context) error { - log.Println("MonitoringAlertEventHandlerRegProc : ") - - monitoringAlertEventHandlerRegInfo := &dragonfly.VmMonitoringAlertEventHandlerInfoReg{} - if err := c.Bind(monitoringAlertEventHandlerRegInfo); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "5001", - })) - } - log.Println(monitoringAlertEventHandlerRegInfo) - resultMonitoringAlertEventHandlerInfo, respStatus := handler.RegMonitoringAlertEventHandler(monitoringAlertEventHandlerRegInfo) - log.Println("MonitoringAlertEventHandlerReg service returned") - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "MonitoringEventHandler": resultMonitoringAlertEventHandlerInfo, - })) -} - -func MonitoringAlertEventHandlerDel(c buffalo.Context) error { - log.Println("MonitoringAlertEventHandlerDelProc : ") - - paramMonitoringAlertEvantHandlerType := c.Param("handlerType") - paramMonitoringAlertEvantHandlerName := c.Param("eventName") - - // 글로벌한 설정이라 namespace 없이 호출 - respBody, respStatus := handler.DelMonitoringAlertEventHandler(paramMonitoringAlertEvantHandlerType, paramMonitoringAlertEvantHandlerName) - log.Println("=============respBody =============", respBody) - - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - })) -} diff --git a/mc_web_console_api/actions/_old/resource.go b/mc_web_console_api/actions/_old/resource.go deleted file mode 100644 index 1607b977..00000000 --- a/mc_web_console_api/actions/_old/resource.go +++ /dev/null @@ -1,28 +0,0 @@ -package actions - -import ( - "mc_web_console_api/handler" - "net/http" - - "github.com/gobuffalo/buffalo" -) - -func LoadCommonResource(c buffalo.Context) error { - - commonresourceinfo, webStatus := handler.GetLoadCommonResource() - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "webstatus": webStatus, - "commonresourceinfo": commonresourceinfo, - })) -} - -func GetInspectResourcesOverview(c buffalo.Context) error { - - cspResource, webStatus := handler.GetInspectResourcesOverview() - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "webstatus": webStatus, - "cspResource": cspResource, - })) -} diff --git a/mc_web_console_api/actions/_old/scheduling.go b/mc_web_console_api/actions/_old/scheduling.go deleted file mode 100644 index 828c7f8b..00000000 --- a/mc_web_console_api/actions/_old/scheduling.go +++ /dev/null @@ -1,104 +0,0 @@ -package actions - -import ( - "log" - "mc_web_console_api/fwmodels/webconsole" - "net/http" - "time" - - "github.com/go-co-op/gocron" - "github.com/gobuffalo/buffalo" -) - -// go-cron을 여기서 실행 시켜야 함. -type Scheduler struct { - Spec string - Title string - StartTime time.Time - McisLifeCycle webconsole.McisLifeCycle - VmLifeCycle webconsole.VmLifeCycle -} - -var c *gocron.Scheduler - -func GoCron(s Scheduler) { - //spec 와일드 카드로 생성(m h dom m dow) - // - - c = gocron.NewScheduler(time.UTC) - spec := s.Spec - j, _ := c.Cron(spec).Do(DoWork, s) - tag := "example" - j.Tag(tag) - // 해당 Tag에 걸린 JOB 없애기 - err := c.RemoveByTag(tag) - if err != nil { - //로그 찍고 DB 저장 할 것 - } - - // 스케쥴 건거 다음 시간 알아내기 - jobs, _ := c.FindJobsByTag(tag) - - j0 := jobs[0] - nextTime := j0.NextRun() - log.Println("nextTime by Tag : ", nextTime) - now := time.Now() - now.Date() -} - -// 마지막 시작된 스케쥴 시간 - -// 해당 스케쥴의 다음 시간 알아내서 전달 -func NextScheduleTimeByTag(t string) time.Time { - j, err := c.FindJobsByTag(t) - - if err != nil { - // 에러가 있을경우 해당 로직 처리 예정 - } - getJob := j[0] - - nextTime := getJob.NextRun() - - return nextTime -} - -func SchedulingReg(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - // mcisLifeCycle := &webconsole.McisLifeCycle{} - // vmLifeCycle := &webconsole.VmLifeCycle{} - - // if err := c.Bind(mcisLifeCycle);err != nil{ - // return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - // "message": "fail", - // "status": "fail", - // })) - // } - - // if err := c.Bind(vmLifeCycle);err != nil{ - // return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - // "message": "fail", - // "status": "fail", - // })) - // } - // mcisLifeCycle.NameSpaceID = namespaceID - // vmLifeCycle.NameSpaceID = namespaceID - // scheduleSet.McisLifeCycle = *mcisLifeCycle - // scheduleSet.VmLifeCycle = *vmLifeCycle - scheduleSet := Scheduler{} - - // namespaceID Setting - scheduleSet.McisLifeCycle.NameSpaceID = namespaceID - scheduleSet.VmLifeCycle.NameSpaceID = namespaceID - - if err := c.Bind(scheduleSet); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - // cron 을 통해 작업 스케쥴링 - GoCron(scheduleSet) - - return nil -} diff --git a/mc_web_console_api/actions/_old/securitygroup.go b/mc_web_console_api/actions/_old/securitygroup.go deleted file mode 100644 index ccb4fc37..00000000 --- a/mc_web_console_api/actions/_old/securitygroup.go +++ /dev/null @@ -1,397 +0,0 @@ -package actions - -import ( - "log" - "mc_web_console_api/handler" - "mc_web_console_api/models" - "mc_web_console_api/models/views" - "net/http" - "strings" - - tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - - "github.com/gobuffalo/buffalo" - "github.com/gofrs/uuid" -) - -// SecuritygroupList -func SecurityGroupList(c buffalo.Context) error { - log.Println("GetSecirityGroupList : ") - namespaceID := c.Session().Get("current_namespace_id").(string) - - optionParam := c.Params().Get("option") - filterKeyParam := c.Params().Get("filterKey") - filterValParam := c.Params().Get("filterVal") - - if optionParam == "id" { - securityGroupInfoList, respStatus := handler.GetSecurityGroupListByOptionID(namespaceID, optionParam, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "SecurityGroupList": securityGroupInfoList, - })) - } else { - securityGroupInfoList, respStatus := handler.GetSecurityGroupListByOption(namespaceID, optionParam, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "SecurityGroupList": securityGroupInfoList, - })) - } -} - -func SecurityGroupListByRegion(c buffalo.Context) error { - log.Println("SecuritygroupListByRegion : ") - namespaceID := c.Session().Get("current_namespace_id").(string) - - optionParam := c.Params().Get("option") - filterKeyParam := c.Params().Get("filterKey") - filterValParam := c.Params().Get("filterVal") - is_cb := c.Params().Get("is_cb") - - paramProviderID := c.Params().Get("providerId") - paramRegionName := c.Params().Get("regionName") - paramZoneName := c.Params().Get("zoneName") - paramConnectionName := c.Params().Get("connectionName") - - paramVpcID := c.Params().Get("vpcId") - paramConnectionMap := map[string]string{} - paramConnectionMap["vpc"] = paramVpcID - - if paramVpcID != "" { - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.NamespaceID = namespaceID - connectionMapping.ResourceType = "vpc" - connectionMapping.ResourceID = paramVpcID - - // TODO : 해당 vpc를 사용하는 securityGroup 목록 조회. filter key로 tb 조회하도록 변경할 것. - usedConnectionMapping, err := handler.GetUsedConnectionTx(connectionMapping, c) - if err != nil { - log.Println("err", err) - } - - log.Println("paramProviderID", paramProviderID) - log.Println("paramRegionName", paramRegionName) - log.Println("usedConnectionMapping", usedConnectionMapping) - - // 두단계 아래는 못가져오므로 connectionId로 provider, region정보를 가져옴.--> 필요한가? - //log.Println("CloudConnection sss ", usedConnectionMapping.CloudConnection) - //paramProviderID = usedConnectionMapping.CloudConnection.ProviderID - //log.Println("Region sss ", usedConnectionMapping.CloudConnection.Region) - //paramRegionName = usedConnectionMapping.CloudConnection.Region.RegionName - //log.Println("paramRegionName", paramRegionName) - } - - log.Println("is_cb ", is_cb) - if is_cb == "N" { - log.Println("is_cb2 ", is_cb) - securityGroupList, err := handler.ListResourceByType(namespaceID, paramConnectionMap, paramProviderID, paramRegionName, paramZoneName, "securitygroup") - if err != nil { - log.Println("VnetListByRegion err", err) - - return c.Render(500, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - - // ID만 가져오는 경우는 가져온 resource에서 vpcID만 추출하여 return - if optionParam == "id" { - returnSecurityGroupIds := []string{} - for _, item := range securityGroupList { - returnSecurityGroupIds = append(returnSecurityGroupIds, item.ResourceName) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "SecurityGroupList": returnSecurityGroupIds, // string 배열 리턴 - })) - } - - // 상세정보가 필요한 경우는 사용된 connection 정보로 cb-tb 조회하여 연결 - usedConnectionMap := map[string]string{} - for _, item := range securityGroupList { - usedConnectionMap[item.ConnectionName] = item.ConnectionName - } - log.Println("usedConnectionMap ", usedConnectionMap) - returnSecurityGroupList := []tbmcir.TbSecurityGroupInfo{} - for _, val := range usedConnectionMap { - paramFilterKey := "connectionName" - paramFilterVal := val - securityGroupInfoList, respStatus := handler.GetSecurityGroupListByOption(namespaceID, optionParam, paramFilterKey, paramFilterVal) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - returnSecurityGroupList = append(returnSecurityGroupList, securityGroupInfoList...) - } - - log.Println("VnetListByRegion return ids", returnSecurityGroupList) - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "SecurityGroupList": returnSecurityGroupList, - })) - - } else { - if filterKeyParam == "" && paramVpcID != "" { - filterKeyParam = "vNetId" - filterValParam = paramVpcID - } - if optionParam == "id" { - securityGroupInfoList, respStatus := handler.GetSecurityGroupListByOptionID(namespaceID, optionParam, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "SecurityGroupList": securityGroupInfoList, - })) - } else { - - if !strings.EqualFold(paramConnectionName, "") && strings.EqualFold(filterKeyParam, "") { - filterKeyParam = "connectionName" - filterValParam = paramConnectionName - } - - securityGroupInfoList, respStatus := handler.GetSecurityGroupListByOption(namespaceID, optionParam, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "SecurityGroupList": securityGroupInfoList, - })) - } - } -} - -// 단건조회 -func SecurityGroupGet(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - paramSecurityGroupID := c.Param("securityGroupId") - securityGroupInfo, respStatus := handler.GetSecurityGroupData(namespaceID, paramSecurityGroupID) - if respStatus.StatusCode == 500 { - return c.Render(http.StatusInternalServerError, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ConnectionName = securityGroupInfo.ConnectionName - viewConnection, err := handler.GetViewConnection(paramViewConnection) - if err != nil { - // cb에서 정보는 가져왔으니 오류로 뱉지는 않기. - } else { - securityGroupInfo.ProviderID = viewConnection.ProviderID - securityGroupInfo.ProviderName = viewConnection.ProviderID - securityGroupInfo.RegionName = viewConnection.RegionName - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "SecurityGroupInfo": securityGroupInfo, - })) -} - -func SecurityGroupReg(c buffalo.Context) error { - // 현재 namespace 정보 가져오기 - - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - securityGroupRegInfo := &tbmcir.TbSecurityGroupReq{} - if err := c.Bind(securityGroupRegInfo); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - log.Println("securityGroupRegInfo ", securityGroupRegInfo) - // connection 조회 : namespace와 무관 . 얘도 bind 써도 되나? - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ProviderID = securityGroupRegInfo.ProviderID - paramViewConnection.RegionName = securityGroupRegInfo.RegionName - paramViewConnection.ZoneName = securityGroupRegInfo.ZoneName - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - - // 사용할 connection set - securityGroupRegInfo.ConnectionName = viewConnection.ConnectionName - - // TB 등록 - resultSecurityGroupInfo, respStatus := handler.RegSecurityGroup(namespaceID, securityGroupRegInfo) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - // DB 등록 - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.Status = "C" - connectionMapping.ResourceType = "securitygroup" - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - connectionMapping.ResourceID = resultSecurityGroupInfo.ID - connectionMapping.ResourceName = resultSecurityGroupInfo.Name - connectionMapping.CloudConnectionID = viewConnection.ID - connectionMapping.CredentialID = viewConnection.CredentialID - log.Println(connectionMapping) - err = handler.SaveConnectionMapping(connectionMapping, c) - if err != nil { - // 실패시 생성한 vpc Resource 제거 - _, respStatus := handler.DelVpc(namespaceID, resultSecurityGroupInfo.ID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(500, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "SecurityGroupInfo": resultSecurityGroupInfo, - })) -} - -func SecurityGroupDel(c buffalo.Context) error { - - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - paramSecurityGroupID := c.Param("securityGroupId") - - respMessage, respStatus := handler.DelSecurityGroup(namespaceID, paramSecurityGroupID) - - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - // DB 등록 : mapping에 D로 저장할 때 사용된 connection 정보가 필요하여 조회 - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - connectionMapping.ResourceType = "securitygroup" - connectionMapping.ResourceID = paramSecurityGroupID - - usedConnectionMapping, err := handler.GetUsedConnection(connectionMapping) - if err != nil { - // TODO : mapping table에 없을 때, 에러로 처리할 것인가? - // return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - // "error": respStatus.Message, - // "status": respStatus.StatusCode, - // })) - } else { - // 삭제 Row 추가 - usedConnectionMapping.Status = "D" - usedConnectionMapping.ID = uuid.UUID{} - err = handler.SaveConnectionMapping(usedConnectionMapping, c) - if err != nil { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": respMessage.Message, - "status": respMessage.StatusCode, - })) -} - -// security group rule 추가 -// firewall 은 connection과 상관없이 sg에 종속이므로 별도로 mapping table에서 관리하지 않음 -func FirewallRuleReg(c buffalo.Context) error { - // 현재 namespace 정보 가져오기 - namespaceID := c.Session().Get("current_namespace_id").(string) - - paramSecurityGroupID := c.Param("securityGroupID") - firewallRuleReqList := &tbmcir.TbFirewallRulesWrapper{} - if err := c.Bind(firewallRuleReqList); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - // TB 등록 - resultSecurityGroupInfo, respStatus := handler.RegFirewallRules(namespaceID, paramSecurityGroupID, firewallRuleReqList) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "SecurityGroupInfo": resultSecurityGroupInfo, - })) -} - -// firewall rule 삭제 : -func FirewallRuleDel(c buffalo.Context) error { - - namespaceID := c.Session().Get("current_namespace_id").(string) - - paramSecurityGroupID := c.Param("securityGroupID") - - firewallRuleReqList := &tbmcir.TbFirewallRulesWrapper{} - if err := c.Bind(firewallRuleReqList); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - resultSecurityGroupInfo, respStatus := handler.DelFirewallRules(namespaceID, paramSecurityGroupID, firewallRuleReqList) - - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "securityGroupInfo": resultSecurityGroupInfo, - })) -} diff --git a/mc_web_console_api/actions/_old/sshkey.go b/mc_web_console_api/actions/_old/sshkey.go deleted file mode 100644 index fdb93c9b..00000000 --- a/mc_web_console_api/actions/_old/sshkey.go +++ /dev/null @@ -1,290 +0,0 @@ -package actions - -import ( - "log" - tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - "mc_web_console_api/handler" - "mc_web_console_api/models" - "mc_web_console_api/models/views" - "net/http" - "strings" - - "github.com/gobuffalo/buffalo" - "github.com/gofrs/uuid" -) - -// SshkeyList default implementation. -func SshKeyList(c buffalo.Context) error { - log.Println("GetSshKeyList : ") - namespaceID := c.Session().Get("current_namespace_id").(string) - // TODO : defaultNameSpaceID 가 없으면 설정화면으로 보낼 것 - log.Println("session get namespace id : ", namespaceID) - optionParam := c.Params().Get("option") - filterKeyParam := c.Params().Get("filterKey") - filterValParam := c.Params().Get("filterVal") - - if optionParam == "id" { - log.Println("option param : id") - sshKeyInfoList, respStatus := handler.GetSshKeyInfoListByID(namespaceID, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "SshKeyList": sshKeyInfoList, - })) - } else { - sshKeyInfoList, respStatus := handler.GetSshKeyInfoListByOption(namespaceID, optionParam, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "SshKeyList": sshKeyInfoList, - })) - } -} - -func SshKeyListByRegion(c buffalo.Context) error { - log.Println("SshKeyListByRegion : ") - namespaceID := c.Session().Get("current_namespace_id").(string) - - optionParam := c.Params().Get("option") - filterKeyParam := c.Params().Get("filterKey") - filterValParam := c.Params().Get("filterVal") - is_cb := c.Params().Get("is_cb") - - paramProviderID := c.Params().Get("providerId") - paramRegionName := c.Params().Get("regionName") - paramZoneName := c.Params().Get("zoneName") - paramConnectionName := c.Params().Get("connectionName") - - paramConnectionMap := map[string]string{} // 특정 connection 을 가져오기 위해 사용. - if !strings.EqualFold(paramConnectionName, "") { - paramConnectionMap["connectionName"] = paramConnectionName - } - - log.Println("is_cb", is_cb) - /// - if is_cb == "N" { - log.Println("is_cb ", is_cb) - sshkeyList, err := handler.ListResourceByType(namespaceID, paramConnectionMap, paramProviderID, paramRegionName, paramZoneName, "sshkey") - if err != nil { - log.Println("SshKeyListByRegion err", err) - - return c.Render(500, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - - // 상세정보가 필요한 경우는 사용된 connection 정보로 cb-tb 조회하여 연결 - usedConnectionMap := map[string]string{} - for _, item := range sshkeyList { - usedConnectionMap[item.ConnectionName] = item.ConnectionName - } - log.Println("usedConnectionMap ", usedConnectionMap) - returnSshKeyList := []tbmcir.TbSshKeyInfo{} - for _, val := range usedConnectionMap { - paramFilterKey := "connectionName" - paramFilterVal := val - sshKeyInfoList, respStatus := handler.GetSshKeyInfoListByOption(namespaceID, optionParam, paramFilterKey, paramFilterVal) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - for _, item := range sshKeyInfoList { - item.ProviderID = paramProviderID - item.RegionName = paramRegionName - returnSshKeyList = append(returnSshKeyList, item) - } - //returnSshKeyList = append(returnSshKeyList, sshKeyInfoList...) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "SshKeyList": returnSshKeyList, - })) - - } else { - returnSshKeyList := []tbmcir.TbSshKeyInfo{} - - if !strings.EqualFold(paramConnectionName, "") && strings.EqualFold(filterKeyParam, "") { - filterKeyParam = "connectionName" - filterValParam = paramConnectionName - } - sshKeyInfoList, respStatus := handler.GetSshKeyInfoListByOption(namespaceID, optionParam, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - for _, item := range sshKeyInfoList { - item.ProviderID = paramProviderID - item.RegionName = paramRegionName - returnSshKeyList = append(returnSshKeyList, item) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "SshKeyList": returnSshKeyList, - })) - } -} -func SshKeyGet(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - paramSshKeyId := c.Param("sshKeyId") - - resultSshKeyInfo, respStatus := handler.GetSshKeyData(namespaceID, paramSshKeyId) - - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ConnectionName = resultSshKeyInfo.ConnectionName - viewConnection, err := handler.GetViewConnection(paramViewConnection) - if err != nil { - // cb에서 정보는 가져왔으니 오류로 뱉지는 않기. - } else { - resultSshKeyInfo.ProviderID = viewConnection.ProviderID - resultSshKeyInfo.ProviderName = viewConnection.ProviderID - resultSshKeyInfo.RegionName = viewConnection.RegionName - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "SshKeyInfo": resultSshKeyInfo, - })) -} - -func SshKeyReg(c buffalo.Context) error { - // 현재 namespace 정보 가져오기 - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - sshKeyReq := &tbmcir.TbSshKeyReq{} - if err := c.Bind(sshKeyReq); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - // connection 조회 : namespace와 무관 . 얘도 bind 써도 되나? - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ProviderID = sshKeyReq.ProviderID - paramViewConnection.RegionName = sshKeyReq.RegionName - paramViewConnection.ZoneName = sshKeyReq.ZoneName - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - log.Println("*************sshkeyreq : ", sshKeyReq, "|*************namespaceID : ", namespaceID, "|**********viewconnection :", viewConnection, "|*************error : ", err) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - // 사용할 connection set - sshKeyReq.ConnectionName = viewConnection.ConnectionName - - resultSshKeyInfo, respStatus := handler.RegSshKey(namespaceID, sshKeyReq) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - // db setting sshkey status: C - //namespace ID add - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.Status = "C" - connectionMapping.ResourceType = "sshkey" - connectionMapping.ResourceID = resultSshKeyInfo.ID - connectionMapping.ResourceName = resultSshKeyInfo.Name - connectionMapping.CloudConnectionID = viewConnection.ID - connectionMapping.CredentialID = viewConnection.CredentialID - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - err = handler.SaveConnectionMapping(connectionMapping, c) - if err != nil { - // 실패시 생성한 vpc Resource 제거 - _, respStatus := handler.DelSshKey(namespaceID, resultSshKeyInfo.ID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(500, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "SshKeyInfo": resultSshKeyInfo, - })) -} - -func SshKeyDel(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - paramSshKeyId := c.Param("sshKeyId") - - respMessage, respStatus := handler.DelSshKey(namespaceID, paramSshKeyId) - - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - connectionMapping.ResourceType = "sshkey" - connectionMapping.ResourceID = paramSshKeyId - - usedConnectionMapping, err := handler.GetUsedConnection(connectionMapping) - if err != nil { - // TODO : mapping table에 없을 때, 에러로 처리할 것인가? - // return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - // "error": respStatus.Message, - // "status": respStatus.StatusCode, - // })) - } else { - // 삭제 Row 추가 - usedConnectionMapping.ID = uuid.UUID{} - usedConnectionMapping.Status = "D" - err = handler.SaveConnectionMapping(usedConnectionMapping, c) - if err != nil { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": respMessage.Message, - "status": respMessage.StatusCode, - })) -} diff --git a/mc_web_console_api/actions/_old/systemenvironment.go b/mc_web_console_api/actions/_old/systemenvironment.go deleted file mode 100644 index be70950c..00000000 --- a/mc_web_console_api/actions/_old/systemenvironment.go +++ /dev/null @@ -1,28 +0,0 @@ -package actions - -import ( - "mc_web_console_api/handler" - "net/http" - - "github.com/gobuffalo/buffalo" -) - -func TbConfig(c buffalo.Context) error { - - configInfo, webStatus := handler.GetAllTbConfig() - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "webstatus": webStatus, - "configInfo": configInfo, - })) -} - -func TbConfigbyId(c buffalo.Context) error { - configId := c.Session().Get("id").(string) - configInfo, webStatus := handler.GetTbConfig(configId) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "webstatus": webStatus, - "configInfo": configInfo, - })) -} diff --git a/mc_web_console_api/actions/_old/systemmanagement.go b/mc_web_console_api/actions/_old/systemmanagement.go deleted file mode 100644 index b86d9582..00000000 --- a/mc_web_console_api/actions/_old/systemmanagement.go +++ /dev/null @@ -1,53 +0,0 @@ -package actions - -import ( - "log" - "mc_web_console_api/handler" - "net/http" - - "github.com/gobuffalo/buffalo" -) - -func GetTBHealth(c buffalo.Context) error { - - tbStatus, webStatus := handler.GetHealth() - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "webstatus": webStatus, - "tbStatus": tbStatus, - })) -} -func GetObjectThroughTB(c buffalo.Context) error { - log.Println("getobjectthroutb") - - key := c.Params().Get("key") - object, webStatus := handler.GetObject(key) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "webstatus": webStatus, - "object": object, - })) -} - -// func GetTBHealth(c buffalo.Context) error { - -// tbStatus, webStatus := handler.GetHealth() - -// return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ -// "webstatus": webStatus, -// "tbStatus": tbStatus, -// })) -// } - -// Get value of an object - -// List all objects for a given key -func GetObjectListThroughTB(c buffalo.Context) error { - key := c.Params().Get("key") - objectList, webStatus := handler.GetObjectList(key) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "webstatus": webStatus, - "objectList": objectList, - })) -} diff --git a/mc_web_console_api/actions/_old/users.go b/mc_web_console_api/actions/_old/users.go deleted file mode 100644 index 0da31db3..00000000 --- a/mc_web_console_api/actions/_old/users.go +++ /dev/null @@ -1,191 +0,0 @@ -package actions - -import ( - "log" - "net/http" - "strings" - - "github.com/davecgh/go-spew/spew" - "github.com/gobuffalo/buffalo" - "github.com/gobuffalo/pop/v6" - - "github.com/pkg/errors" - - "mc_web_console_api/handler" - "mc_web_console_api/models" -) - -// UsersNew renders the users form - -func UsersCreate(c buffalo.Context) error { - u := &models.User{} - if err := c.Bind(u); err != nil { - return errors.WithStack(err) - } - - // default namespace 생성 - email := strings.ToLower(strings.TrimSpace(u.Email)) - prefix_email := strings.Split(email, "@") - default_ns := prefix_email[0] - u.DefaultNamespace = default_ns - - //verrs, err := u.Create(tx) - - // ns_err := NamespaceCreateDefault(c, default_ns, u) - - // if ns_err != nil { - // spew.Dump("=====================") - // spew.Dump("NamespaceCreateDefault error") - // spew.Dump("=====================") - // return errors.WithStack(ns_err) - // } - // 사용자가 가입하고 signin 으로 로그인하게 보낼 경우는 - // 세션에 사용자 ID를 담을 필요가 없음 - // c.Session().Set("current_user_id", u.ID) - // c.Flash().Add("success", "Welcome to Buffalo!") - spew.Dump("=====================") - spew.Dump("여기까지 실행 됐음!!!") - spew.Dump("=====================") - //return c.Redirect(301, "/auth/signin/mngform/") - return nil -} - -// 기본 namespace 설정완료. -// SetCurrentNamespace -// - -func SetCurrentNamespace(c buffalo.Context) error { - log.Println("SetCurrentNamespace") - spew.Dump("======setCurrenttNamespace======") - namespaceID := c.Param("nsId") - log.Println(namespaceID) - //tx := c.Value("tx").(*pop.Connection) - //ns_err, get_ns := handler.GetNamespaceById(namespaceID, tx) - ns, ns_err := handler.GetNamespaceById(namespaceID) - if ns_err != nil { - spew.Dump(ns_err) - } - namespaceName := ns.NsName - c.Session().Set("current_namespace_id", namespaceID) - c.Session().Set("current_namespace", namespaceName) - c.Set("current_namespace_id", namespaceID) - c.Set("current_namespace", namespaceName) - - return c.Render(200, r.JSON(map[string]interface{}{ - "CurrentNameSpaceID": namespaceID, - })) -} - -// SetDefaultNamespace -// - -func SetDefaultNamespace(c buffalo.Context) error { - log.Println("SetDefaultNamespace") - spew.Dump("======setDefaultNamespace======") - namespace := c.Param("nsId") - //namespace := tbcommon.TbNsInfo{} - //if err := c.Bind(namespace); err != nil { - // return errors.WithStack(err) - //} - // - //log.Debug("bind") - - uid := c.Session().Get("current_user_id") - - tx := c.Value("tx").(*pop.Connection) - u := &models.User{} - ns := &models.Namespace{} - // 현재 사용자 가져오기 - u_err := tx.Find(u, uid) - if namespace != u.DefaultNamespace { - u.DefaultNamespace = namespace - spew.Dump(u) - spew.Dump("======setDefaultNamespace======") - if u_err != nil { - return errors.WithStack(u_err) - } - - // 새로 정의한 Default Namespace를 업데이트 친다. - e := tx.Eager().Save(u) - get_ns, ns_err := handler.GetNamespaceById(u.DefaultNamespace) - if ns_err != nil { - spew.Dump(ns_err) - } - - if e != nil { - spew.Dump(e) - } - ns = get_ns - } - //현재 사용자의 Default Namespace 를 새로 정의 하고 - - log.Println(ns) - c.Session().Set("current_namespace", ns.NsName) - c.Session().Set("current_namespace_id", ns.ID) - err := c.Session().Save() - if err != nil { - return errors.WithStack(err) - } - - return c.Render(200, r.JSON(map[string]interface{}{ - "DefaultNameSpaceID": u.DefaultNamespace, - "DefaultNameSpaceName": ns.NsName, - })) -} - -// GetUserByEmail -// - -func GetUserByEmail(c buffalo.Context) error { - tx := c.Value("tx").(*pop.Connection) - email := c.Param("email") - - u := &models.User{} - - //이미 스크립트에서 거르는데 또 거를 필요가 있을까? 싶네.... - if email != "" { - q := tx.Eager().Where("email = ?", email) - b, e_err := q.Exists(u) - if e_err != nil { - return c.Render(http.StatusExpectationFailed, r.JSON(map[string]interface{}{ - "error": "something query error", - "status": "301", - })) - } - if b { - err := q.First(u) - spew.Dump("====GET FIRST U====") - spew.Dump(u) - spew.Dump("====GET FIRST U====") - h_err, uns := handler.GetAssignUserNamespaces(u.ID, tx) - if h_err != nil { - return c.Render(301, r.JSON(map[string]interface{}{ - "error": "cannot find user", - "status": "301", - })) - } - - u.UserNamespaces = *uns - - if err != nil { - return c.Render(301, r.JSON(map[string]interface{}{ - "error": "cannot find user", - "status": "301", - })) - - } - - } else { - return c.Render(301, r.JSON(map[string]interface{}{ - "error": "cannot find user", - "status": "301", - })) - } - } else { - return c.Render(http.StatusExpectationFailed, r.JSON(map[string]interface{}{ - "error": "Please input Email", - "status": "301", - })) - } - return c.Render(http.StatusOK, r.JSON(u)) -} diff --git a/mc_web_console_api/actions/_old/vmimage.go b/mc_web_console_api/actions/_old/vmimage.go deleted file mode 100644 index c1680223..00000000 --- a/mc_web_console_api/actions/_old/vmimage.go +++ /dev/null @@ -1,348 +0,0 @@ -package actions - -import ( - "log" - "mc_web_console_api/fwmodels" - "mc_web_console_api/fwmodels/tumblebug/mcir" - "mc_web_console_api/handler" - "mc_web_console_api/models" - "mc_web_console_api/models/views" - "net/http" - "strings" - - "github.com/gobuffalo/buffalo" - "github.com/gofrs/uuid" -) - -// VmimageList default implementation. -func VmImageList(c buffalo.Context) error { - log.Println("GetVirtualMachineImageList : ") - namespaceID := c.Session().Get("current_namespace_id").(string) - - optionParam := c.Params().Get("option") - filterKeyParam := c.Params().Get("filterKey") - filterValParam := c.Params().Get("filterVal") - - paramConnectionName := c.Params().Get("connectionName") - //paramConnectionMap := map[string]string{} // 특정 connection 을 가져오기 위해 사용. - if !strings.EqualFold(paramConnectionName, "") { - //paramConnectionMap["connectionName"] = paramConnectionName - filterKeyParam = "connectionName" - filterValParam = paramConnectionName - } - - if optionParam == "id" { - virtualMachineImageInfoList, respStatus := handler.GetVirtualMachineImageInfoListByID(namespaceID, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "VirtualMachineImageList": virtualMachineImageInfoList, - })) - } else { - if !strings.EqualFold(paramConnectionName, "") && strings.EqualFold(filterKeyParam, "") { - filterKeyParam = "connectionName" - filterValParam = paramConnectionName - } - - virtualMachineImageInfoList, respStatus := handler.GetVirtualMachineImageInfoListByOption(namespaceID, optionParam, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "VirtualMachineImageList": virtualMachineImageInfoList, - })) - } -} - -func VmImageGet(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - paramVirtualMachineImage := c.Param("vmImageId") - virtualMachineImageInfo, respStatus := handler.GetVirtualMachineImageData(namespaceID, paramVirtualMachineImage) - - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ConnectionName = virtualMachineImageInfo.ConnectionName - viewConnection, err := handler.GetViewConnection(paramViewConnection) - if err != nil { - // cb에서 정보는 가져왔으니 오류로 뱉지는 않기. - } else { - virtualMachineImageInfo.ProviderID = viewConnection.ProviderID - virtualMachineImageInfo.RegionName = viewConnection.RegionName - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "VirtualMachineImageInfo": virtualMachineImageInfo, - })) -} - -func VmImageReg(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - respStatus := fwmodels.WebStatus{} - - resultVirtualMachineImageInfo := new(mcir.TbImageInfo) - - virtualMachineImageRegInfo := new(mcir.TbImageInfo) - virtualMachineImageReqInfo := new(mcir.TbImageReq) - - paramViewConnection := views.ViewCloudConnection{} - - paramVirtualMachineImageRegistType := c.Param("registeringMethod") - - if strings.EqualFold(paramVirtualMachineImageRegistType, "registerWithInfo") { - if err := c.Bind(virtualMachineImageRegInfo); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "error": "fail", - "status": "fail", - })) - } - paramViewConnection.ProviderID = virtualMachineImageRegInfo.ProviderID - paramViewConnection.RegionName = virtualMachineImageRegInfo.RegionName - paramViewConnection.ZoneName = virtualMachineImageRegInfo.ZoneName - - } else { - if err := c.Bind(virtualMachineImageReqInfo); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "error": "fail", - "status": "fail", - })) - } - paramViewConnection.ProviderID = virtualMachineImageReqInfo.ProviderID - paramViewConnection.RegionName = virtualMachineImageReqInfo.RegionName - paramViewConnection.ZoneName = virtualMachineImageReqInfo.ZoneName - - } - - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - - log.Println("*************vmimagereq : ", virtualMachineImageReqInfo, "|*************namespaceID : ", namespaceID, "|**********viewconnection :", viewConnection, "|*************error : ", err) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - - if strings.EqualFold(paramVirtualMachineImageRegistType, "registerWithInfo") { - virtualMachineImageRegInfo.ConnectionName = viewConnection.ConnectionName - resultVirtualMachineImageInfo, respStatus = handler.RegVirtualMachineImageWithInfo(namespaceID, paramVirtualMachineImageRegistType, virtualMachineImageRegInfo) - } else { - virtualMachineImageReqInfo.ConnectionName = viewConnection.ConnectionName - resultVirtualMachineImageInfo, respStatus = handler.RegVirtualMachineImage(namespaceID, paramVirtualMachineImageRegistType, virtualMachineImageReqInfo) - } - - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.Status = "C" - connectionMapping.ResourceType = "vmimage" - connectionMapping.ResourceID = resultVirtualMachineImageInfo.ID - connectionMapping.ResourceName = resultVirtualMachineImageInfo.Name - connectionMapping.CloudConnectionID = viewConnection.ID - connectionMapping.CredentialID = viewConnection.CredentialID - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - err = handler.SaveConnectionMapping(connectionMapping, c) - if err != nil { - // 실패시 생성한 vpc Resource 제거 - _, respStatus := handler.DelVirtualMachineImage(namespaceID, resultVirtualMachineImageInfo.ID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(500, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "VirtualMachineImageInfo": resultVirtualMachineImageInfo, - })) -} - -func VmImageDel(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - paramVmImageId := c.Param("vmImageId") - log.Println("***********paramVirtualMachineImage : ") - log.Println(paramVmImageId) - - respMessage, respStatus := handler.DelVirtualMachineImage(namespaceID, paramVmImageId) - - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - connectionMapping.ResourceType = "vmimage" - connectionMapping.ResourceID = paramVmImageId - - usedConnectionMapping, err := handler.GetUsedConnection(connectionMapping) - - if err != nil { - // TODO : mapping table에 없을 때, 에러로 처리할 것인가? - // return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - // "error": respStatus.Message, - // "status": respStatus.StatusCode, - // })) - } else { - // 삭제 Row 추가 - usedConnectionMapping.ID = uuid.UUID{} - usedConnectionMapping.Status = "D" - - err = handler.SaveConnectionMapping(usedConnectionMapping, c) - - if err != nil { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": respMessage.Message, - "status": respMessage.StatusCode, - })) - -} - -func LookupCspVirtualMachineImageList(c buffalo.Context) error { - - // paramConnectionName := c.Param("connectionName") - - paramProviderId := c.Params().Get("providerId") - paramRegionName := c.Params().Get("regionName") - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ProviderID = paramProviderId - paramViewConnection.RegionName = paramRegionName - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - connectionName := viewConnection.ConnectionName - virtualMachineImageInfoList, respStatus := handler.LookupVirtualMachineImageList(connectionName) - - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "VirtualMachineImageList": virtualMachineImageInfoList, - })) -} - -// lookupImage 상세정보 -func LookupVirtualMachineImageData(c buffalo.Context) error { - log.Println("LookupVirtualMachineImageData : ") - - restLookupImageRequest := new(mcir.RestLookupImageRequest) - - paramProviderId := c.Params().Get("providerId") - paramRegionName := c.Params().Get("regionName") - log.Println("paramProviderId paramRegionName : ", paramProviderId, paramRegionName) - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ProviderID = paramProviderId - paramViewConnection.RegionName = paramRegionName - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - restLookupImageRequest.ConnectionName = viewConnection.ConnectionName - if err := c.Bind(restLookupImageRequest); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "error": "fail", - "status": "fail", - })) - } - // paramVirtualMachineImage := c.Param("imageID") - // virtualMachineImageInfo, respStatus := service.LookupVirtualMachineImageData(paramVirtualMachineImage) - virtualMachineImageInfo, respStatus := handler.LookupVirtualMachineImageData(restLookupImageRequest) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "VirtualMachineImageList": virtualMachineImageInfo, - })) -} - -// lookupImage 상세정보 -func SearchVirtualMachineImageList(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - restSearchImageRequest := new(mcir.RestSearchImageRequest) - if err := c.Bind(restSearchImageRequest); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "error": "fail", - "status": "fail", - })) - } - virtualMachineImageInfoList, respStatus := handler.SearchVirtualMachineImageList(namespaceID, restSearchImageRequest) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "VirtualMachineImageList": virtualMachineImageInfoList, - })) -} - -// TODO : Fetch 의 의미 파악 -func FetchVirtualMachineImageList(c buffalo.Context) error { - log.Println("FetchVirtualMachineImageList : ") - - namespaceID := c.Session().Get("current_namespace_id").(string) - - virtualMachineImageInfoList, respStatus := handler.FetchVirtualMachineImageList(namespaceID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "VirtualMachineImageList": virtualMachineImageInfoList, - })) -} diff --git a/mc_web_console_api/actions/_old/vmspec.go b/mc_web_console_api/actions/_old/vmspec.go deleted file mode 100644 index 2fd57953..00000000 --- a/mc_web_console_api/actions/_old/vmspec.go +++ /dev/null @@ -1,326 +0,0 @@ -package actions - -import ( - "log" - "mc_web_console_api/fwmodels" - "mc_web_console_api/fwmodels/tumblebug/common" - - tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - tbmcis "mc_web_console_api/fwmodels/tumblebug/mcis" - "mc_web_console_api/handler" - "mc_web_console_api/models" - "mc_web_console_api/models/views" - "net/http" - "strings" - - "github.com/gobuffalo/buffalo" - "github.com/gofrs/uuid" -) - -// Get "/lookupvmspecs" -func VmSpecLookupList(c buffalo.Context) error { - connectionName := &common.TbConnectionName{} - - paramProviderId := c.Params().Get("providerId") - paramRegionName := c.Params().Get("regionName") - log.Println("************provider ID : ", paramProviderId) - log.Println("************regionName : ", paramRegionName) - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ProviderID = paramProviderId - paramViewConnection.RegionName = paramRegionName - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - connectionName.ConnectionName = viewConnection.ConnectionName - cspVmSpecInfoList, respStatus := handler.LookupVmSpecInfoList(connectionName) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "CspVmSpecList": cspVmSpecInfoList, - })) -} - -// VmspecList default implementation. -func VmSpecList(c buffalo.Context) error { - log.Println("GetVmSpecList : ") - namespaceID := c.Session().Get("current_namespace_id").(string) - // TODO : defaultNameSpaceID 가 없으면 설정화면으로 보낼 것 - log.Println("namespaceID at vmspecList : ", namespaceID) - optionParam := c.Params().Get("option") - filterKeyParam := c.Params().Get("filterKey") - filterValParam := c.Params().Get("filterVal") - - paramConnectionName := c.Params().Get("connectionName") - - if optionParam == "id" { - vmSpecInfoList, respStatus := handler.GetVmSpecInfoListByID(namespaceID, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "VmSpecList": vmSpecInfoList, - })) - } else { - log.Println("option 값이 없어서 여기로 간다.") - - if !strings.EqualFold(paramConnectionName, "") && strings.EqualFold(filterKeyParam, "") { - filterKeyParam = "connectionName" - filterValParam = paramConnectionName - } - - vmSpecInfoList, respStatus := handler.GetVmSpecInfoListByOption(namespaceID, optionParam, filterKeyParam, filterValParam) - log.Println(vmSpecInfoList) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "VmSpecList": vmSpecInfoList, - })) - } -} - -func VmSpecGet(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - paramVmSpecId := c.Param("vmSpecId") - vmSpecInfo, respStatus := handler.GetVmSpecInfoData(namespaceID, paramVmSpecId) - - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ConnectionName = vmSpecInfo.ConnectionName - viewConnection, err := handler.GetViewConnection(paramViewConnection) - if err != nil { - // cb에서 정보는 가져왔으니 오류로 뱉지는 않기. - } else { - vmSpecInfo.ProviderID = viewConnection.ProviderID - vmSpecInfo.ProviderName = viewConnection.ProviderID - vmSpecInfo.RegionName = viewConnection.RegionName - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "VmSpec": vmSpecInfo, - })) -} - -func VmSpecReg(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - vmSpecReq := &tbmcir.TbSpecReq{} - vmSpecRegInfo := new(tbmcir.TbSpecInfo) - resultVmSpecInfo := new(tbmcir.TbSpecInfo) - - paramVMSpecregisteringMethod := c.Param("specregisteringMethod") - - respStatus := fwmodels.WebStatus{} - paramViewConnection := views.ViewCloudConnection{} - - if strings.EqualFold(paramVMSpecregisteringMethod, "registerWithInfo") { - if err := c.Bind(vmSpecRegInfo); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - paramViewConnection.ProviderID = vmSpecRegInfo.ProviderName - paramViewConnection.RegionName = vmSpecRegInfo.RegionName - - } else { - if err := c.Bind(vmSpecReq); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "error": "fail", - "status": "fail", - })) - } - paramViewConnection.ProviderID = vmSpecReq.ProviderID - paramViewConnection.RegionName = vmSpecReq.RegionName - paramViewConnection.ZoneName = vmSpecReq.ZoneName - } - - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - - log.Println("*************vmspeceq : ", vmSpecReq, "|*************namespaceID : ", namespaceID, "|**********viewconnection :", viewConnection, "|*************error : ", err) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - "error": "there is no available connection", - "status": "500", - })) - } - - if strings.EqualFold(paramVMSpecregisteringMethod, "registerWithInfo") { - vmSpecRegInfo.ConnectionName = viewConnection.ConnectionName - resultVmSpecInfo, respStatus = handler.RegVmSpecWithInfo(namespaceID, paramVMSpecregisteringMethod, vmSpecRegInfo) - } else { - vmSpecReq.ConnectionName = viewConnection.ConnectionName - resultVmSpecInfo, respStatus = handler.RegVmSpec(namespaceID, paramVMSpecregisteringMethod, vmSpecReq) - } - - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.Status = "C" - connectionMapping.ResourceType = "vmspec" - connectionMapping.ResourceID = resultVmSpecInfo.ID - connectionMapping.ResourceName = resultVmSpecInfo.Name - connectionMapping.CloudConnectionID = viewConnection.ID - connectionMapping.CredentialID = viewConnection.CredentialID - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - err = handler.SaveConnectionMapping(connectionMapping, c) - if err != nil { - // 실패시 생성한 vpc Resource 제거 - _, respStatus := handler.DelVMSpec(namespaceID, vmSpecReq.Name) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(500, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "VMSpec": resultVmSpecInfo, - })) -} - -func VmSpecDel(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - paramVmSpecId := c.Param("vmSpecId") - log.Println("***********paramVMSpecID : ") - log.Println(paramVmSpecId) - respMessage, respStatus := handler.DelVMSpec(namespaceID, paramVmSpecId) - - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - connectionMapping.ResourceType = "vmspec" - connectionMapping.ResourceID = paramVmSpecId - - usedConnectionMapping, err := handler.GetUsedConnection(connectionMapping) - - if err != nil { - // TODO : mapping table에 없을 때, 에러로 처리할 것인가? - // return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - // "error": respStatus.Message, - // "status": respStatus.StatusCode, - // })) - } else { - // 삭제 Row 추가 - usedConnectionMapping.ID = uuid.UUID{} - usedConnectionMapping.Status = "D" - - err = handler.SaveConnectionMapping(usedConnectionMapping, c) - - if err != nil { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": respMessage.Message, - "status": respMessage.StatusCode, - })) -} - -func FetchVmSpecList(c buffalo.Context) error { - log.Println("FetchVMSpecList : ") - - namespaceID := c.Session().Get("current_namespace_id").(string) - - // vmSpecInfoList, respStatus := service.FetchVmSpecInfoList(defaultNameSpaceID) - go handler.FetchVmSpecInfoListByAsync(namespaceID, c) - // if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - // return c.JSON(respStatus.StatusCode, map[string]interface{}{ - // "error": respStatus.Message, - // "status": respStatus.StatusCode, - // }) - // } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": http.StatusOK, - })) -} - -func FilterVmSpecList(c buffalo.Context) error { - log.Println("FilterVmspecList : ") - - namespaceID := c.Session().Get("current_namespace_id").(string) - - vmSpecRange := &tbmcir.FilterSpecsByRangeRequest{} - if err := c.Bind(vmSpecRange); err != nil { - log.Println(err) - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - vmSpecInfoList, respStatus := handler.FilterVmSpecInfoListByRange(namespaceID, vmSpecRange) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "VmSpecList": vmSpecInfoList, - })) -} - -// 추천 VMSpec 목록 조회 -func RecommendVmSpecList(c buffalo.Context) error { - mcisDeploymentPlan := &tbmcis.DeploymentPlan{} - if err := c.Bind(mcisDeploymentPlan); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(map[string]interface{}{ - "message": "fail", - "status": "fail", - })) - } - vmSpecList, _ := handler.GetRecommendVmSpecList(mcisDeploymentPlan) - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": 200, - "VmSpecList": vmSpecList, - })) -} diff --git a/mc_web_console_api/actions/_old/vpc.go b/mc_web_console_api/actions/_old/vpc.go deleted file mode 100644 index a47c511d..00000000 --- a/mc_web_console_api/actions/_old/vpc.go +++ /dev/null @@ -1,344 +0,0 @@ -package actions - -import ( - "log" - "net/http" - "strings" - - "github.com/gobuffalo/buffalo" - "github.com/gofrs/uuid" - - tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - "mc_web_console_api/handler" - "mc_web_console_api/models" - "mc_web_console_api/models/views" -) - -func VpcReg(c buffalo.Context) error { - // 현재 namespace 정보 가져오기 - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - vNetRegInfo := &tbmcir.TbVNetReq{} - if err := c.Bind(vNetRegInfo); err != nil { - return c.Render(http.StatusBadRequest, r.JSON(err)) - } - - // connection 조회 : namespace와 무관 . 얘도 bind 써도 되나? - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ProviderID = vNetRegInfo.ProviderID - paramViewConnection.RegionName = vNetRegInfo.RegionName - paramViewConnection.ZoneName = vNetRegInfo.ZoneName - viewConnection, err := handler.GetAvailableConnection(paramViewConnection, c) - if err != nil { - return c.Render(500, r.JSON(map[string]interface{}{ - //"error": "there is no available connection", - "error": err.Error(), - "status": "500", - })) - } - - // 사용할 connection set - vNetRegInfo.ConnectionName = viewConnection.ConnectionName - - // TB 등록 : NS를 ID로 보내고 있어서 에러나고 있음. http://54.180.86.138:1323/tumblebug/ns/g9qligtr8p/resources/vNet - resultVNetInfo, respStatus := handler.RegVpc(namespaceID, vNetRegInfo) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - // DB 등록 - // connectionUUID, err := uuid.FromString(connectionId) - // if err != nil { - // log.Println("connection uuid parsing failed : ", err) - // } - - // credentialUUID, err := uuid.FromString(credentialId) - // if err != nil { - // log.Println("credential uuid parsing failed : ", err) - // } - - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.Status = "C" - connectionMapping.ResourceType = "vpc" - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - connectionMapping.ResourceID = resultVNetInfo.ID - connectionMapping.ResourceName = resultVNetInfo.Name - connectionMapping.CloudConnectionID = viewConnection.ID - connectionMapping.CredentialID = viewConnection.CredentialID - err = handler.SaveConnectionMapping(connectionMapping, c) - if err != nil { - // 실패시 생성한 vpc Resource 제거 - _, respStatus := handler.DelVpc(namespaceID, resultVNetInfo.ID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - return c.Render(500, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "VNetInfo": resultVNetInfo, - })) -} - -func VpcDel(c buffalo.Context) error { - log.Println("VnetDel") - namespaceID := c.Session().Get("current_namespace_id").(string) - namespaceName := c.Session().Get("current_namespace").(string) - - paramVNetID := c.Param("vpcId") - - respMessage, respStatus := handler.DelVpc(namespaceID, paramVNetID) - - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - // Resource Mapping 에서 resource정보 조회(connection, credential) - connectionMapping := &models.CloudConnectionMapping{} - connectionMapping.NamespaceID = namespaceID - connectionMapping.NamespaceName = namespaceName - connectionMapping.ResourceType = "vpc" - connectionMapping.ResourceID = paramVNetID - - usedConnectionMapping, err := handler.GetUsedConnection(connectionMapping) - if err != nil { - // TODO : mapping table에 없을 때, 에러로 처리할 것인가? - // return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - // "error": respStatus.Message, - // "status": respStatus.StatusCode, - // })) - } else { - // 삭제 Row 추가 - usedConnectionMapping.Status = "D" - usedConnectionMapping.ID = uuid.UUID{} - err = handler.SaveConnectionMapping(usedConnectionMapping, c) - if err != nil { - return c.Render(respStatus.StatusCode, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - } - log.Println("DelVpc return") - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": respMessage.Message, - "status": respMessage.StatusCode, - })) -} - -// 단건 조회 by id -func VpcGet(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - paramVNetID := c.Param("vpcId") - vNetInfo, respStatus := handler.GetVpcData(namespaceID, paramVNetID) - - if respStatus.StatusCode == 500 { - return c.Render(http.StatusInternalServerError, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - paramViewConnection := views.ViewCloudConnection{} - paramViewConnection.ConnectionName = vNetInfo.ConnectionName - viewConnection, err := handler.GetViewConnection(paramViewConnection) - if err != nil { - // cb에서 정보는 가져왔으니 오류로 뱉지는 않기. - } else { - vNetInfo.ProviderID = viewConnection.ProviderID - vNetInfo.ProviderName = viewConnection.ProviderID - vNetInfo.RegionName = viewConnection.RegionName - } - - // - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus, - "VNetInfo": vNetInfo, - })) -} - -// VnetList default implementation. -func VpcList(c buffalo.Context) error { - namespaceID := c.Session().Get("current_namespace_id").(string) - - optionParam := c.Params().Get("option") - filterKeyParam := c.Params().Get("filterKey") - filterValParam := c.Params().Get("filterVal") - if optionParam == "id" { - vNetInfoList, respStatus := handler.GetVnetListByID(namespaceID, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "VNetList": vNetInfoList, // string 배열 리턴 - })) - } else { - vNetInfoList, respStatus := handler.GetVnetListByOption(namespaceID, optionParam, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "VNetList": vNetInfoList, //TbVnetInfo 배열 리턴 - })) - } -} - -// 해당 namespace의 Region내 vnet 목록 조회 -func VpcListByRegion(c buffalo.Context) error { - log.Println("VnetListByRegion") - namespaceID := c.Session().Get("current_namespace_id").(string) - - //optionParam := c.Param("option") - optionParam := c.Params().Get("option") - filterKeyParam := c.Params().Get("filterKey") - filterValParam := c.Params().Get("filterVal") - is_cb := c.Params().Get("is_cb") - - paramProviderID := c.Params().Get("providerId") - paramRegionName := c.Params().Get("regionName") - paramZoneName := c.Params().Get("zoneName") - paramConnectionName := c.Params().Get("connectionName") - - paramConnectionMap := map[string]string{} // 특정 connection 을 가져오기 위해 사용. - if !strings.EqualFold(paramConnectionName, "") { - paramConnectionMap["connectionName"] = paramConnectionName - } - - // 1. 해당 region에 등록 된 connection을 바탕으로 vpc목록을 cb-tb에 조회한 결과들을 붙여 return 할 것인가 - // 2. resourceMaping에 등록된 vpc 목록을 return할 것인가 - // 상세정보가 필요하면 1. 이름만 필요하면 2. - if is_cb == "N" { - //ListResourceByType : 해당 Resource의 connection 찾기 : views.ViewCloudConnection - vpcList, err := handler.ListResourceByType(namespaceID, paramConnectionMap, paramProviderID, paramRegionName, paramZoneName, "vpc") - if err != nil { - log.Println("VnetListByRegion err", err) - - return c.Render(500, r.JSON(map[string]interface{}{ - "error": err.Error(), - "status": "500", - })) - } - - // // ID만 가져오는 경우는 가져온 resource에서 vpcID만 추출하여 return - // if optionParam == "id" { - // returnVnetIds := []string{} - // for _, vpc := range vpcList { - // returnVnetIds = append(returnVnetIds, vpc.ResourceName) - // } - // return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - // "message": "success", - // "status": "200", - // "DefaultNameSpaceID": namespaceID, - // "VNetList": returnVnetIds, // string 배열 리턴 - // })) - // } - - // 상세정보가 필요한 경우는 사용된 connection 정보로 cb-tb 조회하여 연결 - usedConnectionMap := map[string]string{} - if paramConnectionName != "" { - usedConnectionMap[paramConnectionName] = paramConnectionName - } else { - for _, vpc := range vpcList { - usedConnectionMap[vpc.ConnectionName] = vpc.ConnectionName - } - } - returnVpcList := []tbmcir.TbVNetInfo{} - for _, val := range usedConnectionMap { - paramFilterKey := "connectionName" - paramFilterVal := val - vNetInfoList, respStatus := handler.GetVnetListByOption(namespaceID, optionParam, paramFilterKey, paramFilterVal) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - for _, item := range vNetInfoList { - item.ProviderID = paramProviderID - item.RegionName = paramRegionName - returnVpcList = append(returnVpcList, item) - } - //returnVpcList = append(returnVpcList, vNetInfoList...) - } - - log.Println("VnetListByRegion return ", returnVpcList) - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": "200", - "DefaultNameSpaceID": namespaceID, - "VNetList": returnVpcList, - })) - } - - log.Println("VnetListByRegion optionParam ", optionParam) - // is_cb=Y(default) cb-tb를 바로 호출하는 경우 - if optionParam == "id" { - vNetInfoList, respStatus := handler.GetVnetListByID(namespaceID, filterKeyParam, filterValParam) // TODO : GetVnetIdList 같은걸로 이름변경할 것 byID가 아니라 ID만 가져오는 기능임. - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "VNetList": vNetInfoList, // string 배열 리턴 - })) - } else { - log.Println("GetVnetListByOption") - if !strings.EqualFold(paramConnectionName, "") && strings.EqualFold(filterKeyParam, "") { - filterKeyParam = "connectionName" - filterValParam = paramConnectionName - } - vNetInfoList, respStatus := handler.GetVnetListByOption(namespaceID, optionParam, filterKeyParam, filterValParam) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "error": respStatus.Message, - "status": respStatus.StatusCode, - })) - } - - return c.Render(http.StatusOK, r.JSON(map[string]interface{}{ - "message": "success", - "status": respStatus.StatusCode, - "DefaultNameSpaceID": namespaceID, - "VNetList": vNetInfoList, //TbVnetInfo 배열 리턴 - })) - } - -} diff --git a/mc_web_console_api/actions/_old/websocket.go b/mc_web_console_api/actions/_old/websocket.go deleted file mode 100644 index ba6f1b8d..00000000 --- a/mc_web_console_api/actions/_old/websocket.go +++ /dev/null @@ -1,106 +0,0 @@ -package actions - -import ( - "log" - - "github.com/gobuffalo/buffalo" - - "mc_web_console_api/handler" - - "encoding/json" - "strconv" - "time" - - "github.com/gorilla/websocket" -) - -var ( - upgrader = websocket.Upgrader{ - ReadBufferSize: 1024, - WriteBufferSize: 1024, - } -) - -type pushMessage struct { - pushpush string -} - -// WebSocketDataList -// - -func WebSocketDataList(c buffalo.Context) error { - // Upgrade the incoming request to a WebSocket connection - ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil) - if err != nil { - log.Print("websocket upgrade:", err) - return err - } - defer ws.Close() - - t := time.Now() - ws.SetWriteDeadline(t.Add(time.Second * 1200)) - - for { - //messageType, message, err := ws.ReadMessage() - _, message, err := ws.ReadMessage() - if err != nil { - log.Println("read:", err) - break - } - var objmap map[string]interface{} - _ = json.Unmarshal(message, &objmap) - event := objmap["event"].(string) // event에 구분 : 요청은 open, req, close. 응답은 res로 한다. - - switch event { - case "open": // 화면이 처음 열렸을 때 - log.Println("websocket open:") - defaultTime := t.Add(time.Minute * -60) // 기본 조회시간은 현재시간 - 60분 - - socketDataList := handler.GetWebsocketMessageByProcessTime(defaultTime.UnixNano(), c) - log.Println(socketDataList) - returnMessage := map[string]interface{}{ - "event": "res", - "message": socketDataList, - "callTime": time.Now().UnixNano(), - } - - sendErr := ws.WriteJSON(returnMessage) - if sendErr != nil { - log.Println("ws send Err ", sendErr.Error()) - } - // log.Println("is socket working : open finished") - case "req": // 특정시간 이후 모두 조회. 조회할 시간이 parameter로 넘어온다. // key값이 unixTime으로 되어 있으므로 string -> int64 -> unixTime -> time - // sendData["data"] = objmap["data"] - log.Println("websocket req ", objmap) - sCallTime := objmap["callTime"].(string) - // log.Println("is socket working : req started") - nCallTime, nErr := strconv.ParseInt(sCallTime, 10, 64) - if nErr != nil { - log.Println("sCallTime err ", sCallTime) - d2 := t.Add(time.Minute * -5) - nCallTime = d2.UnixNano() - } - - uCallTime := time.Unix(0, nCallTime) - socketDataMap := handler.GetWebsocketMessageByProcessTime(uCallTime.UnixNano(), c) - returnMessage := map[string]interface{}{ - "event": "res", - "message": socketDataMap, - "callTime": time.Now().UnixNano(), - } - - sendErr := ws.WriteJSON(returnMessage) - if sendErr != nil { - log.Println("ws send Err ", sendErr.Error()) - } - // log.Println("is socket working : req finished") - // 마지막 조회 - case "close": // page 이동시 - log.Printf("ws.Close()") - ws.Close() - log.Printf("socket closed ") - } - - } - return err -} diff --git a/mc_web_console_api/actions/_old/worker.go b/mc_web_console_api/actions/_old/worker.go deleted file mode 100644 index 653e0d87..00000000 --- a/mc_web_console_api/actions/_old/worker.go +++ /dev/null @@ -1,49 +0,0 @@ -package actions - -import ( - "mc_web_console_api/fwmodels/webconsole" - "mc_web_console_api/handler" - "sync" - - "github.com/gobuffalo/buffalo/worker" -) - -var w worker.Worker -var wg sync.WaitGroup - -func init() { - w = App().Worker - w.Register("life_cycle_scheduler", LifeCycleScheduler) -} - -// func TestRegisterWorker(c buffalo.Context) error { -// //wg := &sync.WaitGroup{} - -// DoRegister() - -// return c.Render(http.StatusOK, r.JSON("success")) -// } -func LifeCycleScheduler(a worker.Args) error { - //var mcisLifeCycle *webconsole.McisLifeCycle - - mcisLifeCycle := a["mcisLifeCycle"].(*webconsole.McisLifeCycle) - - handler.McisLifeCycle(mcisLifeCycle) - - return nil -} - -func DoWork(m *webconsole.McisLifeCycle) { - // var mcisLifeCycle *webconsole.McisLifeCycle - // mcisLifeCycle.McisID = - // mcisLifeCycle.NameSpaceID = a["namespaceID"].(string) - a := map[string]interface{}{ - "action": "", - "mcisLifeCycle": m, - } - w.Perform(worker.Job{ - Queue: "defaut", - Handler: "life_cycle_scheduler", - Args: a, - }) -} diff --git a/mc_web_console_api/actions/app.go b/mc_web_console_api/actions/app.go index 3c8fc10e..546c6d56 100644 --- a/mc_web_console_api/actions/app.go +++ b/mc_web_console_api/actions/app.go @@ -1,6 +1,7 @@ package actions import ( + "log" "os" "sync" @@ -15,6 +16,7 @@ import ( i18n "github.com/gobuffalo/mw-i18n/v2" paramlogger "github.com/gobuffalo/mw-paramlogger" + "mc_web_console_api/handler/mciammanager" "mc_web_console_api/models" ) @@ -41,30 +43,85 @@ func App() *buffalo.App { app.Use(contenttype.Set("application/json")) app.Use(popmw.Transaction(models.DB)) - // middleware START // - // app.Use(AuthMiddleware) - // middleware END // + app.ANY("/alive", alive) apiPath := "/api" + + auth := app.Group(apiPath + "/auth") + auth.POST("/login", AuthLogin) + // auth.POST("/login/refresh", AuthLoginRefresh) + auth.POST("/logout", AuthLogout) + // auth.GET("/userinfo", AuthGetUserInfo) + api := app.Group(apiPath) + api.Use(session("")) api.GET("/{targetController}", GetRouteController) api.POST("/{targetController}", PostRouteController) - // DEBUG START // - if ENV == "development" { - debug := app.Group(apiPath + "/debug") - debug.ANY("/{targetfw}/{path:.+}", DebugApiCaller) - } - // DEBUG END // + role := app.Group("/test/role") + role.Use(session("")) + role.ANY("/alive", alive) + admin := app.Group("/test/admin") + admin.Use(session("admin")) + admin.ANY("/alive", alive) + + viewer := app.Group("/test/viewer") + viewer.Use(session("admin")) + viewer.ANY("/alive", alive) + + operator := app.Group("/test/operator") + operator.Use(session("admin")) + operator.ANY("/alive", alive) }) return app } +func alive(c buffalo.Context) error { + name := "" + roles := []string{} + sub := "" + upn := "" + if userName, ok := c.Value("PreferredUsername").(string); ok { + name = userName + } + if userRoles, ok := c.Value("RealmAccessRoles").([]string); ok { + roles = userRoles + } + if userSub, ok := c.Value("Sub").(string); ok { + sub = userSub + } + if userUpn, ok := c.Value("Upn").(string); ok { + upn = userUpn + } + + return c.Render(200, r.JSON(map[string]interface{}{ + "status": "OK", + "method": c.Request().Method, + "preferredUsername": name, + "realmAccessRoles": roles, + "Sub": sub, + "Upn": upn, + })) +} + func forceSSL() buffalo.MiddlewareFunc { return forcessl.Middleware(secure.Options{ SSLRedirect: ENV == "production", SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, }) } + +func session(role string) buffalo.MiddlewareFunc { + if MCIAM_USE { + return mciammanager.Middleware(role) + } else { + return func(next buffalo.Handler) buffalo.Handler { + return func(c buffalo.Context) error { + log.Println("NO SESSION MIDDLEWARE") + return next(c) + } + } + } +} diff --git a/mc_web_console_api/actions/auth.go b/mc_web_console_api/actions/auth.go index 03fd9d53..11511cc5 100644 --- a/mc_web_console_api/actions/auth.go +++ b/mc_web_console_api/actions/auth.go @@ -1,41 +1,94 @@ package actions import ( - "mc_web_console_api/actions/auth" - webconsole "mc_web_console_api/fwmodels/webconsole" - util "mc_web_console_api/util" + "mc_web_console_api/handler" + "mc_web_console_api/handler/mciammanager" + "mc_web_console_api/handler/self" + "net/http" + "strings" "github.com/gobuffalo/buffalo" + "github.com/gobuffalo/pop/v6" ) -func AuthLogin(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - if util.MCIAM_USE { - commonResponse := auth.AuthMcIamLogin(c, commonRequest) - return commonResponse +func AuthLogin(c buffalo.Context) error { + commonResponse := &handler.CommonResponse{} + commonRequest := &handler.CommonRequest{} + c.Bind(commonRequest) + + if MCIAM_USE { + commonResponse = mciammanager.McIamLogin(c, commonRequest) + if commonResponse.Status.StatusCode != 200 && commonResponse.Status.StatusCode != 201 { + return c.Render(commonResponse.Status.StatusCode, r.JSON(commonResponse)) + } + + tx := c.Value("tx").(*pop.Connection) + _, err := self.CreateUserSessFromResponseData(tx, commonResponse, commonRequest.Request.(map[string]interface{})["id"].(string)) + if err != nil { + return c.Render(http.StatusInternalServerError, r.JSON(map[string]interface{}{"error": err.Error()})) + } + // c.Session().Set("Authorization", sess.AccessToken) + return c.Render(commonResponse.Status.StatusCode, r.JSON(commonResponse)) + } else { + commonResponse = handler.CommonResponseStatusInternalServerError("NOT IMPL") + return c.Render(commonResponse.Status.StatusCode, r.JSON(commonResponse)) } - return webconsole.CommonResponseStatusInternalServerError(nil) } -func AuthLogout(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - if util.MCIAM_USE { - commonResponse := auth.AuthMcIamLogout(c, commonRequest) - return commonResponse +func AuthLoginRefresh(c buffalo.Context) error { + commonResponse := &handler.CommonResponse{} + commonRequest := &handler.CommonRequest{} + c.Bind(commonRequest) + + if MCIAM_USE { + commonResponse = mciammanager.McIamLoginRefresh(c, commonRequest) + } else { + commonResponse = handler.CommonResponseStatusInternalServerError("NOT IMPL") } - return webconsole.CommonResponseStatusInternalServerError(nil) + + return c.Render(commonResponse.Status.StatusCode, r.JSON(commonResponse)) } -func AuthGetUserInfo(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - if util.MCIAM_USE { - commonResponse := auth.AuthMcIamGetUserInfo(c, commonRequest) - return commonResponse +func AuthLogout(c buffalo.Context) error { + commonResponse := &handler.CommonResponse{} + commonRequest := &handler.CommonRequest{} + c.Bind(commonRequest) + + if MCIAM_USE { + accessToken := strings.TrimPrefix(c.Request().Header.Get("Authorization"), "Bearer ") + tx := c.Value("tx").(*pop.Connection) + rt, err := self.DestroyUserSessByAccesstokenforLogout(tx, accessToken) + if err != nil { + return c.Render(http.StatusInternalServerError, r.JSON(map[string]interface{}{"error": err.Error()})) + } + commonRequest := &handler.CommonRequest{ + Request: map[string]string{ + "refresh_token": rt, + }, + } + commonResponse = mciammanager.McIamLogout(c, commonRequest) + if commonResponse.Status.StatusCode != 200 && commonResponse.Status.StatusCode != 201 { + return c.Render(commonResponse.Status.StatusCode, r.JSON(commonResponse)) + } + // c.Session().Clear() + return c.Render(commonResponse.Status.StatusCode, r.JSON(commonResponse)) + } else { + commonResponse = handler.CommonResponseStatusInternalServerError("NOT IMPL") + return c.Render(commonResponse.Status.StatusCode, r.JSON(commonResponse)) } - return webconsole.CommonResponseStatusInternalServerError(nil) + } -func AuthGetUserValidate(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - if util.MCIAM_USE { - commonResponse := auth.AuthMcIamGetUserValidate(c, commonRequest) - return commonResponse +func AuthGetUserInfo(c buffalo.Context) error { + commonResponse := &handler.CommonResponse{} + commonRequest := &handler.CommonRequest{} + c.Bind(commonRequest) + + if MCIAM_USE { + commonResponse = mciammanager.McIamGetUserInfo(c, commonRequest) + } else { + commonResponse = handler.CommonResponseStatusInternalServerError("NOT IMPL") } - return webconsole.CommonResponseStatusInternalServerError(nil) + + return c.Render(commonResponse.Status.StatusCode, r.JSON(commonResponse)) } diff --git a/mc_web_console_api/actions/auth/mciammanagerauth.go b/mc_web_console_api/actions/auth/mciammanagerauth.go deleted file mode 100644 index 413a5537..00000000 --- a/mc_web_console_api/actions/auth/mciammanagerauth.go +++ /dev/null @@ -1,111 +0,0 @@ -package auth - -import ( - "log" - "mc_web_console_api/fwmodels/webconsole" - "mc_web_console_api/models" - "mc_web_console_api/util" - mcmodels "mc_web_console_common_models" - "net/http" - "strings" - - "github.com/gobuffalo/buffalo" - "github.com/gofrs/uuid" - "github.com/golang-jwt/jwt/v4" - "github.com/mitchellh/mapstructure" -) - -var ( - getAccesstokenEndPoint = "/api/auth/login" - accesstokenRefreshEndPoint = "/api/auth/login/refresh" - getUserInfoEndPoint = "/api/auth/userinfo" - getUserValidateEndPoint = "/api/auth/validate" - suspendAccesstokenEndPoint = "/api/auth/logout" -) - -func McIamJwtDecode(jwtToken string) jwt.MapClaims { - claims := jwt.MapClaims{} - jwt.NewParser().ParseWithClaims(jwtToken, claims, func(token *jwt.Token) (interface{}, error) { return "", nil }) - return claims -} - -func AuthMcIamLogin(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - commonResponse, err := webconsole.CommonCallerWithoutToken(http.MethodPost, util.MCIAMMANAGER, getAccesstokenEndPoint, commonRequest) - if err != nil { - log.Println(err) - return commonResponse - } - - accessTokenResponse := &mcmodels.AccessTokenResponse{} - if err := mapstructure.Decode(commonResponse.ResponseData, accessTokenResponse); err != nil { - return webconsole.CommonResponseStatusInternalServerError(err.Error()) - } - - jwtDecodd := McIamJwtDecode(accessTokenResponse.AccessToken) - targetSubject, _ := uuid.FromString(jwtDecodd["sub"].(string)) - usersess := &models.Usersession{ - ID: targetSubject, - AccessToken: accessTokenResponse.AccessToken, - ExpiresIn: accessTokenResponse.ExpiresIn, - RefreshToken: accessTokenResponse.RefreshToken, - RefreshExpiresIn: accessTokenResponse.RefreshExpiresIn, - } - - txerr := models.DB.Create(usersess) - if txerr != nil { - if strings.Contains(txerr.Error(), "SQLSTATE 23505") { // unique constraint violation catch - txerr = models.DB.Update(usersess) - if txerr != nil { - return webconsole.CommonResponseStatusInternalServerError(txerr) - } - } else { - return webconsole.CommonResponseStatusInternalServerError(txerr) - } - } - - return commonResponse -} - -func AuthMcIamLogout(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - headerAccessToken := c.Request().Header.Get("Authorization") - accessToken := strings.TrimPrefix(headerAccessToken, "Bearer ") - jwtDecoded := McIamJwtDecode(accessToken) - targetSubject, _ := uuid.FromString(jwtDecoded["sub"].(string)) - - usersess := &models.Usersession{} - txerr := models.DB.Find(usersess, targetSubject) - if txerr != nil { - return webconsole.CommonResponseStatusBadRequest(txerr.Error()) - } - - req := &webconsole.CommonRequest{ - Request: &mcmodels.AccessTokenRequest{ - RefreshToken: usersess.RefreshToken, - }, - } - commonResponse, err := webconsole.CommonCaller(http.MethodPost, util.MCIAMMANAGER, suspendAccesstokenEndPoint, req, c.Request().Header.Get("Authorization")) - if err != nil { - return webconsole.CommonResponseStatusInternalServerError(err.Error()) - } - txerr = models.DB.Destroy(usersess) - if txerr != nil { - return webconsole.CommonResponseStatusInternalServerError(txerr.Error()) - } - return commonResponse -} - -func AuthMcIamGetUserInfo(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - commonResponse, _ := webconsole.CommonCaller(http.MethodGet, util.MCIAMMANAGER, getUserInfoEndPoint, commonRequest, c.Request().Header.Get("Authorization")) - return commonResponse -} - -func AuthMcIamGetUserValidate(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - commonResponse, _ := webconsole.CommonCaller(http.MethodGet, util.MCIAMMANAGER, getUserValidateEndPoint, commonRequest, c.Request().Header.Get("Authorization")) - return commonResponse -} - -// // NOT IMPL -// func AuthMcIamRefresh(c buffalo.Context, commonReq *webconsole.CommonRequest) (*webconsole.CommonResponse, error) { -// commonResponse := &webconsole.CommonResponse{} -// return commonResponse, nil -// } diff --git a/mc_web_console_api/actions/auth/webconsoleauth.go b/mc_web_console_api/actions/auth/webconsoleauth.go deleted file mode 100644 index 8832b06d..00000000 --- a/mc_web_console_api/actions/auth/webconsoleauth.go +++ /dev/null @@ -1 +0,0 @@ -package auth diff --git a/mc_web_console_api/actions/debug.go b/mc_web_console_api/actions/debug.go deleted file mode 100644 index ed1c24fc..00000000 --- a/mc_web_console_api/actions/debug.go +++ /dev/null @@ -1,53 +0,0 @@ -package actions - -import ( - "encoding/json" - "io" - util "mc_web_console_api/util" - "net/http" - "strings" - - "github.com/gobuffalo/buffalo" -) - -func DebugApiCaller(c buffalo.Context) error { - targetfw := c.Param("targetfw") - - fwPath := "" - switch targetfw { - case "spider": - fwPath = util.SPIDER - case "tumblebug": - fwPath = util.TUMBLEBUG - case "mciammanager": - fwPath = util.MCIAMMANAGER - default: - // direct todo - return c.Render(http.StatusServiceUnavailable, r.JSON(map[string]interface{}{ - "status": http.StatusServiceUnavailable, - "err": "target framework err", - })) - } - - targetPath := strings.Replace(c.Request().URL.Path, "/api/debug/"+targetfw, "", 1) - targetPath = targetPath[:len(targetPath)-1] - fwPath += targetPath - - body, err := io.ReadAll(c.Request().Body) - if err != nil { - return c.Render(http.StatusServiceUnavailable, r.JSON(err.Error())) - } - - resp, err := util.CommonHttp(fwPath, body, c.Request().Method) - if err != nil { - return c.Render(http.StatusServiceUnavailable, r.JSON(err.Error())) - } - - var data interface{} - decoderErr := json.NewDecoder(resp.Body).Decode(&data) - if decoderErr != nil { - return c.Render(http.StatusServiceUnavailable, r.JSON(decoderErr.Error())) - } - - return c.Render(http.StatusOK, r.JSON(data)) -} diff --git a/mc_web_console_api/actions/demo/demouserinfo.go b/mc_web_console_api/actions/demo/demouserinfo.go deleted file mode 100644 index d52f7efe..00000000 --- a/mc_web_console_api/actions/demo/demouserinfo.go +++ /dev/null @@ -1,33 +0,0 @@ -package demo - -import ( - "mc_web_console_api/fwmodels/webconsole" - "mc_web_console_api/util" - "net/http" - "strings" - - "github.com/gobuffalo/buffalo" - "github.com/golang-jwt/jwt/v4" -) - -func mcIamJwtDecode(jwtToken string) jwt.MapClaims { - claims := jwt.MapClaims{} - jwt.NewParser().ParseWithClaims(jwtToken, claims, func(token *jwt.Token) (interface{}, error) { return "", nil }) - return claims -} - -func DemoGetuserinfo(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - commonResponse := &webconsole.CommonResponse{} - headerAccessToken := c.Request().Header.Get("Authorization") - accessToken := strings.TrimPrefix(headerAccessToken, "Bearer ") - jwtDecoded := mcIamJwtDecode(accessToken) - - commonResponse.ResponseData = jwtDecoded - - return commonResponse -} - -func DemoGetuserCred(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - commonResponse, _ := webconsole.CommonCaller(http.MethodGet, util.MCIAMMANAGER, "/api/auth/securitykey", commonRequest, c.Request().Header.Get("Authorization")) - return commonResponse -} diff --git a/mc_web_console_api/actions/env.go b/mc_web_console_api/actions/env.go new file mode 100644 index 00000000..2a81aced --- /dev/null +++ b/mc_web_console_api/actions/env.go @@ -0,0 +1,12 @@ +package actions + +import ( + "os" + "strconv" +) + +func init() { + MCIAM_USE, _ = strconv.ParseBool(os.Getenv("MCIAM_USE")) +} + +var MCIAM_USE = false // MC-IAM-MANAGER 사용여부, init 에서 재정의 diff --git a/mc_web_console_api/actions/mcis.go b/mc_web_console_api/actions/mcis.go new file mode 100644 index 00000000..d02266e0 --- /dev/null +++ b/mc_web_console_api/actions/mcis.go @@ -0,0 +1,124 @@ +package actions + +import ( + "fmt" + "mc_web_console_api/handler" + "mc_web_console_api/handler/mcinframanager" + + "github.com/gobuffalo/buffalo" +) + +// MCIS 목록 조회 +func GetMcisList(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraGetMcisList(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// MCIS 단건 조회 +func GetMcis(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraGetMcis(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// MCIS 생성 +func CreateMcis(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraCreateMcis(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// MCIS 삭제 +func DeleteMcis(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraDeleteMcis(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// Dynamic MCIS 생성 +func CreateDynamicMcis(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraCreateDynamicMcis(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// 특정 ns에 vpc, securitygroup, sshkey 등 default resource를 생성 +func GetLoadDefaultResource(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraGetLoadDefaultResouce(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func DelDefaultResource(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraDeleteDefaultResouce(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func McisRecommendVm(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraMcisRecommendVm(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func McisDynamicCheckRequest(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraMcisDynamicCheckRequest(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// MCIS 내 모든 VM에 command 실행 +func CmdMCIS(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraCmdMCIS(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func ControlMcis(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraControlMcis(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func CreateMcisVmDynamic(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraMcisVmDynamic(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} diff --git a/mc_web_console_api/actions/resource.go b/mc_web_console_api/actions/resource.go new file mode 100644 index 00000000..7ea250df --- /dev/null +++ b/mc_web_console_api/actions/resource.go @@ -0,0 +1,206 @@ +package actions + +import ( + "fmt" + "mc_web_console_api/handler" + "mc_web_console_api/handler/mcinframanager" + + "github.com/gobuffalo/buffalo" +) + +// VPC 목록 조회 +func GetVPCList(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraGetVPCList(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// VPC 단건 조회 +func GetVPC(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraGetVPC(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// VPC 생성 +func CreateVPC(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraCreateVPC(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// VPC 삭제 +func DeleteVPC(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraDeleteVPC(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func DeleteAllVPC(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraDeleteAllVPC(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// VPC 목록 조회 +func GetSecurityGroupList(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraGetSecurityGroupList(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// SG 단건 조회 +func GetSecurityGroup(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraGetSecurityGroup(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// SG 생성 +func CreateSecurityGroup(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraCreateSecurityGroup(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func DeleteSecurityGroup(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraDeleteSecurityGroup(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func DeleteAllSecurityGroup(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraDeleteAllSecurityGroup(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func GetVmSpecList(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraGetVmSpecList(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// Virtual machine Spec +func GetVmSpec(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraGetVmSpec(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func CreateVmSpec(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraCreateVmSpec(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func DeleteVmSpec(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraDeleteVmSpec(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func DeleteAllVmSpec(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraDeleteAllVmSpec(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func GetCommonVmSpecList(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraGetCommonVmSpecList(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func GetCommonVmSpec(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraGetCommonVmSpec(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func GetResourceCommonSpec(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraGetResourceCommonSpec(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func GetConnConfigListByType(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraGetConnConfigListByType(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func GetResourceList(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraGetResourceList(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +func GetResource(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mcinframanager.InfraGetResource(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} diff --git a/mc_web_console_api/actions/routesinfo.go b/mc_web_console_api/actions/routesinfo.go index bd915daa..88efc6d7 100644 --- a/mc_web_console_api/actions/routesinfo.go +++ b/mc_web_console_api/actions/routesinfo.go @@ -3,15 +3,15 @@ package actions import ( "errors" "log" + "mc_web_console_api/handler" + "mc_web_console_api/handler/mciammanager" + + "mc_web_console_api/handler/mcinframanager" + "mc_web_console_api/handler/self" "net/http" "reflect" "strings" - demo "mc_web_console_api/actions/demo" - tumblebug "mc_web_console_api/actions/tumblebug" - webconsole "mc_web_console_api/fwmodels/webconsole" - "mc_web_console_api/models" - "github.com/gobuffalo/buffalo" ) @@ -27,42 +27,123 @@ type actions struct{} // case문에서 controller이름 추출하여 controller 호출 func PostRouteController(c buffalo.Context) error { log.Println("#### PostRouteController ") - commonRequest := &webconsole.CommonRequest{} + log.Println("User Role is : ", c.Data()["roles"]) + + commonRequest := &handler.CommonRequest{} c.Bind(commonRequest) targetController := strings.ToLower(c.Param("targetController")) log.Printf("== targetController\t:[ %s ]\n", targetController) log.Printf("== commonRequest\t:\n%+v\n\n", commonRequest) - commonResponse := &webconsole.CommonResponse{} + commonResponse := &handler.CommonResponse{} switch targetController { + + // MCIS Mng Area + case "getmcislist": - commonResponse = tumblebug.GetMCISList(c, commonRequest) + commonResponse = GetMcisList(c, commonRequest) case "getmcis": - commonResponse = tumblebug.GetMCIS(c, commonRequest) + commonResponse = GetMcis(c, commonRequest) case "delmcis": - commonResponse = tumblebug.DelMCIS(c, commonRequest) + commonResponse = DeleteMcis(c, commonRequest) case "createmcis": - commonResponse = tumblebug.CreateMCIS(c, commonRequest) - - case "authlogin": - commonResponse = AuthLogin(c, commonRequest) - case "authlogout": - commonResponse = AuthLogout(c, commonRequest) - case "authgetuserinfo": - commonResponse = AuthGetUserInfo(c, commonRequest) - case "authgetuservalidate": - commonResponse = AuthGetUserValidate(c, commonRequest) - + commonResponse = CreateMcis(c, commonRequest) + case "createdynamicmcis": + commonResponse = CreateDynamicMcis(c, commonRequest) + case "getloaddefaultresource": + commonResponse = GetLoadDefaultResource(c, commonRequest) + case "deldefaultresources": + commonResponse = DelDefaultResource(c, commonRequest) + case "mcisrecommendvm": + commonResponse = McisRecommendVm(c, commonRequest) + case "mcisdynamiccheckrequest": + commonResponse = McisDynamicCheckRequest(c, commonRequest) + case "sendcommandtomcis": + commonResponse = CmdMCIS(c, commonRequest) + case "controllifecycle": + commonResponse = ControlMcis(c, commonRequest) + case "getimageid": + commonResponse = mcinframanager.InfraGetPublicImage(c, commonRequest) + case "disklookup": + commonResponse, _ = self.DiskLookup(c, commonRequest) + case "createvmdynamic": + commonResponse = CreateMcisVmDynamic(c, commonRequest) + // MCIS Mng Area end + + // workspace mng area case "getworkspacebyuserid": - commonResponse = GetWorkspaceByUserId(c, commonRequest) - - case "demogetuserinfo": - commonResponse = demo.DemoGetuserinfo(c, commonRequest) - case "demogetusercred": - commonResponse = demo.DemoGetuserCred(c, commonRequest) - + commonResponse = GetWorkspaceByuserId(c, commonRequest) + case "getworkspacelist": + commonResponse = GetWorkspacelist(c, commonRequest) + case "getworkspace": + commonResponse = GetWorkspace(c, commonRequest) + case "createworkspace": + commonResponse = CreateWorkspace(c, commonRequest) + case "deleteworkspace": + commonResponse = DeleteWorkspace(c, commonRequest) + + // workspace, project mapping + case "getworkspaceuserrolemappingbyworkspaceuser": + commonResponse = mciammanager.McIamGetworkspaceuserrolemappingbyworkspaceuser(c, commonRequest) + case "getworkspaceuserrolemappingbyuser": + commonResponse = mciammanager.McIamGetworkspaceuserrolemappingbyuser(c, commonRequest) + + case "projectlistbyworkspaceid": + commonResponse = GetProject(c, commonRequest) + + // // workspace mng area + // case "demogetuserinfo": + // commonResponse = demo.DemoGetuserinfo(c, commonRequest) + // case "demogetusercred": + // commonResponse = demo.DemoGetuserCred(c, commonRequest) + + // settings resources + case "getvpclist": + commonResponse = GetVPCList(c, commonRequest) + case "getvpc": + commonResponse = GetVPC(c, commonRequest) + case "createvpc": + commonResponse = CreateVPC(c, commonRequest) + case "deletevpc": + commonResponse = DeleteVPC(c, commonRequest) + case "deleteallvpc": + commonResponse = DeleteAllVPC(c, commonRequest) + case "getsecuritygrouplist": + commonResponse = GetSecurityGroupList(c, commonRequest) + case "getsecuritygroup": + commonResponse = GetSecurityGroup(c, commonRequest) + case "createsecuritygroup": + commonResponse = CreateSecurityGroup(c, commonRequest) + case "deletesecuritygroup": + commonResponse = DeleteSecurityGroup(c, commonRequest) + case "deleteallsecuritygroup": + commonResponse = DeleteAllSecurityGroup(c, commonRequest) + case "getvmspeclist": + commonResponse = GetVmSpecList(c, commonRequest) + case "getvmspec": + commonResponse = GetVmSpec(c, commonRequest) + case "createvmspec": + commonResponse = CreateVmSpec(c, commonRequest) + case "deletevmspec": + commonResponse = DeleteVmSpec(c, commonRequest) + case "deleteallvmspec": + commonResponse = DeleteAllVmSpec(c, commonRequest) + + case "getcommonvmspeclist": + commonResponse = GetCommonVmSpecList(c, commonRequest) + case "getcommonvmspec": + commonResponse = GetCommonVmSpec(c, commonRequest) + case "getresourcecommonspec": + commonResponse = GetResourceCommonSpec(c, commonRequest) + case "getconnconfiglistbytype": + commonResponse = GetConnConfigListByType(c, commonRequest) + + case "getresourcelist": + commonResponse = GetResourceList(c, commonRequest) + case "getresource": + commonResponse = GetResource(c, commonRequest) default: - commonResponse = webconsole.CommonResponseStatusNotFound("NO MATCH targetController") + commonResponse = handler.CommonResponseStatusNotFound("NO MATCH targetController") return c.Render(commonResponse.Status.StatusCode, r.JSON(commonResponse)) } @@ -75,6 +156,7 @@ func GetRouteController(c buffalo.Context) error { // target controller 이름. log.Println("in RouteGetController") + log.Println("User Role is : ", c.Data()["roles"]) // path param추출 path := c.Request().URL.Path @@ -109,7 +191,7 @@ func GetRouteController(c buffalo.Context) error { // switch commonRequest.TargetController { // case "McisList":// Get Type // // - // mcisList, respStatus := tumblebug.TbMcisList(commonRequest) + // mcisList, respStatus := mcinframanager.TbMcisList(commonRequest) // commonResponse.ResponseData = mcisList // commonResponse.Status = respStatus // case "McisReg":// Post Type @@ -143,89 +225,89 @@ func GetRouteController(c buffalo.Context) error { } // 관리자 설정 -func RoutesManager(app *buffalo.App) *buffalo.App { - - // TODO : DB에서 path와 handler를 가져오도록 - // 1. handler 구현한 뒤에 화면을 통해 db에 등록하는 process를 가져가도록 - // 2. 화면이 있으면 xxxform, json의 경우에는 /api/xxx 로 경로명 지정 - // ex ) "/api/<카테고리대분류>/<리소스>/<정의>" / "/<카테고리대분류>/<리소스>/mngform/" - - // ID uuid.UUID `json:"id" db:"id"` - // Method string `json:"method" db:"method"` - // Path string `json:"path" db:"path"` - // HandlerName string `json:"handler_name" db:"handler_name"` - // ResourceName string `json:"resource_name" db:"resource_name"` - // PathName string `json:"path_name" db:"path_name"` - // Aliases string `json:"aliases" db:"aliases"` - // CreatedAt time.Time `json:"created_at" db:"created_at"` - // UpdatedAt time.Time `json:"updated_at" db:"updated_at"` - - // routerList := []models.RouteInfo{ - // {Path: "/home1", HandlerName: "GetHome", Method: "GET"}, - // {Path: "/about1", HandlerName: "AboutHandler", Method: "GET"}, - // {Path: "/settings/resources/vpc/mngform", HandlerName: "VpcMngForm", Method: "GET"}, - - // {Path: "/settings/resources/vpc/", HandlerName: "vpcList", Method: "GET"}, - // {Path: "/settings/resources/vpc/", HandlerName: "vpcReg", Method: "POST"}, - // {Path: "/settings/resources/vpc/id/{vNetId}", HandlerName: "vpcGet", Method: "GET"}, - // {Path: "/settings/resources/vpc/id/{vNetId}", HandlerName: "vpcDel", Method: "DELETE"}, - // {Path: "/settings/resources/vpc/region", HandlerName: "vpcListByRegion", Method: "DELETE"}, - // } - - routerList := models.RouteInfoes{} - - //err := models.DB.Find(&resultCredential, credential.ID) - //if err != nil { - // return resultCredential, errors.WithStack(err) - //} - - query := models.DB.Q() - err := query.All(&routerList) - if err != nil { - log.Println("query err ", err) - return app - } - - for _, router := range routerList { - //log.Println(router) - // handlerFunction은 (a actions) function명 으로 정의 해야 함. - handlerFunc := getHandlerFuncByName(router.HandlerName) - if handlerFunc == nil { - log.Println(router.HandlerName + " Handler not found") - log.Println(router) - continue - } - //log.Println(router) - log.Println(router.Path + " : " + router.PathName + " : " + router.Method) - //log.Println(handlerFunc) - // 라우터 등록 - - switch router.Method { - case "GET": - app.GET(router.Path, handlerFunc).Name(router.PathName) - case "POST": - app.POST(router.Path, handlerFunc).Name(router.PathName) - case "PUT": - app.PUT(router.Path, handlerFunc).Name(router.PathName) - case "PATCH": - app.PATCH(router.Path, handlerFunc).Name(router.PathName) - case "HEAD": - app.HEAD(router.Path, handlerFunc).Name(router.PathName) - case "OPTIONS": - app.OPTIONS(router.Path, handlerFunc).Name(router.PathName) - case "DELETE": - app.DELETE(router.Path, handlerFunc).Name(router.PathName) - default: - log.Println(" any begin~~~~~~~~~~~~~~~~~~~~~~~") - log.Println(router) - log.Println(" any end ~~~~~~~~~~~~~~~~~~~~~~~") - app.ANY(router.Path, handlerFunc) - } - - } - - return app -} +// func RoutesManager(app *buffalo.App) *buffalo.App { + +// // TODO : DB에서 path와 handler를 가져오도록 +// // 1. handler 구현한 뒤에 화면을 통해 db에 등록하는 process를 가져가도록 +// // 2. 화면이 있으면 xxxform, json의 경우에는 /api/xxx 로 경로명 지정 +// // ex ) "/api/<카테고리대분류>/<리소스>/<정의>" / "/<카테고리대분류>/<리소스>/mngform/" + +// // ID uuid.UUID `json:"id" db:"id"` +// // Method string `json:"method" db:"method"` +// // Path string `json:"path" db:"path"` +// // HandlerName string `json:"handler_name" db:"handler_name"` +// // ResourceName string `json:"resource_name" db:"resource_name"` +// // PathName string `json:"path_name" db:"path_name"` +// // Aliases string `json:"aliases" db:"aliases"` +// // CreatedAt time.Time `json:"created_at" db:"created_at"` +// // UpdatedAt time.Time `json:"updated_at" db:"updated_at"` + +// // routerList := []models.RouteInfo{ +// // {Path: "/home1", HandlerName: "GetHome", Method: "GET"}, +// // {Path: "/about1", HandlerName: "AboutHandler", Method: "GET"}, +// // {Path: "/settings/resources/vpc/mngform", HandlerName: "VpcMngForm", Method: "GET"}, + +// // {Path: "/settings/resources/vpc/", HandlerName: "vpcList", Method: "GET"}, +// // {Path: "/settings/resources/vpc/", HandlerName: "vpcReg", Method: "POST"}, +// // {Path: "/settings/resources/vpc/id/{vNetId}", HandlerName: "vpcGet", Method: "GET"}, +// // {Path: "/settings/resources/vpc/id/{vNetId}", HandlerName: "vpcDel", Method: "DELETE"}, +// // {Path: "/settings/resources/vpc/region", HandlerName: "vpcListByRegion", Method: "DELETE"}, +// // } + +// routerList := models.RouteInfoes{} + +// //err := models.DB.Find(&resultCredential, credential.ID) +// //if err != nil { +// // return resultCredential, errors.WithStack(err) +// //} + +// query := models.DB.Q() +// err := query.All(&routerList) +// if err != nil { +// log.Println("query err ", err) +// return app +// } + +// for _, router := range routerList { +// //log.Println(router) +// // handlerFunction은 (a actions) function명 으로 정의 해야 함. +// handlerFunc := getHandlerFuncByName(router.HandlerName) +// if handlerFunc == nil { +// log.Println(router.HandlerName + " Handler not found") +// log.Println(router) +// continue +// } +// //log.Println(router) +// log.Println(router.Path + " : " + router.PathName + " : " + router.Method) +// //log.Println(handlerFunc) +// // 라우터 등록 + +// switch router.Method { +// case "GET": +// app.GET(router.Path, handlerFunc).Name(router.PathName) +// case "POST": +// app.POST(router.Path, handlerFunc).Name(router.PathName) +// case "PUT": +// app.PUT(router.Path, handlerFunc).Name(router.PathName) +// case "PATCH": +// app.PATCH(router.Path, handlerFunc).Name(router.PathName) +// case "HEAD": +// app.HEAD(router.Path, handlerFunc).Name(router.PathName) +// case "OPTIONS": +// app.OPTIONS(router.Path, handlerFunc).Name(router.PathName) +// case "DELETE": +// app.DELETE(router.Path, handlerFunc).Name(router.PathName) +// default: +// log.Println(" any begin~~~~~~~~~~~~~~~~~~~~~~~") +// log.Println(router) +// log.Println(" any end ~~~~~~~~~~~~~~~~~~~~~~~") +// app.ANY(router.Path, handlerFunc) +// } + +// } + +// return app +// } // Get the handler function by its name func getHandlerFuncByName(handlerName string) buffalo.Handler { diff --git a/mc_web_console_api/actions/tumblebug/mcismng.go b/mc_web_console_api/actions/tumblebug/mcismng.go deleted file mode 100644 index 0ffed8a3..00000000 --- a/mc_web_console_api/actions/tumblebug/mcismng.go +++ /dev/null @@ -1,33 +0,0 @@ -package tumblebug - -import ( - "mc_web_console_api/fwmodels/webconsole" - "mc_web_console_api/util" - "net/http" - - "github.com/gobuffalo/buffalo" -) - -func GetMCISList(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - endPoint := "/ns/{nsId}/mcis" - commonResponse, _ := webconsole.CommonCaller(http.MethodGet, util.TUMBLEBUG, endPoint, commonRequest, webconsole.TBAuthentication()) - return commonResponse -} - -func GetMCIS(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - endPoint := "/ns/{nsId}/mcis/{mcisId}" - commonResponse, _ := webconsole.CommonCaller(http.MethodGet, util.TUMBLEBUG, endPoint, commonRequest, webconsole.TBAuthentication()) - return commonResponse -} - -func DelMCIS(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - endPoint := "/ns/{nsId}/mcis/{mcisId}" - commonResponse, _ := webconsole.CommonCaller(http.MethodDelete, util.TUMBLEBUG, endPoint, commonRequest, webconsole.TBAuthentication()) - return commonResponse -} - -func CreateMCIS(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - endPoint := "/ns/{nsId}/mcis" - commonResponse, _ := webconsole.CommonCaller(http.MethodPost, util.TUMBLEBUG, endPoint, commonRequest, webconsole.TBAuthentication()) - return commonResponse -} diff --git a/mc_web_console_api/actions/workspace.go b/mc_web_console_api/actions/workspace.go index 0a1659f0..f208f38f 100644 --- a/mc_web_console_api/actions/workspace.go +++ b/mc_web_console_api/actions/workspace.go @@ -1,21 +1,82 @@ package actions import ( - "mc_web_console_api/actions/workspace" - "mc_web_console_api/fwmodels/webconsole" - util "mc_web_console_api/util" + "fmt" + "log" + "mc_web_console_api/handler" + "mc_web_console_api/handler/mciammanager" "github.com/gobuffalo/buffalo" ) -// 사용자의 workspace 목록 조회 -// mciammamager를 사용하지 않으면 default 를 return -func GetWorkspaceByUserId(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - if util.MCIAM_USE { - commonResponse := workspace.McIamGetWorkspaceByUserId(c, commonRequest) +func GetWorkspaceByuserId(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + // token에서 userId 추출 + userId := c.Value("PreferredUsername").(string) + //userId, _ := jwtDecoded["preferred_username"].(string) + log.Println("UserId ", userId) + pathParams := make(map[string]string) + // pathParams := map[string]string{ + // "userId": userId, + // } + pathParams["userId"] = userId + + req := &handler.CommonRequest{ + PathParams: pathParams, + } + + commonResponse := mciammanager.McIamGetworkspaceuserrolemappingbyworkspaceuser(c, req) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// Workspace 목록 조회 +func GetWorkspacelist(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mciammanager.McIamGetworkspacelist(c, commonRequest) + fmt.Println(commonResponse) return commonResponse - } else { - commonResponse := workspace.WebconsoleGetWorkspaceByUserId(c, commonRequest) + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// Workspace 단건 조회 +func GetWorkspace(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mciammanager.McIamGetworkspace(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// workspace 생성 +func CreateWorkspace(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mciammanager.McIamCreateworkspace(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// workspace 삭제 +func DeleteWorkspace(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mciammanager.McIamDeleteworkspace(c, commonRequest) + fmt.Println(commonResponse) + return commonResponse + } + return handler.CommonResponseStatusInternalServerError(nil) +} + +// Project 단건 조회 +func GetProject(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + if MCIAM_USE { + commonResponse := mciammanager.McIamGetworkspaceprojectmappingbyworkspace(c, commonRequest) + fmt.Println(commonResponse) return commonResponse } + return handler.CommonResponseStatusInternalServerError(nil) } diff --git a/mc_web_console_api/actions/workspace/mciammanagerworkspace.go b/mc_web_console_api/actions/workspace/mciammanagerworkspace.go deleted file mode 100644 index 31963534..00000000 --- a/mc_web_console_api/actions/workspace/mciammanagerworkspace.go +++ /dev/null @@ -1,36 +0,0 @@ -package workspace - -import ( - "mc_web_console_api/actions/auth" - "mc_web_console_api/fwmodels/webconsole" - "mc_web_console_api/util" - "net/http" - "strings" - - "github.com/gobuffalo/buffalo" -) - -var ( - getWorkspaceByUserIdEndPoint = "/api/ws/user/{userid}" -) - -func McIamGetWorkspaceByUserId(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - headerAccessToken := c.Request().Header.Get("Authorization") - accessToken := strings.TrimPrefix(headerAccessToken, "Bearer ") - jwtDecoded := auth.McIamJwtDecode(accessToken) - userId, _ := jwtDecoded["preferred_username"].(string) - - pathParams := make(map[string]string) - pathParams["userid"] = userId - - req := &webconsole.CommonRequest{ - PathParams: pathParams, - } - - commonResponse, err := webconsole.CommonCaller(http.MethodGet, util.MCIAMMANAGER, getWorkspaceByUserIdEndPoint, req, c.Request().Header.Get("Authorization")) - if err != nil { - return webconsole.CommonResponseStatusInternalServerError(err.Error()) - } - - return commonResponse -} diff --git a/mc_web_console_api/actions/workspace/webconsoleworkspace.go b/mc_web_console_api/actions/workspace/webconsoleworkspace.go deleted file mode 100644 index f5672e60..00000000 --- a/mc_web_console_api/actions/workspace/webconsoleworkspace.go +++ /dev/null @@ -1,29 +0,0 @@ -package workspace - -import ( - "mc_web_console_api/actions/auth" - "mc_web_console_api/fwmodels/webconsole" - "strings" - - "github.com/gobuffalo/buffalo" -) - -func WebconsoleGetWorkspaceByUserId(c buffalo.Context, commonRequest *webconsole.CommonRequest) *webconsole.CommonResponse { - headerAccessToken := c.Request().Header.Get("Authorization") - accessToken := strings.TrimPrefix(headerAccessToken, "Bearer ") - jwtDecoded := auth.McIamJwtDecode(accessToken) - userId, _ := jwtDecoded["preferred_username"].(string) - - pathParams := make(map[string]string) - pathParams["userid"] = userId - - defualtWorkspace := map[string]string{ - "workspaceId": "00000000-0000-0000-0000-000000000000", - "workspaceName": "DefaultWorkspace", - "description": "DefaultWorkspace", - "projectList": "", - } - commonResponse := webconsole.CommonResponseStatusOK(defualtWorkspace) - - return commonResponse -} diff --git a/mc_web_console_api/docs/docs.go b/mc_web_console_api/docs/docs.go deleted file mode 100644 index 34e557fb..00000000 --- a/mc_web_console_api/docs/docs.go +++ /dev/null @@ -1,2941 +0,0 @@ -// Code generated by swaggo/swag. DO NOT EDIT. - -package docs - -import "github.com/swaggo/swag" - -const docTemplate = `{ - "schemes": {{ marshal .Schemes }}, - "swagger": "2.0", - "info": { - "description": "{{escape .Description}}", - "title": "{{.Title}}", - "contact": { - "name": " ", - "url": "https://github.com/ " - }, - "license": {}, - "version": "{{.Version}}" - }, - "host": "{{.Host}}", - "basePath": "{{.BasePath}}", - "paths": { - "/adminconfig/category/mngform/": { - "get": { - "description": "[CategoryMngForm] Category 설정 폼을 렌더링합니다.", - "produces": [ - "text/html" - ], - "tags": [ - "adminconfig" - ], - "summary": "Category 설정 폼 렌더링", - "responses": { - "200": { - "description": "adminconfig/categorymng/mngform.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/adminconfig/config/mngform/": { - "get": { - "description": "[AdminMngForm] Admin 관리자 설정 폼을 렌더링합니다. : not implement -- 아직 기획된바 없음.", - "produces": [ - "text/html" - ], - "tags": [ - "adminconfig" - ], - "summary": "관리자 설정 폼 렌더링 : not implement -- 아직 기획된바 없음.", - "responses": { - "200": { - "description": "adminconfig/regiongroup/mngform.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/adminconfig/menu/mngform/": { - "get": { - "description": "[MenuMngForm] Menu 설정 폼을 렌더링합니다.", - "produces": [ - "text/html" - ], - "tags": [ - "adminconfig" - ], - "summary": "Menu 설정 폼 렌더링", - "responses": { - "200": { - "description": "adminconfig/menumng/mngform.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/api/adminconfig/category/": { - "get": { - "security": [ - { - "CSRFTokenHeader": [] - } - ], - "description": "[CategoryList] categoryName을 받아 categoryList를 반환합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Category 리스트 조회", - "parameters": [ - { - "type": "string", - "description": "categoryName", - "name": "categoryName", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{\"message\":\"success\",\"status\":respStatus.StatusCode,\"regionGroup\":categoryList,}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'respStatus.Message','error':'respStatus.Message'}", - "schema": { - "type": "string" - } - } - } - }, - "post": { - "description": "[RegCategory] 카테고리를 등록합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Category 등록", - "parameters": [ - { - "description": "models.Category", - "name": "Category", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Category" - } - } - ], - "responses": { - "200": { - "description": "{'message': 'success', 'status': 200}", - "schema": { - "type": "string" - } - } - } - }, - "delete": { - "description": "[CategoryDel] 카테고리를 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Category 삭제", - "parameters": [ - { - "description": "models.Category", - "name": "Category", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Category" - } - } - ], - "responses": { - "200": { - "description": "{'message': 'success', 'status': 200}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/adminconfig/category/id/{categoryName}/": { - "get": { - "security": [ - { - "CSRFTokenHeader": [] - } - ], - "description": "[CategoryGet] categoryName을 받아 category 단건을 반환합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Category 단건 조회", - "parameters": [ - { - "type": "string", - "description": "categoryName", - "name": "categoryName", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','category':'category',}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'errors.WithStack(err)'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/adminconfig/menu/": { - "get": { - "description": "[MenuList] menuId, menuName, menuAlias, categoryId 중 순서로 마지막 한개를 받아 메뉴 리스트를 반환합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Menu 리스트 조회", - "parameters": [ - { - "type": "string", - "description": "menuId", - "name": "menuId", - "in": "query" - }, - { - "type": "string", - "description": "menuName", - "name": "menuName", - "in": "query" - }, - { - "type": "string", - "description": "menuAlias", - "name": "menuAlias", - "in": "query" - }, - { - "type": "string", - "description": "categoryId", - "name": "categoryId", - "in": "query" - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200', 'menuList': 'menuList'}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'errors.WithStack(err)'}", - "schema": { - "type": "string" - } - } - } - }, - "put": { - "description": "[UpdateMenu] models.Menu를 받아 메뉴를 단건 업데이트합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Menu 업데이트", - "parameters": [ - { - "description": "models.Menu", - "name": "menu", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Menu" - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200'}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'errors.WithStack(err)'}", - "schema": { - "type": "string" - } - } - } - }, - "post": { - "description": "[RegMenu] models.Menu를 받아 메뉴를 단건 등록합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Menu 등록", - "parameters": [ - { - "description": "models.Menu", - "name": "menu", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Menu" - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200'}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'errors.WithStack(err)'}", - "schema": { - "type": "string" - } - } - } - }, - "delete": { - "description": "[DelMenu] models.Menu를 받아 메뉴를 단건 삭제합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Menu 삭제", - "parameters": [ - { - "description": "models.Menu", - "name": "menu", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Menu" - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200'}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'errors.WithStack(err)'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/adminconfig/menu/id/{menuId}/": { - "get": { - "description": "[GetMenu] menuId와 menuName, menuAlias, categoryId 중 순서로 마지막 한개를 받아 메뉴를 반환합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Menu 조회", - "parameters": [ - { - "type": "string", - "description": "menuId", - "name": "menuId", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "menuName", - "name": "menuName", - "in": "query" - }, - { - "type": "string", - "description": "menuAlias", - "name": "menuAlias", - "in": "query" - }, - { - "type": "string", - "description": "categoryId", - "name": "categoryId", - "in": "query" - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200', 'menu': 'menu'}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'errors.WithStack(err)'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/adminconfig/menu/tree/": { - "get": { - "description": "[MenuTree] category, menu구조를 tree형태로 쿼리하여 반환합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Menu Tree 조회", - "responses": { - "200": { - "description": "{'message':'success','status':'200', 'menutree': 'menutree'}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'errors.WithStack(err)'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/adminconfig/regiongroup/": { - "get": { - "description": "[RegionGroupList] providerId 와 regionGroupName 을 받아 RegionGroupList를 반환합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "RegionGroup 리스트 조회", - "parameters": [ - { - "type": "string", - "description": "provider", - "name": "provider", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "regionGroupName", - "name": "regionGroupName", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{\"message\":\"success\",\"status\":respStatus.StatusCode,\"regionGroup\":regionGroupList,}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'respStatus.Message','error':'respStatus.Message'}", - "schema": { - "type": "string" - } - } - } - }, - "post": { - "description": "[RegRegionGroup] 리전 그룹을 등록합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Region Group 등록", - "parameters": [ - { - "description": "models.RegionGroup", - "name": "regionGroup", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.RegionGroup" - } - } - ], - "responses": { - "200": { - "description": "{'message': 'success', 'status': respStatus.StatusCode}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error':'respStatus.Message','status':respStatus.StatusCode}", - "schema": { - "type": "string" - } - } - } - }, - "delete": { - "description": "[DelRegionGroup] 리전 그룹을 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Region Group 삭제", - "parameters": [ - { - "description": "models.RegionGroup", - "name": "regionGroup", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.RegionGroup" - } - } - ], - "responses": { - "200": { - "description": "{'message': 'success', 'status': respStatus.StatusCode}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error':'respStatus.Message','status':respStatus.StatusCode}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/adminconfig/regiongroup/{regionGroupId}": { - "get": { - "description": "[GetRegionGroup] regionGroupId와 providerId, regionGroupName, regionId 중 한개를 받아 regionGroup을 반환합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "RegionGroup 단건 Vpc 조회", - "parameters": [ - { - "type": "string", - "description": "regionGroupId", - "name": "regionGroupId", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "providerId", - "name": "providerId", - "in": "query" - }, - { - "type": "string", - "description": "regionGroupName", - "name": "regionGroupName", - "in": "query" - }, - { - "type": "string", - "description": "regionId", - "name": "regionId", - "in": "query" - } - ], - "responses": { - "200": { - "description": "{\"message\":\"success\",\"status\":respStatus.StatusCode,\"regionGroup\":regionGroup,}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error':'err.Error()','status':'500'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/auth/logout/": { - "get": { - "description": "[AuthDestroy] 로그아웃을 합니다. clears the session and logs a user out", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "auth" - ], - "summary": "로그아웃", - "responses": { - "200": { - "description": "{'success-Flash': 'You have been logged out!'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/auth/signin/": { - "post": { - "description": "[AuthCreate] 존재하는 계정으로 로그인을 시도합니다. attempts to log the user in with an existing account.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "auth" - ], - "summary": "로그인", - "parameters": [ - { - "type": "string", - "description": "Email", - "name": "Email", - "in": "formData", - "required": true - }, - { - "type": "string", - "description": "Password", - "name": "Password", - "in": "formData", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message': 'success', 'user': 'u'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error':'verrs','status':'http.StatusUnauthorized'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/": { - "get": { - "description": "[CloudConnectionList] connection 리스트를 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "CloudConnection 리스트 조회", - "parameters": [ - { - "type": "string", - "description": "providerId", - "name": "providerId", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "regionName", - "name": "regionName", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "zoneName", - "name": "zoneName", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/models.CloudConnection" - } - } - } - } - }, - "put": { - "description": "[CloudConnectionUpdate] Cloud Connection을 수정합니다. -- not implementated yet", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Cloud Connection을 업데이트 -- not implementated yet", - "responses": { - "200": { - "description": "{'message': 'success','status': 'not implementated yet',}", - "schema": { - "type": "string" - } - } - } - }, - "post": { - "description": "[CloudConnectionCreate] ConnectionReg 등록 후 connection 목록조회\n---- SpiderConnectionReg -\u003e CloudConnectionCreate로 변경\n---- is_cb 가 아니면 connection 등록 후 db 저장하도록 보완할 것.\n---- TODO : SpiderCloudConnectionConfigReg 로 변경할 것\n---- TODO : cloud_connections 저장 MconRegCloudConnection -\u003e 저장실패시 생성한 connection 삭제하도록\n---- TODO : cloud_connections table 조회하도록 변경할 것. : MconCloudConnectionList()\n---- TODO : SpiderCloudConnectionConfigList 로 변경할 것.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "CloudConnection 생성", - "parameters": [ - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/available/": { - "get": { - "description": "[AvailableCloudConnectionList] 사용가능한 Cloud Connection 목록을 조회합니다. Check avaiable ConnectionConfig list for creating MCIS Dynamically", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "사용가능한 Cloud Connection 리스트 조회", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/credential/": { - "get": { - "description": "[CredentialList] Credential 리스트를 조회합니다.\nSpiderCredentialList -\u003e CredentialList 으로 변경 GET", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Credential 리스트 조회", - "parameters": [ - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "message\":\"success\",\"status\":\"200\",\"Credential\": credentialList,}", - "schema": { - "type": "json" - } - }, - "500": { - "description": "error\": err.Error(),\"status\": \"500\",}", - "schema": { - "type": "json" - } - } - } - }, - "post": { - "description": "[CredentialCreate] Credential을 생성합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Credential 생성", - "parameters": [ - { - "description": "spider.CredentialInfo", - "name": "credentialInfo", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/spider.CredentialInfo" - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200',}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - }, - "delete": { - "description": "[CredentialDelete] Credential 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Credential 삭제", - "parameters": [ - { - "description": "models.Credential", - "name": "paramCredential", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Credential" - } - } - ], - "responses": { - "200": { - "description": "success", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/credential/id/{credential}/": { - "get": { - "description": "[CredentialGet] Credential 단건 조회합니다", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Credential 단건 조회", - "parameters": [ - { - "type": "string", - "description": "iscredential_cb", - "name": "credential", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','Credential': 'credentialInfo',}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/credential/sync/": { - "get": { - "description": "[SyncCredential] CB 조회내역을 DB 에 저장합니다. Credential 동기화[handler.SyncCredential(c)]", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Credential 동기화", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/driver/": { - "get": { - "description": "[DriverList] driver 리스트 조회합니다. -- swagger TEST 오류 확인함.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Driver 리스트 조회", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/models.Driver" - } - } - } - } - }, - "post": { - "description": "[DriverCreate] Driver를 생성합니다.\nSpiderDriverReg 등록 -\u003e DriverCreate 로 변경 /settings/connection/driver", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Driver 생성", - "parameters": [ - { - "description": "spider.DriverInfo", - "name": "paramdriverInfoDriver", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/spider.DriverInfo" - } - }, - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "message\": \"success\",\"status\": \"respStatus\",}", - "schema": { - "type": "json" - } - }, - "201": { - "description": "error\": respStatus.Message,\"status\": respStatus.StatusCode,}", - "schema": { - "type": "json" - } - }, - "500": { - "description": "error\": err.Error(),\"status\": 500,}", - "schema": { - "type": "json" - } - } - } - }, - "delete": { - "description": "[DriverDelete] Driver를 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Driver 삭제", - "parameters": [ - { - "description": "models.Driver", - "name": "paramDriver", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Driver" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/models.Driver" - } - } - } - } - }, - "/api/settings/connection/driver/id/{driverId}/": { - "get": { - "description": "[DriverGet] Driver를 단건 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Driver 단건 조회", - "parameters": [ - { - "type": "string", - "description": "driver", - "name": "driver", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message': 'success','status': 'respStatus','Driver': 'driverInfo',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/driver/spider/": { - "get": { - "description": "[SpiderDriverList] Spider Driver 리스트를 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Spider Driver 리스트 조회", - "responses": { - "200": { - "description": "{'message': 'success','status': 'respStatus','Driver': 'driverList',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/driver/spider/id/{driver}/": { - "delete": { - "description": "[SpiderDriverDelete] Spider Driver를 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Spider Driver 삭제", - "parameters": [ - { - "type": "string", - "description": "driver", - "name": "driver", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message': 'success','status': 'respStatus'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/driver/sync/": { - "get": { - "description": "[SyncDriver] CB 조회내역을 DB 에 저장합니다. Driver 동기화[handler.SyncDriver(c)]", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Driver 동기화", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/generate/all/bycredential": { - "get": { - "description": "[GenerateConnectionsByAllCredential] credential 별로 지정 Provider의 모든 region에 대해 connection 생성.\n- 모든 credential에 대해 connection 생성 genconnection\n- handler.GetCredentialList()\n- (현재 설정된 credential 목록 : 목록에서는 key의 value는 ...으로 표시)", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "credential 별 모든 region connection 생성", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/generate/bycredential": { - "get": { - "description": "[GenerateConnectionsByCredential] credential 별로 지정 Provider의 모든 region에 대해 connection 생성.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "credential 별 지정 Provider 모든 region 생성", - "parameters": [ - { - "type": "string", - "description": "providerId", - "name": "providerId", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "credentialName", - "name": "credentialName", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/healthcheck/agent/": { - "get": { - "description": "[AgentHealthCheck] MCIS 또는 VM 에 agent 상태 확인", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Agent Health Check -- TODO", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/healthcheck/framework/": { - "get": { - "description": "[FrameworkHealthCheck] 프레임워크 헬스체크\n- c.Params().Get(\"framework\")\n- DF의 response 에서 return결과가 \"\"으로 들어와 204를 return 함.\n- DF에서 정상적인 message 보내라고 할 것.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Framework Health Check", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/id/{configName}/": { - "delete": { - "description": "[CloudConnectionDelete] Connection을 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Connection 삭제", - "parameters": [ - { - "type": "string", - "description": "paramConfigName", - "name": "paramConfigName", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "success", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/id/{connectionId}/": { - "get": { - "description": "[CloudConnectionGet] connection 단건 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "connection 단건 조회", - "parameters": [ - { - "type": "string", - "description": "connectionId", - "name": "connectionId", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/models.CloudConnection" - } - } - } - } - } - }, - "/api/settings/connection/provider/sync/": { - "get": { - "description": "[SyncCloudProvider] CB 조회내역을 DB 에 저장합니다. CloudProvider 동기화[handler.SyncCloudProvider(c)]", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "CloudProvider 동기화", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/providers/": { - "get": { - "description": "[CloudProviderList] Cloud Provider 리스트를 조회합니다.\nDB에서 가져오게 할 것인가?\nSpiderProviderList 삭제 함 23.07.06", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Cloud Provider 리스트 조회", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus','Region':'resionInfo'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/region/": { - "get": { - "description": "[RegionList] Region 리스트를 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Region 리스트 조회", - "parameters": [ - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "filterKeyParam", - "name": "filterKeyParam", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "filterValParam", - "name": "filterValParam", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','Region':'regionList'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - }, - "post": { - "description": "[RegionCreate] Region을 생성합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Region 생성", - "parameters": [ - { - "description": "spider.RegionInfo", - "name": "regionInfo", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/spider.RegionInfo" - } - }, - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200',}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - }, - "delete": { - "description": "[RegionDelete] Region을 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Region 삭제", - "parameters": [ - { - "description": "models.Region", - "name": "paramRegion", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Region" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/models.Driver" - } - } - } - } - }, - "/api/settings/connection/region/all": { - "get": { - "description": "[RegionAllList] Region의 모든 리스트를 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Region 모든 리스트를 조회", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/models.Region" - } - } - } - } - } - }, - "/api/settings/connection/region/id/{paramRegion}/": { - "get": { - "description": "[RegionGet] Region 단건 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Region 단건 조회", - "parameters": [ - { - "type": "string", - "description": "paramRegion", - "name": "paramRegion", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus','Region':'resionInfo'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/region/sync/": { - "get": { - "description": "[SyncRegion] CB 조회내역을 DB 에 저장합니다. Region 동기화[handler.SyncRegion(c)]", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Region 동기화", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/spider/": { - "get": { - "description": "[SpiderConnectionList] SPIDER connection 리스트를 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "SPIDER ConnectionList 목록조회", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/spider/id/{connectionId}/": { - "get": { - "description": "[SpiderConnectionGet] SPIDER connection 단건을 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "SPIDER Connection 단건조회", - "parameters": [ - { - "type": "string", - "description": "connectionId", - "name": "connectionId", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/sync/": { - "get": { - "description": "[SyncConnection] CB 조회내역을 DB 에 저장합니다. Connection 동기화[handler.SyncConnection(c)]", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Connection 동기화", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/resources/datadisk/": { - "get": { - "description": "[DataDiskList] Data Disk List를 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Data Disk List 조회", - "parameters": [ - { - "type": "string", - "description": "option", - "name": "option", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "filterKey", - "name": "filterKey", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "filterVal", - "name": "filterVal", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','defaultNameSpaceID': namespaceID,'status': respStatus.StatusCode,}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - }, - "post": { - "description": "[DataDiskReg] Data Disk를 생성합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "DataDisk 생성", - "parameters": [ - { - "description": "tbmcir.TbDataDiskReq", - "name": "dataDiskRegInfo", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/mcir.TbDataDiskReq" - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200',}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/resources/datadisk/availabledisk/": { - "get": { - "description": "[McisVmAvailableDataDiskList] VM 이사용가능한 DataDisk Id 목록 조회", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Mcis Vm Available Data Disk List 조회", - "parameters": [ - { - "type": "string", - "description": "mcisId", - "name": "mcisId", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "vmID", - "name": "vmID", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','dataDiskInfoList':dataDiskInfoList}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/resources/datadisk/id/{dataDiskId}/": { - "get": { - "description": "[DataDiskGet] Data Disk를 dataDiskId로 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Data Disk 단건 조회", - "parameters": [ - { - "type": "string", - "description": "dataDiskId", - "name": "dataDiskId", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','dataDiskInfo': dataDiskInfo}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - }, - "put": { - "description": "[DataDiskPut] Data Disk를 변경합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Data Disk 변경", - "parameters": [ - { - "type": "string", - "description": "dataDiskId", - "name": "dataDiskId", - "in": "path", - "required": true - }, - { - "description": "tbmcir.TbDataDiskUpsizeReq", - "name": "dataDiskUpsizeReq", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/mcir.TbDataDiskUpsizeReq" - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','DataDiskInfo': DataDiskInfo}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - }, - "delete": { - "description": "[DataDiskDel] Data Disk를 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Data Disk 삭제", - "parameters": [ - { - "type": "string", - "description": "dataDiskId", - "name": "dataDiskId", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/resources/datadisk/lookup/": { - "get": { - "description": "[AvailableDataDiskTypeList] Provider, Region에서 사용가능한 DiskType 조회(DiskLookup)\nspider의 cloudos_meta.yaml 참조", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Available Data Disk List 조회", - "parameters": [ - { - "type": "string", - "description": "providerId", - "name": "providerId", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "regionName", - "name": "regionName", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','DiskInfoList':availableDiskTypeList}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/resources/datadisk/mngdata/": { - "post": { - "description": "[DataDiskMng] Data Disk Mng(CRD) 합니다.\nCreate, Update, Delete가 한번에 일어나는 경우 사용\nex) table에 addRow로 추가하고 delet로 삭제한 것들을 한번에 저장할 때.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Data Disk CRD 한번에", - "parameters": [ - { - "description": "webtool.DataDiskMngReq", - "name": "dataDiskRegInfo", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/webtool.DataDiskMngReq" - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200',}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/resources/datadisk/region/": { - "get": { - "description": "[DataDiskListByRegion] Data Disk List를 connection으로 조회합니다.\n해당리전에 등록 된 DataDisk 목록. connection 필요\nUI 에서 용이하게 쓰기 위함 (콤보 선택용)", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Data Disk List 조회 (connection)", - "parameters": [ - { - "type": "string", - "description": "option", - "name": "option", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "connectionName", - "name": "filterValParam", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','defaultNameSpaceID': namespaceID,'dataDiskInfoList': dataDiskInfoList,}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/test/apitest/searchapi/": { - "post": { - "description": "[ApiSearch] Api 핸들러를 찾아 Swagger 로 이동합니다.", - "produces": [ - "text/html" - ], - "tags": [ - "debug" - ], - "summary": "Api Search swagger : todo : 삭제", - "responses": { - "200": { - "description": "redirect", - "schema": { - "type": "html" - } - } - } - } - }, - "/api/test/connection/list/": { - "get": { - "description": "[CloudConnectionAllList] 모든 connection을 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "debug" - ], - "summary": "모든 connection 조회", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/models.CloudConnection" - } - } - } - } - } - }, - "/api/test/connection/list/bycred": { - "post": { - "description": "[TestCloudConnection] credential로 가능한 Connection 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "debug" - ], - "summary": "credential로 가능한 Connection 조회", - "parameters": [ - { - "description": "models.Credentials", - "name": "credential", - "in": "body", - "required": true, - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/models.Credential" - } - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/auth/landing/mngform/": { - "get": { - "description": "[AuthLandingForm] 렌딩 화면을 렌더링합니다. AuthLanding shows a landing page to login", - "produces": [ - "text/html" - ], - "tags": [ - "auth" - ], - "summary": "렌딩 화면 렌더링", - "responses": { - "200": { - "description": "auth/landing.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/auth/signin/mngform/": { - "get": { - "description": "[AuthNewForm] 로그인 화면을 렌더링합니다. AuthNew loads the signin page", - "produces": [ - "text/html" - ], - "tags": [ - "auth" - ], - "summary": "로그인 화면 렌더링", - "responses": { - "200": { - "description": "auth/new.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/operations/globaldashboard/mngform/": { - "get": { - "description": "[GlobalDashboardGet] Global Dashboard 폼을 렌더링 합니다. GlobalDashboardMngForm default implementation.", - "produces": [ - "text/html" - ], - "tags": [ - "globaldashboard" - ], - "summary": "Global Dashboard 폼 렌더링 : TODO", - "responses": { - "200": { - "description": "operations/globaldashboard/mngform.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/settings/connection/mngform/": { - "get": { - "description": "[ConnectionMngForm] ConnectionForm은 Connection 설정 폼을 렌더링합니다.", - "produces": [ - "text/html" - ], - "tags": [ - "connection" - ], - "summary": "Connection 설정 폼 렌더링", - "responses": { - "200": { - "description": "settings/connection/mngform.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/settings/resources/datadisk/mngform/": { - "get": { - "description": "[DataDiskMngForm] 데이터 디스크 화면을 렌더링합니다.", - "produces": [ - "text/html" - ], - "tags": [ - "datadisk" - ], - "summary": "데이터 디스크 화면 렌더링", - "responses": { - "200": { - "description": "settings/datadisk/mngform.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/test/apitest/mngform/": { - "get": { - "description": "[ApiTestForm] ApiTest를 렌더링 합니다.", - "produces": [ - "text/html" - ], - "tags": [ - "debug" - ], - "summary": "Api test mngform : todo : 삭제", - "responses": { - "200": { - "description": "adminconfig/apitest/mngform.html", - "schema": { - "type": "html" - } - } - } - } - } - }, - "definitions": { - "mcir.TbDataDiskReq": { - "type": "object", - "properties": { - "connectionName": { - "type": "string" - }, - "cspDataDiskId": { - "type": "string" - }, - "description": { - "type": "string" - }, - "diskSize": { - "type": "string" - }, - "diskType": { - "type": "string" - }, - "name": { - "type": "string" - }, - "providerId": { - "description": "connection 을 provider, regname으로 대체를 위해 추가", - "type": "string" - }, - "providerName": { - "type": "string" - }, - "regionName": { - "type": "string" - }, - "zoneName": { - "type": "string" - } - } - }, - "mcir.TbDataDiskUpsizeReq": { - "type": "object", - "properties": { - "description": { - "type": "string" - }, - "diskSize": { - "type": "string" - }, - "providerId": { - "type": "string" - }, - "providerName": { - "type": "string" - }, - "regionName": { - "type": "string" - }, - "zoneName": { - "type": "string" - } - } - }, - "models.Category": { - "type": "object", - "properties": { - "category_name": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "parent_category_id": { - "type": "string" - }, - "sort": { - "type": "integer" - }, - "updated_at": { - "type": "string" - } - } - }, - "models.CloudConnection": { - "type": "object", - "properties": { - "connectionName": { - "type": "string" - }, - "connection_id": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "credential": { - "$ref": "#/definitions/models.Credential" - }, - "credential_id": { - "type": "string" - }, - "driver": { - "$ref": "#/definitions/models.Driver" - }, - "driver_id": { - "type": "string" - }, - "provider": { - "$ref": "#/definitions/models.CloudProvider" - }, - "provider_id": { - "description": "사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함.", - "type": "string" - }, - "region": { - "$ref": "#/definitions/models.Region" - }, - "region_id": { - "type": "string" - }, - "updated_at": { - "type": "string" - } - } - }, - "models.CloudConnections": { - "type": "array", - "items": { - "$ref": "#/definitions/models.CloudConnection" - } - }, - "models.CloudProvider": { - "type": "object", - "properties": { - "created_at": { - "type": "string" - }, - "provider_id": { - "type": "string" - }, - "provider_name": { - "type": "string" - }, - "updated_at": { - "type": "string" - } - } - }, - "models.Credential": { - "type": "object", - "properties": { - "cloudConnections": { - "description": "사용 될 참조", - "allOf": [ - { - "$ref": "#/definitions/models.CloudConnections" - } - ] - }, - "created_at": { - "type": "string" - }, - "credentialKeyValues": { - "description": "여러개는 객체", - "type": "array", - "items": { - "$ref": "#/definitions/models.CredentialKeyvalue" - } - }, - "credentialName": { - "type": "string" - }, - "id": { - "type": "string" - }, - "provider": { - "$ref": "#/definitions/models.CloudProvider" - }, - "provider_id": { - "description": "사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함.", - "type": "string" - }, - "updated_at": { - "type": "string" - }, - "userLevel": { - "type": "string" - } - } - }, - "models.CredentialKeyvalue": { - "type": "object", - "properties": { - "created_at": { - "type": "string" - }, - "credential": { - "$ref": "#/definitions/models.Credential" - }, - "credential_id": { - "type": "string" - }, - "id": { - "type": "string" - }, - "key": { - "type": "string" - }, - "updated_at": { - "type": "string" - }, - "value": { - "type": "string" - } - } - }, - "models.Driver": { - "type": "object", - "properties": { - "cloudConnections": { - "description": "CloudConnection *CloudConnection ` + "`" + `belongs_to:\"cloud_connection\"` + "`" + `", - "type": "array", - "items": { - "$ref": "#/definitions/models.CloudConnection" - } - }, - "created_at": { - "type": "string" - }, - "driver_name": { - "type": "string" - }, - "id": { - "type": "string" - }, - "lib_file_name": { - "type": "string" - }, - "provider": { - "$ref": "#/definitions/models.CloudProvider" - }, - "provider_id": { - "type": "string" - }, - "updated_at": { - "type": "string" - } - } - }, - "models.Menu": { - "type": "object", - "properties": { - "alias": { - "description": "Path string ` + "`" + `json:\"path\" db:\"path\"` + "`" + `\nAlias string ` + "`" + `json:\"alias\" db:\"alias\"` + "`" + `", - "type": "string" - }, - "category": { - "$ref": "#/definitions/models.Category" - }, - "category_id": { - "description": "사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함.", - "type": "string" - }, - "created_at": { - "type": "string" - }, - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "sort": { - "type": "integer" - }, - "updated_at": { - "type": "string" - }, - "visible": { - "type": "boolean" - } - } - }, - "models.Region": { - "type": "object", - "properties": { - "created_at": { - "type": "string" - }, - "id": { - "type": "string" - }, - "provider": { - "$ref": "#/definitions/models.CloudProvider" - }, - "provider_id": { - "type": "string" - }, - "regionKeyValue": { - "type": "array", - "items": { - "$ref": "#/definitions/models.RegionKeyvalue" - } - }, - "regionName": { - "type": "string" - }, - "updated_at": { - "type": "string" - } - } - }, - "models.RegionGroup": { - "type": "object", - "properties": { - "created_at": { - "type": "string" - }, - "csp_region_name": { - "description": "raw query로 호출하여 return하기위해 추가", - "type": "string" - }, - "provider_id": { - "description": "사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함. transaction으로 호출해야 relation이 적용 됨. 그냥 query로 호출하면 null.", - "type": "string" - }, - "provider_name": { - "description": "raw query로 호출하여 return하기위해 추가", - "type": "string" - }, - "region_group_id": { - "type": "string" - }, - "region_group_name": { - "type": "string" - }, - "region_id": { - "type": "string" - }, - "region_name": { - "description": "raw query로 호출하여 return하기위해 추가", - "type": "string" - }, - "updated_at": { - "type": "string" - } - } - }, - "models.RegionKeyvalue": { - "type": "object", - "properties": { - "created_at": { - "type": "string" - }, - "id": { - "type": "string" - }, - "key": { - "type": "string" - }, - "region": { - "$ref": "#/definitions/models.Region" - }, - "region_id": { - "type": "string" - }, - "updated_at": { - "type": "string" - }, - "value": { - "type": "string" - } - } - }, - "spider.CredentialInfo": { - "type": "object", - "properties": { - "CredentialName": { - "description": "user(username, password, email)", - "type": "string" - }, - "KeyValueInfoList": { - "type": "array", - "items": { - "$ref": "#/definitions/spider.SpKeyValueInfo" - } - }, - "ProviderName": { - "type": "string" - } - } - }, - "spider.DriverInfo": { - "type": "object", - "properties": { - "DriverLibFileName": { - "type": "string" - }, - "DriverName": { - "description": "user(username, password, email)", - "type": "string" - }, - "ProviderName": { - "type": "string" - } - } - }, - "spider.RegionInfo": { - "type": "object", - "properties": { - "KeyValueInfoList": { - "type": "array", - "items": { - "$ref": "#/definitions/spider.SpKeyValueInfo" - } - }, - "ProviderName": { - "type": "string" - }, - "RegionName": { - "type": "string" - } - } - }, - "spider.SpKeyValueInfo": { - "type": "object", - "properties": { - "Key": { - "type": "string" - }, - "Value": { - "type": "string" - } - } - }, - "webtool.DataDiskCreateReq": { - "type": "object", - "properties": { - "attachVmId": { - "description": "VmID string ` + "`" + `json:\"vmId\"` + "`" + `", - "type": "string" - }, - "connectionName": { - "type": "string" - }, - "cspDataDiskId": { - "type": "string" - }, - "description": { - "type": "string" - }, - "diskSize": { - "type": "string" - }, - "diskType": { - "type": "string" - }, - "mcisId": { - "description": "Attach VMID", - "type": "string" - }, - "name": { - "description": "tbmcir.TbDataDiskReq", - "type": "string" - } - } - }, - "webtool.DataDiskMngReq": { - "type": "object", - "properties": { - "attachDataDiskList": { - "description": "attach list", - "type": "array", - "items": { - "type": "string" - } - }, - "createDataDiskList": { - "description": "create disk list", - "type": "array", - "items": { - "$ref": "#/definitions/webtool.DataDiskCreateReq" - } - }, - "dataDiskList": { - "description": "del disk list", - "type": "array", - "items": { - "type": "string" - } - }, - "dettachDataDiskList": { - "description": "detach list", - "type": "array", - "items": { - "type": "string" - } - } - } - } - } -}` - -// SwaggerInfo holds exported Swagger Info so clients can modify it -var SwaggerInfo = &swag.Spec{ - Version: "??", - Host: "localhost:3000", - BasePath: "/", - Schemes: []string{}, - Title: " API", - Description: " API Swagger page", - InfoInstanceName: "swagger", - SwaggerTemplate: docTemplate, - LeftDelim: "{{", - RightDelim: "}}", -} - -func init() { - swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo) -} diff --git a/mc_web_console_api/docs/example.txt b/mc_web_console_api/docs/example.txt deleted file mode 100644 index 6d7ce795..00000000 --- a/mc_web_console_api/docs/example.txt +++ /dev/null @@ -1,39 +0,0 @@ -// 예시 엔드포인트 -// @Summary 인사 메시지 보내기 -// @Description 이름을 입력받아 인사 메시지를 보냅니다. -// @Tags greetings -// @Accept json -// @Produce plain -// @Param name query string true "이름" -// @Success 200 {string} string -// @Failure 400 {object} ErrorResponse -// @Router /greet [get] - - -// 예시 엔드포인트 -// @Summary 인사 메시지 보내기 -// @Description 이름을 입력받아 인사 메시지를 보냅니다. -// @Tags greetings -// @Accept json -// @Produce plain -// @Param name query string true "이름" --> // @Param "" - -// @Param id path int true "사용자 ID" -// @Param name query string false "사용자 이름" -// @Param limit query int false "결과 제한" - - -// @Success 200 {string} string -// @Failure 400 {object} ErrorResponse -// @Router /greet [get] -func Greet(c buffalo.Context) error { - name := c.Param("name") - greeting := fmt.Sprintf("안녕하세요, %s님!", name) - return c.Render(200, r.Plain(greeting)) -} - - - -{"message":"success","status":respStatus.StatusCode,"regionGroup":regionGroupList,} - -"{'error':'respStatus.Message','status':respStatus.StatusCode}" diff --git a/mc_web_console_api/docs/swagger.json b/mc_web_console_api/docs/swagger.json deleted file mode 100644 index c0fec501..00000000 --- a/mc_web_console_api/docs/swagger.json +++ /dev/null @@ -1,2916 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "description": " API Swagger page", - "title": " API", - "contact": { - "name": " ", - "url": "https://github.com/ " - }, - "license": {}, - "version": "??" - }, - "host": "localhost:3000", - "basePath": "/", - "paths": { - "/adminconfig/category/mngform/": { - "get": { - "description": "[CategoryMngForm] Category 설정 폼을 렌더링합니다.", - "produces": [ - "text/html" - ], - "tags": [ - "adminconfig" - ], - "summary": "Category 설정 폼 렌더링", - "responses": { - "200": { - "description": "adminconfig/categorymng/mngform.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/adminconfig/config/mngform/": { - "get": { - "description": "[AdminMngForm] Admin 관리자 설정 폼을 렌더링합니다. : not implement -- 아직 기획된바 없음.", - "produces": [ - "text/html" - ], - "tags": [ - "adminconfig" - ], - "summary": "관리자 설정 폼 렌더링 : not implement -- 아직 기획된바 없음.", - "responses": { - "200": { - "description": "adminconfig/regiongroup/mngform.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/adminconfig/menu/mngform/": { - "get": { - "description": "[MenuMngForm] Menu 설정 폼을 렌더링합니다.", - "produces": [ - "text/html" - ], - "tags": [ - "adminconfig" - ], - "summary": "Menu 설정 폼 렌더링", - "responses": { - "200": { - "description": "adminconfig/menumng/mngform.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/api/adminconfig/category/": { - "get": { - "security": [ - { - "CSRFTokenHeader": [] - } - ], - "description": "[CategoryList] categoryName을 받아 categoryList를 반환합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Category 리스트 조회", - "parameters": [ - { - "type": "string", - "description": "categoryName", - "name": "categoryName", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{\"message\":\"success\",\"status\":respStatus.StatusCode,\"regionGroup\":categoryList,}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'respStatus.Message','error':'respStatus.Message'}", - "schema": { - "type": "string" - } - } - } - }, - "post": { - "description": "[RegCategory] 카테고리를 등록합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Category 등록", - "parameters": [ - { - "description": "models.Category", - "name": "Category", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Category" - } - } - ], - "responses": { - "200": { - "description": "{'message': 'success', 'status': 200}", - "schema": { - "type": "string" - } - } - } - }, - "delete": { - "description": "[CategoryDel] 카테고리를 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Category 삭제", - "parameters": [ - { - "description": "models.Category", - "name": "Category", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Category" - } - } - ], - "responses": { - "200": { - "description": "{'message': 'success', 'status': 200}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/adminconfig/category/id/{categoryName}/": { - "get": { - "security": [ - { - "CSRFTokenHeader": [] - } - ], - "description": "[CategoryGet] categoryName을 받아 category 단건을 반환합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Category 단건 조회", - "parameters": [ - { - "type": "string", - "description": "categoryName", - "name": "categoryName", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','category':'category',}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'errors.WithStack(err)'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/adminconfig/menu/": { - "get": { - "description": "[MenuList] menuId, menuName, menuAlias, categoryId 중 순서로 마지막 한개를 받아 메뉴 리스트를 반환합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Menu 리스트 조회", - "parameters": [ - { - "type": "string", - "description": "menuId", - "name": "menuId", - "in": "query" - }, - { - "type": "string", - "description": "menuName", - "name": "menuName", - "in": "query" - }, - { - "type": "string", - "description": "menuAlias", - "name": "menuAlias", - "in": "query" - }, - { - "type": "string", - "description": "categoryId", - "name": "categoryId", - "in": "query" - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200', 'menuList': 'menuList'}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'errors.WithStack(err)'}", - "schema": { - "type": "string" - } - } - } - }, - "put": { - "description": "[UpdateMenu] models.Menu를 받아 메뉴를 단건 업데이트합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Menu 업데이트", - "parameters": [ - { - "description": "models.Menu", - "name": "menu", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Menu" - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200'}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'errors.WithStack(err)'}", - "schema": { - "type": "string" - } - } - } - }, - "post": { - "description": "[RegMenu] models.Menu를 받아 메뉴를 단건 등록합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Menu 등록", - "parameters": [ - { - "description": "models.Menu", - "name": "menu", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Menu" - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200'}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'errors.WithStack(err)'}", - "schema": { - "type": "string" - } - } - } - }, - "delete": { - "description": "[DelMenu] models.Menu를 받아 메뉴를 단건 삭제합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Menu 삭제", - "parameters": [ - { - "description": "models.Menu", - "name": "menu", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Menu" - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200'}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'errors.WithStack(err)'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/adminconfig/menu/id/{menuId}/": { - "get": { - "description": "[GetMenu] menuId와 menuName, menuAlias, categoryId 중 순서로 마지막 한개를 받아 메뉴를 반환합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Menu 조회", - "parameters": [ - { - "type": "string", - "description": "menuId", - "name": "menuId", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "menuName", - "name": "menuName", - "in": "query" - }, - { - "type": "string", - "description": "menuAlias", - "name": "menuAlias", - "in": "query" - }, - { - "type": "string", - "description": "categoryId", - "name": "categoryId", - "in": "query" - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200', 'menu': 'menu'}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'errors.WithStack(err)'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/adminconfig/menu/tree/": { - "get": { - "description": "[MenuTree] category, menu구조를 tree형태로 쿼리하여 반환합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Menu Tree 조회", - "responses": { - "200": { - "description": "{'message':'success','status':'200', 'menutree': 'menutree'}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'errors.WithStack(err)'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/adminconfig/regiongroup/": { - "get": { - "description": "[RegionGroupList] providerId 와 regionGroupName 을 받아 RegionGroupList를 반환합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "RegionGroup 리스트 조회", - "parameters": [ - { - "type": "string", - "description": "provider", - "name": "provider", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "regionGroupName", - "name": "regionGroupName", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{\"message\":\"success\",\"status\":respStatus.StatusCode,\"regionGroup\":regionGroupList,}", - "schema": { - "type": "string" - } - }, - "400": { - "description": "{'error':'respStatus.Message','error':'respStatus.Message'}", - "schema": { - "type": "string" - } - } - } - }, - "post": { - "description": "[RegRegionGroup] 리전 그룹을 등록합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Region Group 등록", - "parameters": [ - { - "description": "models.RegionGroup", - "name": "regionGroup", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.RegionGroup" - } - } - ], - "responses": { - "200": { - "description": "{'message': 'success', 'status': respStatus.StatusCode}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error':'respStatus.Message','status':respStatus.StatusCode}", - "schema": { - "type": "string" - } - } - } - }, - "delete": { - "description": "[DelRegionGroup] 리전 그룹을 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "Region Group 삭제", - "parameters": [ - { - "description": "models.RegionGroup", - "name": "regionGroup", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.RegionGroup" - } - } - ], - "responses": { - "200": { - "description": "{'message': 'success', 'status': respStatus.StatusCode}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error':'respStatus.Message','status':respStatus.StatusCode}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/adminconfig/regiongroup/{regionGroupId}": { - "get": { - "description": "[GetRegionGroup] regionGroupId와 providerId, regionGroupName, regionId 중 한개를 받아 regionGroup을 반환합니다.", - "produces": [ - "application/json" - ], - "tags": [ - "adminconfig" - ], - "summary": "RegionGroup 단건 Vpc 조회", - "parameters": [ - { - "type": "string", - "description": "regionGroupId", - "name": "regionGroupId", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "providerId", - "name": "providerId", - "in": "query" - }, - { - "type": "string", - "description": "regionGroupName", - "name": "regionGroupName", - "in": "query" - }, - { - "type": "string", - "description": "regionId", - "name": "regionId", - "in": "query" - } - ], - "responses": { - "200": { - "description": "{\"message\":\"success\",\"status\":respStatus.StatusCode,\"regionGroup\":regionGroup,}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error':'err.Error()','status':'500'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/auth/logout/": { - "get": { - "description": "[AuthDestroy] 로그아웃을 합니다. clears the session and logs a user out", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "auth" - ], - "summary": "로그아웃", - "responses": { - "200": { - "description": "{'success-Flash': 'You have been logged out!'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/auth/signin/": { - "post": { - "description": "[AuthCreate] 존재하는 계정으로 로그인을 시도합니다. attempts to log the user in with an existing account.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "auth" - ], - "summary": "로그인", - "parameters": [ - { - "type": "string", - "description": "Email", - "name": "Email", - "in": "formData", - "required": true - }, - { - "type": "string", - "description": "Password", - "name": "Password", - "in": "formData", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message': 'success', 'user': 'u'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error':'verrs','status':'http.StatusUnauthorized'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/": { - "get": { - "description": "[CloudConnectionList] connection 리스트를 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "CloudConnection 리스트 조회", - "parameters": [ - { - "type": "string", - "description": "providerId", - "name": "providerId", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "regionName", - "name": "regionName", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "zoneName", - "name": "zoneName", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/models.CloudConnection" - } - } - } - } - }, - "put": { - "description": "[CloudConnectionUpdate] Cloud Connection을 수정합니다. -- not implementated yet", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Cloud Connection을 업데이트 -- not implementated yet", - "responses": { - "200": { - "description": "{'message': 'success','status': 'not implementated yet',}", - "schema": { - "type": "string" - } - } - } - }, - "post": { - "description": "[CloudConnectionCreate] ConnectionReg 등록 후 connection 목록조회\n---- SpiderConnectionReg -\u003e CloudConnectionCreate로 변경\n---- is_cb 가 아니면 connection 등록 후 db 저장하도록 보완할 것.\n---- TODO : SpiderCloudConnectionConfigReg 로 변경할 것\n---- TODO : cloud_connections 저장 MconRegCloudConnection -\u003e 저장실패시 생성한 connection 삭제하도록\n---- TODO : cloud_connections table 조회하도록 변경할 것. : MconCloudConnectionList()\n---- TODO : SpiderCloudConnectionConfigList 로 변경할 것.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "CloudConnection 생성", - "parameters": [ - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/available/": { - "get": { - "description": "[AvailableCloudConnectionList] 사용가능한 Cloud Connection 목록을 조회합니다. Check avaiable ConnectionConfig list for creating MCIS Dynamically", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "사용가능한 Cloud Connection 리스트 조회", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/credential/": { - "get": { - "description": "[CredentialList] Credential 리스트를 조회합니다.\nSpiderCredentialList -\u003e CredentialList 으로 변경 GET", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Credential 리스트 조회", - "parameters": [ - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "message\":\"success\",\"status\":\"200\",\"Credential\": credentialList,}", - "schema": { - "type": "json" - } - }, - "500": { - "description": "error\": err.Error(),\"status\": \"500\",}", - "schema": { - "type": "json" - } - } - } - }, - "post": { - "description": "[CredentialCreate] Credential을 생성합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Credential 생성", - "parameters": [ - { - "description": "spider.CredentialInfo", - "name": "credentialInfo", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/spider.CredentialInfo" - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200',}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - }, - "delete": { - "description": "[CredentialDelete] Credential 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Credential 삭제", - "parameters": [ - { - "description": "models.Credential", - "name": "paramCredential", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Credential" - } - } - ], - "responses": { - "200": { - "description": "success", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/credential/id/{credential}/": { - "get": { - "description": "[CredentialGet] Credential 단건 조회합니다", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Credential 단건 조회", - "parameters": [ - { - "type": "string", - "description": "iscredential_cb", - "name": "credential", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','Credential': 'credentialInfo',}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/credential/sync/": { - "get": { - "description": "[SyncCredential] CB 조회내역을 DB 에 저장합니다. Credential 동기화[handler.SyncCredential(c)]", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Credential 동기화", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/driver/": { - "get": { - "description": "[DriverList] driver 리스트 조회합니다. -- swagger TEST 오류 확인함.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Driver 리스트 조회", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/models.Driver" - } - } - } - } - }, - "post": { - "description": "[DriverCreate] Driver를 생성합니다.\nSpiderDriverReg 등록 -\u003e DriverCreate 로 변경 /settings/connection/driver", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Driver 생성", - "parameters": [ - { - "description": "spider.DriverInfo", - "name": "paramdriverInfoDriver", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/spider.DriverInfo" - } - }, - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "message\": \"success\",\"status\": \"respStatus\",}", - "schema": { - "type": "json" - } - }, - "201": { - "description": "error\": respStatus.Message,\"status\": respStatus.StatusCode,}", - "schema": { - "type": "json" - } - }, - "500": { - "description": "error\": err.Error(),\"status\": 500,}", - "schema": { - "type": "json" - } - } - } - }, - "delete": { - "description": "[DriverDelete] Driver를 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Driver 삭제", - "parameters": [ - { - "description": "models.Driver", - "name": "paramDriver", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Driver" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/models.Driver" - } - } - } - } - }, - "/api/settings/connection/driver/id/{driverId}/": { - "get": { - "description": "[DriverGet] Driver를 단건 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Driver 단건 조회", - "parameters": [ - { - "type": "string", - "description": "driver", - "name": "driver", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message': 'success','status': 'respStatus','Driver': 'driverInfo',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/driver/spider/": { - "get": { - "description": "[SpiderDriverList] Spider Driver 리스트를 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Spider Driver 리스트 조회", - "responses": { - "200": { - "description": "{'message': 'success','status': 'respStatus','Driver': 'driverList',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/driver/spider/id/{driver}/": { - "delete": { - "description": "[SpiderDriverDelete] Spider Driver를 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Spider Driver 삭제", - "parameters": [ - { - "type": "string", - "description": "driver", - "name": "driver", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message': 'success','status': 'respStatus'}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/driver/sync/": { - "get": { - "description": "[SyncDriver] CB 조회내역을 DB 에 저장합니다. Driver 동기화[handler.SyncDriver(c)]", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Driver 동기화", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/generate/all/bycredential": { - "get": { - "description": "[GenerateConnectionsByAllCredential] credential 별로 지정 Provider의 모든 region에 대해 connection 생성.\n- 모든 credential에 대해 connection 생성 genconnection\n- handler.GetCredentialList()\n- (현재 설정된 credential 목록 : 목록에서는 key의 value는 ...으로 표시)", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "credential 별 모든 region connection 생성", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/generate/bycredential": { - "get": { - "description": "[GenerateConnectionsByCredential] credential 별로 지정 Provider의 모든 region에 대해 connection 생성.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "credential 별 지정 Provider 모든 region 생성", - "parameters": [ - { - "type": "string", - "description": "providerId", - "name": "providerId", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "credentialName", - "name": "credentialName", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/healthcheck/agent/": { - "get": { - "description": "[AgentHealthCheck] MCIS 또는 VM 에 agent 상태 확인", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Agent Health Check -- TODO", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/healthcheck/framework/": { - "get": { - "description": "[FrameworkHealthCheck] 프레임워크 헬스체크\n- c.Params().Get(\"framework\")\n- DF의 response 에서 return결과가 \"\"으로 들어와 204를 return 함.\n- DF에서 정상적인 message 보내라고 할 것.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Framework Health Check", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/id/{configName}/": { - "delete": { - "description": "[CloudConnectionDelete] Connection을 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Connection 삭제", - "parameters": [ - { - "type": "string", - "description": "paramConfigName", - "name": "paramConfigName", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "success", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/id/{connectionId}/": { - "get": { - "description": "[CloudConnectionGet] connection 단건 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "connection 단건 조회", - "parameters": [ - { - "type": "string", - "description": "connectionId", - "name": "connectionId", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/models.CloudConnection" - } - } - } - } - } - }, - "/api/settings/connection/provider/sync/": { - "get": { - "description": "[SyncCloudProvider] CB 조회내역을 DB 에 저장합니다. CloudProvider 동기화[handler.SyncCloudProvider(c)]", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "CloudProvider 동기화", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/providers/": { - "get": { - "description": "[CloudProviderList] Cloud Provider 리스트를 조회합니다.\nDB에서 가져오게 할 것인가?\nSpiderProviderList 삭제 함 23.07.06", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Cloud Provider 리스트 조회", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus','Region':'resionInfo'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/region/": { - "get": { - "description": "[RegionList] Region 리스트를 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Region 리스트 조회", - "parameters": [ - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "filterKeyParam", - "name": "filterKeyParam", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "filterValParam", - "name": "filterValParam", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','Region':'regionList'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - }, - "post": { - "description": "[RegionCreate] Region을 생성합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Region 생성", - "parameters": [ - { - "description": "spider.RegionInfo", - "name": "regionInfo", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/spider.RegionInfo" - } - }, - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200',}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - }, - "delete": { - "description": "[RegionDelete] Region을 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Region 삭제", - "parameters": [ - { - "description": "models.Region", - "name": "paramRegion", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/models.Region" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/models.Driver" - } - } - } - } - }, - "/api/settings/connection/region/all": { - "get": { - "description": "[RegionAllList] Region의 모든 리스트를 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Region 모든 리스트를 조회", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/models.Region" - } - } - } - } - } - }, - "/api/settings/connection/region/id/{paramRegion}/": { - "get": { - "description": "[RegionGet] Region 단건 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Region 단건 조회", - "parameters": [ - { - "type": "string", - "description": "paramRegion", - "name": "paramRegion", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "is_cb", - "name": "is_cb", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus','Region':'resionInfo'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/region/sync/": { - "get": { - "description": "[SyncRegion] CB 조회내역을 DB 에 저장합니다. Region 동기화[handler.SyncRegion(c)]", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Region 동기화", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/spider/": { - "get": { - "description": "[SpiderConnectionList] SPIDER connection 리스트를 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "SPIDER ConnectionList 목록조회", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/spider/id/{connectionId}/": { - "get": { - "description": "[SpiderConnectionGet] SPIDER connection 단건을 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "SPIDER Connection 단건조회", - "parameters": [ - { - "type": "string", - "description": "connectionId", - "name": "connectionId", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/connection/sync/": { - "get": { - "description": "[SyncConnection] CB 조회내역을 DB 에 저장합니다. Connection 동기화[handler.SyncConnection(c)]", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "connection" - ], - "summary": "Connection 동기화", - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/resources/datadisk/": { - "get": { - "description": "[DataDiskList] Data Disk List를 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Data Disk List 조회", - "parameters": [ - { - "type": "string", - "description": "option", - "name": "option", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "filterKey", - "name": "filterKey", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "filterVal", - "name": "filterVal", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','defaultNameSpaceID': namespaceID,'status': respStatus.StatusCode,}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - }, - "post": { - "description": "[DataDiskReg] Data Disk를 생성합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "DataDisk 생성", - "parameters": [ - { - "description": "tbmcir.TbDataDiskReq", - "name": "dataDiskRegInfo", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/mcir.TbDataDiskReq" - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200',}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/resources/datadisk/availabledisk/": { - "get": { - "description": "[McisVmAvailableDataDiskList] VM 이사용가능한 DataDisk Id 목록 조회", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Mcis Vm Available Data Disk List 조회", - "parameters": [ - { - "type": "string", - "description": "mcisId", - "name": "mcisId", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "vmID", - "name": "vmID", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','dataDiskInfoList':dataDiskInfoList}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/resources/datadisk/id/{dataDiskId}/": { - "get": { - "description": "[DataDiskGet] Data Disk를 dataDiskId로 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Data Disk 단건 조회", - "parameters": [ - { - "type": "string", - "description": "dataDiskId", - "name": "dataDiskId", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','dataDiskInfo': dataDiskInfo}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - }, - "put": { - "description": "[DataDiskPut] Data Disk를 변경합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Data Disk 변경", - "parameters": [ - { - "type": "string", - "description": "dataDiskId", - "name": "dataDiskId", - "in": "path", - "required": true - }, - { - "description": "tbmcir.TbDataDiskUpsizeReq", - "name": "dataDiskUpsizeReq", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/mcir.TbDataDiskUpsizeReq" - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','DataDiskInfo': DataDiskInfo}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - }, - "delete": { - "description": "[DataDiskDel] Data Disk를 삭제합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Data Disk 삭제", - "parameters": [ - { - "type": "string", - "description": "dataDiskId", - "name": "dataDiskId", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/resources/datadisk/lookup/": { - "get": { - "description": "[AvailableDataDiskTypeList] Provider, Region에서 사용가능한 DiskType 조회(DiskLookup)\nspider의 cloudos_meta.yaml 참조", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Available Data Disk List 조회", - "parameters": [ - { - "type": "string", - "description": "providerId", - "name": "providerId", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "regionName", - "name": "regionName", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','DiskInfoList':availableDiskTypeList}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/resources/datadisk/mngdata/": { - "post": { - "description": "[DataDiskMng] Data Disk Mng(CRD) 합니다.\nCreate, Update, Delete가 한번에 일어나는 경우 사용\nex) table에 addRow로 추가하고 delet로 삭제한 것들을 한번에 저장할 때.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Data Disk CRD 한번에", - "parameters": [ - { - "description": "webtool.DataDiskMngReq", - "name": "dataDiskRegInfo", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/webtool.DataDiskMngReq" - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200',}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/settings/resources/datadisk/region/": { - "get": { - "description": "[DataDiskListByRegion] Data Disk List를 connection으로 조회합니다.\n해당리전에 등록 된 DataDisk 목록. connection 필요\nUI 에서 용이하게 쓰기 위함 (콤보 선택용)", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "datadisk" - ], - "summary": "Data Disk List 조회 (connection)", - "parameters": [ - { - "type": "string", - "description": "option", - "name": "option", - "in": "query", - "required": true - }, - { - "type": "string", - "description": "connectionName", - "name": "filterValParam", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'200','defaultNameSpaceID': namespaceID,'dataDiskInfoList': dataDiskInfoList,}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/api/test/apitest/searchapi/": { - "post": { - "description": "[ApiSearch] Api 핸들러를 찾아 Swagger 로 이동합니다.", - "produces": [ - "text/html" - ], - "tags": [ - "debug" - ], - "summary": "Api Search swagger : todo : 삭제", - "responses": { - "200": { - "description": "redirect", - "schema": { - "type": "html" - } - } - } - } - }, - "/api/test/connection/list/": { - "get": { - "description": "[CloudConnectionAllList] 모든 connection을 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "debug" - ], - "summary": "모든 connection 조회", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/models.CloudConnection" - } - } - } - } - } - }, - "/api/test/connection/list/bycred": { - "post": { - "description": "[TestCloudConnection] credential로 가능한 Connection 조회합니다.", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "debug" - ], - "summary": "credential로 가능한 Connection 조회", - "parameters": [ - { - "description": "models.Credentials", - "name": "credential", - "in": "body", - "required": true, - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/models.Credential" - } - } - } - ], - "responses": { - "200": { - "description": "{'message':'success','status':'respStatus'}", - "schema": { - "type": "string" - } - }, - "500": { - "description": "{'error': err.Error(),'status': '500',}", - "schema": { - "type": "string" - } - } - } - } - }, - "/auth/landing/mngform/": { - "get": { - "description": "[AuthLandingForm] 렌딩 화면을 렌더링합니다. AuthLanding shows a landing page to login", - "produces": [ - "text/html" - ], - "tags": [ - "auth" - ], - "summary": "렌딩 화면 렌더링", - "responses": { - "200": { - "description": "auth/landing.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/auth/signin/mngform/": { - "get": { - "description": "[AuthNewForm] 로그인 화면을 렌더링합니다. AuthNew loads the signin page", - "produces": [ - "text/html" - ], - "tags": [ - "auth" - ], - "summary": "로그인 화면 렌더링", - "responses": { - "200": { - "description": "auth/new.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/operations/globaldashboard/mngform/": { - "get": { - "description": "[GlobalDashboardGet] Global Dashboard 폼을 렌더링 합니다. GlobalDashboardMngForm default implementation.", - "produces": [ - "text/html" - ], - "tags": [ - "globaldashboard" - ], - "summary": "Global Dashboard 폼 렌더링 : TODO", - "responses": { - "200": { - "description": "operations/globaldashboard/mngform.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/settings/connection/mngform/": { - "get": { - "description": "[ConnectionMngForm] ConnectionForm은 Connection 설정 폼을 렌더링합니다.", - "produces": [ - "text/html" - ], - "tags": [ - "connection" - ], - "summary": "Connection 설정 폼 렌더링", - "responses": { - "200": { - "description": "settings/connection/mngform.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/settings/resources/datadisk/mngform/": { - "get": { - "description": "[DataDiskMngForm] 데이터 디스크 화면을 렌더링합니다.", - "produces": [ - "text/html" - ], - "tags": [ - "datadisk" - ], - "summary": "데이터 디스크 화면 렌더링", - "responses": { - "200": { - "description": "settings/datadisk/mngform.html", - "schema": { - "type": "html" - } - } - } - } - }, - "/test/apitest/mngform/": { - "get": { - "description": "[ApiTestForm] ApiTest를 렌더링 합니다.", - "produces": [ - "text/html" - ], - "tags": [ - "debug" - ], - "summary": "Api test mngform : todo : 삭제", - "responses": { - "200": { - "description": "adminconfig/apitest/mngform.html", - "schema": { - "type": "html" - } - } - } - } - } - }, - "definitions": { - "mcir.TbDataDiskReq": { - "type": "object", - "properties": { - "connectionName": { - "type": "string" - }, - "cspDataDiskId": { - "type": "string" - }, - "description": { - "type": "string" - }, - "diskSize": { - "type": "string" - }, - "diskType": { - "type": "string" - }, - "name": { - "type": "string" - }, - "providerId": { - "description": "connection 을 provider, regname으로 대체를 위해 추가", - "type": "string" - }, - "providerName": { - "type": "string" - }, - "regionName": { - "type": "string" - }, - "zoneName": { - "type": "string" - } - } - }, - "mcir.TbDataDiskUpsizeReq": { - "type": "object", - "properties": { - "description": { - "type": "string" - }, - "diskSize": { - "type": "string" - }, - "providerId": { - "type": "string" - }, - "providerName": { - "type": "string" - }, - "regionName": { - "type": "string" - }, - "zoneName": { - "type": "string" - } - } - }, - "models.Category": { - "type": "object", - "properties": { - "category_name": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "parent_category_id": { - "type": "string" - }, - "sort": { - "type": "integer" - }, - "updated_at": { - "type": "string" - } - } - }, - "models.CloudConnection": { - "type": "object", - "properties": { - "connectionName": { - "type": "string" - }, - "connection_id": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "credential": { - "$ref": "#/definitions/models.Credential" - }, - "credential_id": { - "type": "string" - }, - "driver": { - "$ref": "#/definitions/models.Driver" - }, - "driver_id": { - "type": "string" - }, - "provider": { - "$ref": "#/definitions/models.CloudProvider" - }, - "provider_id": { - "description": "사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함.", - "type": "string" - }, - "region": { - "$ref": "#/definitions/models.Region" - }, - "region_id": { - "type": "string" - }, - "updated_at": { - "type": "string" - } - } - }, - "models.CloudConnections": { - "type": "array", - "items": { - "$ref": "#/definitions/models.CloudConnection" - } - }, - "models.CloudProvider": { - "type": "object", - "properties": { - "created_at": { - "type": "string" - }, - "provider_id": { - "type": "string" - }, - "provider_name": { - "type": "string" - }, - "updated_at": { - "type": "string" - } - } - }, - "models.Credential": { - "type": "object", - "properties": { - "cloudConnections": { - "description": "사용 될 참조", - "allOf": [ - { - "$ref": "#/definitions/models.CloudConnections" - } - ] - }, - "created_at": { - "type": "string" - }, - "credentialKeyValues": { - "description": "여러개는 객체", - "type": "array", - "items": { - "$ref": "#/definitions/models.CredentialKeyvalue" - } - }, - "credentialName": { - "type": "string" - }, - "id": { - "type": "string" - }, - "provider": { - "$ref": "#/definitions/models.CloudProvider" - }, - "provider_id": { - "description": "사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함.", - "type": "string" - }, - "updated_at": { - "type": "string" - }, - "userLevel": { - "type": "string" - } - } - }, - "models.CredentialKeyvalue": { - "type": "object", - "properties": { - "created_at": { - "type": "string" - }, - "credential": { - "$ref": "#/definitions/models.Credential" - }, - "credential_id": { - "type": "string" - }, - "id": { - "type": "string" - }, - "key": { - "type": "string" - }, - "updated_at": { - "type": "string" - }, - "value": { - "type": "string" - } - } - }, - "models.Driver": { - "type": "object", - "properties": { - "cloudConnections": { - "description": "CloudConnection *CloudConnection `belongs_to:\"cloud_connection\"`", - "type": "array", - "items": { - "$ref": "#/definitions/models.CloudConnection" - } - }, - "created_at": { - "type": "string" - }, - "driver_name": { - "type": "string" - }, - "id": { - "type": "string" - }, - "lib_file_name": { - "type": "string" - }, - "provider": { - "$ref": "#/definitions/models.CloudProvider" - }, - "provider_id": { - "type": "string" - }, - "updated_at": { - "type": "string" - } - } - }, - "models.Menu": { - "type": "object", - "properties": { - "alias": { - "description": "Path string `json:\"path\" db:\"path\"`\nAlias string `json:\"alias\" db:\"alias\"`", - "type": "string" - }, - "category": { - "$ref": "#/definitions/models.Category" - }, - "category_id": { - "description": "사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함.", - "type": "string" - }, - "created_at": { - "type": "string" - }, - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "sort": { - "type": "integer" - }, - "updated_at": { - "type": "string" - }, - "visible": { - "type": "boolean" - } - } - }, - "models.Region": { - "type": "object", - "properties": { - "created_at": { - "type": "string" - }, - "id": { - "type": "string" - }, - "provider": { - "$ref": "#/definitions/models.CloudProvider" - }, - "provider_id": { - "type": "string" - }, - "regionKeyValue": { - "type": "array", - "items": { - "$ref": "#/definitions/models.RegionKeyvalue" - } - }, - "regionName": { - "type": "string" - }, - "updated_at": { - "type": "string" - } - } - }, - "models.RegionGroup": { - "type": "object", - "properties": { - "created_at": { - "type": "string" - }, - "csp_region_name": { - "description": "raw query로 호출하여 return하기위해 추가", - "type": "string" - }, - "provider_id": { - "description": "사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함. transaction으로 호출해야 relation이 적용 됨. 그냥 query로 호출하면 null.", - "type": "string" - }, - "provider_name": { - "description": "raw query로 호출하여 return하기위해 추가", - "type": "string" - }, - "region_group_id": { - "type": "string" - }, - "region_group_name": { - "type": "string" - }, - "region_id": { - "type": "string" - }, - "region_name": { - "description": "raw query로 호출하여 return하기위해 추가", - "type": "string" - }, - "updated_at": { - "type": "string" - } - } - }, - "models.RegionKeyvalue": { - "type": "object", - "properties": { - "created_at": { - "type": "string" - }, - "id": { - "type": "string" - }, - "key": { - "type": "string" - }, - "region": { - "$ref": "#/definitions/models.Region" - }, - "region_id": { - "type": "string" - }, - "updated_at": { - "type": "string" - }, - "value": { - "type": "string" - } - } - }, - "spider.CredentialInfo": { - "type": "object", - "properties": { - "CredentialName": { - "description": "user(username, password, email)", - "type": "string" - }, - "KeyValueInfoList": { - "type": "array", - "items": { - "$ref": "#/definitions/spider.SpKeyValueInfo" - } - }, - "ProviderName": { - "type": "string" - } - } - }, - "spider.DriverInfo": { - "type": "object", - "properties": { - "DriverLibFileName": { - "type": "string" - }, - "DriverName": { - "description": "user(username, password, email)", - "type": "string" - }, - "ProviderName": { - "type": "string" - } - } - }, - "spider.RegionInfo": { - "type": "object", - "properties": { - "KeyValueInfoList": { - "type": "array", - "items": { - "$ref": "#/definitions/spider.SpKeyValueInfo" - } - }, - "ProviderName": { - "type": "string" - }, - "RegionName": { - "type": "string" - } - } - }, - "spider.SpKeyValueInfo": { - "type": "object", - "properties": { - "Key": { - "type": "string" - }, - "Value": { - "type": "string" - } - } - }, - "webtool.DataDiskCreateReq": { - "type": "object", - "properties": { - "attachVmId": { - "description": "VmID string `json:\"vmId\"`", - "type": "string" - }, - "connectionName": { - "type": "string" - }, - "cspDataDiskId": { - "type": "string" - }, - "description": { - "type": "string" - }, - "diskSize": { - "type": "string" - }, - "diskType": { - "type": "string" - }, - "mcisId": { - "description": "Attach VMID", - "type": "string" - }, - "name": { - "description": "tbmcir.TbDataDiskReq", - "type": "string" - } - } - }, - "webtool.DataDiskMngReq": { - "type": "object", - "properties": { - "attachDataDiskList": { - "description": "attach list", - "type": "array", - "items": { - "type": "string" - } - }, - "createDataDiskList": { - "description": "create disk list", - "type": "array", - "items": { - "$ref": "#/definitions/webtool.DataDiskCreateReq" - } - }, - "dataDiskList": { - "description": "del disk list", - "type": "array", - "items": { - "type": "string" - } - }, - "dettachDataDiskList": { - "description": "detach list", - "type": "array", - "items": { - "type": "string" - } - } - } - } - } -} \ No newline at end of file diff --git a/mc_web_console_api/docs/swagger.yaml b/mc_web_console_api/docs/swagger.yaml deleted file mode 100644 index fe12b261..00000000 --- a/mc_web_console_api/docs/swagger.yaml +++ /dev/null @@ -1,1978 +0,0 @@ -basePath: / -definitions: - mcir.TbDataDiskReq: - properties: - connectionName: - type: string - cspDataDiskId: - type: string - description: - type: string - diskSize: - type: string - diskType: - type: string - name: - type: string - providerId: - description: connection 을 provider, regname으로 대체를 위해 추가 - type: string - providerName: - type: string - regionName: - type: string - zoneName: - type: string - type: object - mcir.TbDataDiskUpsizeReq: - properties: - description: - type: string - diskSize: - type: string - providerId: - type: string - providerName: - type: string - regionName: - type: string - zoneName: - type: string - type: object - models.Category: - properties: - category_name: - type: string - created_at: - type: string - description: - type: string - id: - type: string - parent_category_id: - type: string - sort: - type: integer - updated_at: - type: string - type: object - models.CloudConnection: - properties: - connection_id: - type: string - connectionName: - type: string - created_at: - type: string - credential: - $ref: '#/definitions/models.Credential' - credential_id: - type: string - driver: - $ref: '#/definitions/models.Driver' - driver_id: - type: string - provider: - $ref: '#/definitions/models.CloudProvider' - provider_id: - description: '사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함.' - type: string - region: - $ref: '#/definitions/models.Region' - region_id: - type: string - updated_at: - type: string - type: object - models.CloudConnections: - items: - $ref: '#/definitions/models.CloudConnection' - type: array - models.CloudProvider: - properties: - created_at: - type: string - provider_id: - type: string - provider_name: - type: string - updated_at: - type: string - type: object - models.Credential: - properties: - cloudConnections: - allOf: - - $ref: '#/definitions/models.CloudConnections' - description: 사용 될 참조 - created_at: - type: string - credentialKeyValues: - description: 여러개는 객체 - items: - $ref: '#/definitions/models.CredentialKeyvalue' - type: array - credentialName: - type: string - id: - type: string - provider: - $ref: '#/definitions/models.CloudProvider' - provider_id: - description: '사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함.' - type: string - updated_at: - type: string - userLevel: - type: string - type: object - models.CredentialKeyvalue: - properties: - created_at: - type: string - credential: - $ref: '#/definitions/models.Credential' - credential_id: - type: string - id: - type: string - key: - type: string - updated_at: - type: string - value: - type: string - type: object - models.Driver: - properties: - cloudConnections: - description: CloudConnection *CloudConnection `belongs_to:"cloud_connection"` - items: - $ref: '#/definitions/models.CloudConnection' - type: array - created_at: - type: string - driver_name: - type: string - id: - type: string - lib_file_name: - type: string - provider: - $ref: '#/definitions/models.CloudProvider' - provider_id: - type: string - updated_at: - type: string - type: object - models.Menu: - properties: - alias: - description: |- - Path string `json:"path" db:"path"` - Alias string `json:"alias" db:"alias"` - type: string - category: - $ref: '#/definitions/models.Category' - category_id: - description: '사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함.' - type: string - created_at: - type: string - description: - type: string - id: - type: string - name: - type: string - sort: - type: integer - updated_at: - type: string - visible: - type: boolean - type: object - models.Region: - properties: - created_at: - type: string - id: - type: string - provider: - $ref: '#/definitions/models.CloudProvider' - provider_id: - type: string - regionKeyValue: - items: - $ref: '#/definitions/models.RegionKeyvalue' - type: array - regionName: - type: string - updated_at: - type: string - type: object - models.RegionGroup: - properties: - created_at: - type: string - csp_region_name: - description: raw query로 호출하여 return하기위해 추가 - type: string - provider_id: - description: '사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함. transaction으로 호출해야 relation이 - 적용 됨. 그냥 query로 호출하면 null.' - type: string - provider_name: - description: raw query로 호출하여 return하기위해 추가 - type: string - region_group_id: - type: string - region_group_name: - type: string - region_id: - type: string - region_name: - description: raw query로 호출하여 return하기위해 추가 - type: string - updated_at: - type: string - type: object - models.RegionKeyvalue: - properties: - created_at: - type: string - id: - type: string - key: - type: string - region: - $ref: '#/definitions/models.Region' - region_id: - type: string - updated_at: - type: string - value: - type: string - type: object - spider.CredentialInfo: - properties: - CredentialName: - description: user(username, password, email) - type: string - KeyValueInfoList: - items: - $ref: '#/definitions/spider.SpKeyValueInfo' - type: array - ProviderName: - type: string - type: object - spider.DriverInfo: - properties: - DriverLibFileName: - type: string - DriverName: - description: user(username, password, email) - type: string - ProviderName: - type: string - type: object - spider.RegionInfo: - properties: - KeyValueInfoList: - items: - $ref: '#/definitions/spider.SpKeyValueInfo' - type: array - ProviderName: - type: string - RegionName: - type: string - type: object - spider.SpKeyValueInfo: - properties: - Key: - type: string - Value: - type: string - type: object - webtool.DataDiskCreateReq: - properties: - attachVmId: - description: VmID string `json:"vmId"` - type: string - connectionName: - type: string - cspDataDiskId: - type: string - description: - type: string - diskSize: - type: string - diskType: - type: string - mcisId: - description: Attach VMID - type: string - name: - description: tbmcir.TbDataDiskReq - type: string - type: object - webtool.DataDiskMngReq: - properties: - attachDataDiskList: - description: attach list - items: - type: string - type: array - createDataDiskList: - description: create disk list - items: - $ref: '#/definitions/webtool.DataDiskCreateReq' - type: array - dataDiskList: - description: del disk list - items: - type: string - type: array - dettachDataDiskList: - description: detach list - items: - type: string - type: array - type: object -host: localhost:3000 -info: - contact: - name: - url: https://github.com/ - description: API Swagger page - license: {} - title: API - version: ?? -paths: - /adminconfig/category/mngform/: - get: - description: '[CategoryMngForm] Category 설정 폼을 렌더링합니다.' - produces: - - text/html - responses: - "200": - description: adminconfig/categorymng/mngform.html - schema: - type: html - summary: Category 설정 폼 렌더링 - tags: - - adminconfig - /adminconfig/config/mngform/: - get: - description: '[AdminMngForm] Admin 관리자 설정 폼을 렌더링합니다. : not implement -- 아직 기획된바 - 없음.' - produces: - - text/html - responses: - "200": - description: adminconfig/regiongroup/mngform.html - schema: - type: html - summary: '관리자 설정 폼 렌더링 : not implement -- 아직 기획된바 없음.' - tags: - - adminconfig - /adminconfig/menu/mngform/: - get: - description: '[MenuMngForm] Menu 설정 폼을 렌더링합니다.' - produces: - - text/html - responses: - "200": - description: adminconfig/menumng/mngform.html - schema: - type: html - summary: Menu 설정 폼 렌더링 - tags: - - adminconfig - /api/adminconfig/category/: - delete: - consumes: - - application/json - description: '[CategoryDel] 카테고리를 삭제합니다.' - parameters: - - description: models.Category - in: body - name: Category - required: true - schema: - $ref: '#/definitions/models.Category' - produces: - - application/json - responses: - "200": - description: '{''message'': ''success'', ''status'': 200}' - schema: - type: string - summary: Category 삭제 - tags: - - adminconfig - get: - description: '[CategoryList] categoryName을 받아 categoryList를 반환합니다.' - parameters: - - description: categoryName - in: query - name: categoryName - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{"message":"success","status":respStatus.StatusCode,"regionGroup":categoryList,}' - schema: - type: string - "400": - description: '{''error'':''respStatus.Message'',''error'':''respStatus.Message''}' - schema: - type: string - security: - - CSRFTokenHeader: [] - summary: Category 리스트 조회 - tags: - - adminconfig - post: - consumes: - - application/json - description: '[RegCategory] 카테고리를 등록합니다.' - parameters: - - description: models.Category - in: body - name: Category - required: true - schema: - $ref: '#/definitions/models.Category' - produces: - - application/json - responses: - "200": - description: '{''message'': ''success'', ''status'': 200}' - schema: - type: string - summary: Category 등록 - tags: - - adminconfig - /api/adminconfig/category/id/{categoryName}/: - get: - description: '[CategoryGet] categoryName을 받아 category 단건을 반환합니다.' - parameters: - - description: categoryName - in: query - name: categoryName - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'',''category'':''category'',}' - schema: - type: string - "400": - description: '{''error'':''errors.WithStack(err)''}' - schema: - type: string - security: - - CSRFTokenHeader: [] - summary: Category 단건 조회 - tags: - - adminconfig - /api/adminconfig/menu/: - delete: - description: '[DelMenu] models.Menu를 받아 메뉴를 단건 삭제합니다.' - parameters: - - description: models.Menu - in: body - name: menu - required: true - schema: - $ref: '#/definitions/models.Menu' - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200''}' - schema: - type: string - "400": - description: '{''error'':''errors.WithStack(err)''}' - schema: - type: string - summary: Menu 삭제 - tags: - - adminconfig - get: - description: '[MenuList] menuId, menuName, menuAlias, categoryId 중 순서로 마지막 한개를 - 받아 메뉴 리스트를 반환합니다.' - parameters: - - description: menuId - in: query - name: menuId - type: string - - description: menuName - in: query - name: menuName - type: string - - description: menuAlias - in: query - name: menuAlias - type: string - - description: categoryId - in: query - name: categoryId - type: string - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'', ''menuList'': - ''menuList''}' - schema: - type: string - "400": - description: '{''error'':''errors.WithStack(err)''}' - schema: - type: string - summary: Menu 리스트 조회 - tags: - - adminconfig - post: - description: '[RegMenu] models.Menu를 받아 메뉴를 단건 등록합니다.' - parameters: - - description: models.Menu - in: body - name: menu - required: true - schema: - $ref: '#/definitions/models.Menu' - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200''}' - schema: - type: string - "400": - description: '{''error'':''errors.WithStack(err)''}' - schema: - type: string - summary: Menu 등록 - tags: - - adminconfig - put: - description: '[UpdateMenu] models.Menu를 받아 메뉴를 단건 업데이트합니다.' - parameters: - - description: models.Menu - in: body - name: menu - required: true - schema: - $ref: '#/definitions/models.Menu' - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200''}' - schema: - type: string - "400": - description: '{''error'':''errors.WithStack(err)''}' - schema: - type: string - summary: Menu 업데이트 - tags: - - adminconfig - /api/adminconfig/menu/id/{menuId}/: - get: - description: '[GetMenu] menuId와 menuName, menuAlias, categoryId 중 순서로 마지막 한개를 - 받아 메뉴를 반환합니다.' - parameters: - - description: menuId - in: path - name: menuId - required: true - type: string - - description: menuName - in: query - name: menuName - type: string - - description: menuAlias - in: query - name: menuAlias - type: string - - description: categoryId - in: query - name: categoryId - type: string - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'', ''menu'': ''menu''}' - schema: - type: string - "400": - description: '{''error'':''errors.WithStack(err)''}' - schema: - type: string - summary: Menu 조회 - tags: - - adminconfig - /api/adminconfig/menu/tree/: - get: - description: '[MenuTree] category, menu구조를 tree형태로 쿼리하여 반환합니다.' - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'', ''menutree'': - ''menutree''}' - schema: - type: string - "400": - description: '{''error'':''errors.WithStack(err)''}' - schema: - type: string - summary: Menu Tree 조회 - tags: - - adminconfig - /api/adminconfig/regiongroup/: - delete: - consumes: - - application/json - description: '[DelRegionGroup] 리전 그룹을 삭제합니다.' - parameters: - - description: models.RegionGroup - in: body - name: regionGroup - required: true - schema: - $ref: '#/definitions/models.RegionGroup' - produces: - - application/json - responses: - "200": - description: '{''message'': ''success'', ''status'': respStatus.StatusCode}' - schema: - type: string - "500": - description: '{''error'':''respStatus.Message'',''status'':respStatus.StatusCode}' - schema: - type: string - summary: Region Group 삭제 - tags: - - adminconfig - get: - description: '[RegionGroupList] providerId 와 regionGroupName 을 받아 RegionGroupList를 - 반환합니다.' - parameters: - - description: provider - in: query - name: provider - required: true - type: string - - description: regionGroupName - in: query - name: regionGroupName - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{"message":"success","status":respStatus.StatusCode,"regionGroup":regionGroupList,}' - schema: - type: string - "400": - description: '{''error'':''respStatus.Message'',''error'':''respStatus.Message''}' - schema: - type: string - summary: RegionGroup 리스트 조회 - tags: - - adminconfig - post: - consumes: - - application/json - description: '[RegRegionGroup] 리전 그룹을 등록합니다.' - parameters: - - description: models.RegionGroup - in: body - name: regionGroup - required: true - schema: - $ref: '#/definitions/models.RegionGroup' - produces: - - application/json - responses: - "200": - description: '{''message'': ''success'', ''status'': respStatus.StatusCode}' - schema: - type: string - "500": - description: '{''error'':''respStatus.Message'',''status'':respStatus.StatusCode}' - schema: - type: string - summary: Region Group 등록 - tags: - - adminconfig - /api/adminconfig/regiongroup/{regionGroupId}: - get: - description: '[GetRegionGroup] regionGroupId와 providerId, regionGroupName, - regionId 중 한개를 받아 regionGroup을 반환합니다.' - parameters: - - description: regionGroupId - in: path - name: regionGroupId - required: true - type: string - - description: providerId - in: query - name: providerId - type: string - - description: regionGroupName - in: query - name: regionGroupName - type: string - - description: regionId - in: query - name: regionId - type: string - produces: - - application/json - responses: - "200": - description: '{"message":"success","status":respStatus.StatusCode,"regionGroup":regionGroup,}' - schema: - type: string - "500": - description: '{''error'':''err.Error()'',''status'':''500''}' - schema: - type: string - summary: RegionGroup 단건 Vpc 조회 - tags: - - adminconfig - /api/auth/logout/: - get: - consumes: - - application/json - description: '[AuthDestroy] 로그아웃을 합니다. clears the session and logs a user out' - produces: - - application/json - responses: - "200": - description: '{''success-Flash'': ''You have been logged out!''}' - schema: - type: string - summary: 로그아웃 - tags: - - auth - /api/auth/signin/: - post: - consumes: - - application/json - description: '[AuthCreate] 존재하는 계정으로 로그인을 시도합니다. attempts to log the user in - with an existing account.' - parameters: - - description: Email - in: formData - name: Email - required: true - type: string - - description: Password - in: formData - name: Password - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{''message'': ''success'', ''user'': ''u''}' - schema: - type: string - "500": - description: '{''error'':''verrs'',''status'':''http.StatusUnauthorized''}' - schema: - type: string - summary: 로그인 - tags: - - auth - /api/settings/connection/: - get: - consumes: - - application/json - description: '[CloudConnectionList] connection 리스트를 조회합니다.' - parameters: - - description: providerId - in: query - name: providerId - required: true - type: string - - description: regionName - in: query - name: regionName - required: true - type: string - - description: zoneName - in: query - name: zoneName - required: true - type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - items: - $ref: '#/definitions/models.CloudConnection' - type: array - summary: CloudConnection 리스트 조회 - tags: - - connection - post: - consumes: - - application/json - description: |- - [CloudConnectionCreate] ConnectionReg 등록 후 connection 목록조회 - ---- SpiderConnectionReg -> CloudConnectionCreate로 변경 - ---- is_cb 가 아니면 connection 등록 후 db 저장하도록 보완할 것. - ---- TODO : SpiderCloudConnectionConfigReg 로 변경할 것 - ---- TODO : cloud_connections 저장 MconRegCloudConnection -> 저장실패시 생성한 connection 삭제하도록 - ---- TODO : cloud_connections table 조회하도록 변경할 것. : MconCloudConnectionList() - ---- TODO : SpiderCloudConnectionConfigList 로 변경할 것. - parameters: - - description: is_cb - in: query - name: is_cb - required: true - type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - type: string - summary: CloudConnection 생성 - tags: - - connection - put: - consumes: - - application/json - description: '[CloudConnectionUpdate] Cloud Connection을 수정합니다. -- not implementated - yet' - produces: - - application/json - responses: - "200": - description: '{''message'': ''success'',''status'': ''not implementated - yet'',}' - schema: - type: string - summary: Cloud Connection을 업데이트 -- not implementated yet - tags: - - connection - /api/settings/connection/available/: - get: - consumes: - - application/json - description: '[AvailableCloudConnectionList] 사용가능한 Cloud Connection 목록을 조회합니다. - Check avaiable ConnectionConfig list for creating MCIS Dynamically' - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''respStatus''}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: 사용가능한 Cloud Connection 리스트 조회 - tags: - - connection - /api/settings/connection/credential/: - delete: - consumes: - - application/json - description: '[CredentialDelete] Credential 삭제합니다.' - parameters: - - description: models.Credential - in: body - name: paramCredential - required: true - schema: - $ref: '#/definitions/models.Credential' - produces: - - application/json - responses: - "200": - description: success - schema: - type: string - summary: Credential 삭제 - tags: - - connection - get: - consumes: - - application/json - description: |- - [CredentialList] Credential 리스트를 조회합니다. - SpiderCredentialList -> CredentialList 으로 변경 GET - parameters: - - description: is_cb - in: query - name: is_cb - required: true - type: string - produces: - - application/json - responses: - "200": - description: 'message":"success","status":"200","Credential": credentialList,}' - schema: - type: json - "500": - description: 'error": err.Error(),"status": "500",}' - schema: - type: json - summary: Credential 리스트 조회 - tags: - - connection - post: - consumes: - - application/json - description: '[CredentialCreate] Credential을 생성합니다.' - parameters: - - description: spider.CredentialInfo - in: body - name: credentialInfo - required: true - schema: - $ref: '#/definitions/spider.CredentialInfo' - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'',}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Credential 생성 - tags: - - connection - /api/settings/connection/credential/id/{credential}/: - get: - consumes: - - application/json - description: '[CredentialGet] Credential 단건 조회합니다' - parameters: - - description: iscredential_cb - in: path - name: credential - required: true - type: string - - description: is_cb - in: query - name: is_cb - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'',''Credential'': - ''credentialInfo'',}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Credential 단건 조회 - tags: - - connection - /api/settings/connection/credential/sync/: - get: - consumes: - - application/json - description: '[SyncCredential] CB 조회내역을 DB 에 저장합니다. Credential 동기화[handler.SyncCredential(c)]' - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''respStatus''}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Credential 동기화 - tags: - - connection - /api/settings/connection/driver/: - delete: - consumes: - - application/json - description: '[DriverDelete] Driver를 삭제합니다.' - parameters: - - description: models.Driver - in: body - name: paramDriver - required: true - schema: - $ref: '#/definitions/models.Driver' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/models.Driver' - summary: Driver 삭제 - tags: - - connection - get: - consumes: - - application/json - description: '[DriverList] driver 리스트 조회합니다. -- swagger TEST 오류 확인함.' - produces: - - application/json - responses: - "200": - description: OK - schema: - items: - $ref: '#/definitions/models.Driver' - type: array - summary: Driver 리스트 조회 - tags: - - connection - post: - consumes: - - application/json - description: |- - [DriverCreate] Driver를 생성합니다. - SpiderDriverReg 등록 -> DriverCreate 로 변경 /settings/connection/driver - parameters: - - description: spider.DriverInfo - in: body - name: paramdriverInfoDriver - required: true - schema: - $ref: '#/definitions/spider.DriverInfo' - - description: is_cb - in: query - name: is_cb - required: true - type: string - produces: - - application/json - responses: - "200": - description: 'message": "success","status": "respStatus",}' - schema: - type: json - "201": - description: 'error": respStatus.Message,"status": respStatus.StatusCode,}' - schema: - type: json - "500": - description: 'error": err.Error(),"status": 500,}' - schema: - type: json - summary: Driver 생성 - tags: - - connection - /api/settings/connection/driver/id/{driverId}/: - get: - consumes: - - application/json - description: '[DriverGet] Driver를 단건 조회합니다.' - parameters: - - description: driver - in: path - name: driver - required: true - type: string - - description: is_cb - in: query - name: is_cb - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{''message'': ''success'',''status'': ''respStatus'',''Driver'': - ''driverInfo'',}' - schema: - type: string - summary: Driver 단건 조회 - tags: - - connection - /api/settings/connection/driver/spider/: - get: - consumes: - - application/json - description: '[SpiderDriverList] Spider Driver 리스트를 조회합니다.' - produces: - - application/json - responses: - "200": - description: '{''message'': ''success'',''status'': ''respStatus'',''Driver'': - ''driverList'',}' - schema: - type: string - summary: Spider Driver 리스트 조회 - tags: - - connection - /api/settings/connection/driver/spider/id/{driver}/: - delete: - consumes: - - application/json - description: '[SpiderDriverDelete] Spider Driver를 삭제합니다.' - parameters: - - description: driver - in: path - name: driver - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{''message'': ''success'',''status'': ''respStatus''}' - schema: - type: string - summary: Spider Driver 삭제 - tags: - - connection - /api/settings/connection/driver/sync/: - get: - consumes: - - application/json - description: '[SyncDriver] CB 조회내역을 DB 에 저장합니다. Driver 동기화[handler.SyncDriver(c)]' - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''respStatus''}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Driver 동기화 - tags: - - connection - /api/settings/connection/generate/all/bycredential: - get: - consumes: - - application/json - description: |- - [GenerateConnectionsByAllCredential] credential 별로 지정 Provider의 모든 region에 대해 connection 생성. - - 모든 credential에 대해 connection 생성 genconnection - - handler.GetCredentialList() - - (현재 설정된 credential 목록 : 목록에서는 key의 value는 ...으로 표시) - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''respStatus''}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: credential 별 모든 region connection 생성 - tags: - - connection - /api/settings/connection/generate/bycredential: - get: - consumes: - - application/json - description: '[GenerateConnectionsByCredential] credential 별로 지정 Provider의 모든 - region에 대해 connection 생성.' - parameters: - - description: providerId - in: query - name: providerId - required: true - type: string - - description: credentialName - in: query - name: credentialName - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''respStatus''}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: credential 별 지정 Provider 모든 region 생성 - tags: - - connection - /api/settings/connection/healthcheck/agent/: - get: - consumes: - - application/json - description: '[AgentHealthCheck] MCIS 또는 VM 에 agent 상태 확인' - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''respStatus''}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Agent Health Check -- TODO - tags: - - connection - /api/settings/connection/healthcheck/framework/: - get: - consumes: - - application/json - description: |- - [FrameworkHealthCheck] 프레임워크 헬스체크 - - c.Params().Get("framework") - - DF의 response 에서 return결과가 ""으로 들어와 204를 return 함. - - DF에서 정상적인 message 보내라고 할 것. - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''respStatus''}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Framework Health Check - tags: - - connection - /api/settings/connection/id/{configName}/: - delete: - consumes: - - application/json - description: '[CloudConnectionDelete] Connection을 삭제합니다.' - parameters: - - description: paramConfigName - in: path - name: paramConfigName - required: true - type: string - - description: is_cb - in: query - name: is_cb - required: true - type: string - produces: - - application/json - responses: - "200": - description: success - schema: - type: string - summary: Connection 삭제 - tags: - - connection - /api/settings/connection/id/{connectionId}/: - get: - consumes: - - application/json - description: '[CloudConnectionGet] connection 단건 조회합니다.' - parameters: - - description: connectionId - in: path - name: connectionId - required: true - type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - items: - $ref: '#/definitions/models.CloudConnection' - type: array - summary: connection 단건 조회 - tags: - - connection - /api/settings/connection/provider/sync/: - get: - consumes: - - application/json - description: '[SyncCloudProvider] CB 조회내역을 DB 에 저장합니다. CloudProvider 동기화[handler.SyncCloudProvider(c)]' - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''respStatus''}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: CloudProvider 동기화 - tags: - - connection - /api/settings/connection/providers/: - get: - consumes: - - application/json - description: |- - [CloudProviderList] Cloud Provider 리스트를 조회합니다. - DB에서 가져오게 할 것인가? - SpiderProviderList 삭제 함 23.07.06 - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''respStatus'',''Region'':''resionInfo''}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Cloud Provider 리스트 조회 - tags: - - connection - /api/settings/connection/region/: - delete: - consumes: - - application/json - description: '[RegionDelete] Region을 삭제합니다.' - parameters: - - description: models.Region - in: body - name: paramRegion - required: true - schema: - $ref: '#/definitions/models.Region' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/models.Driver' - summary: Region 삭제 - tags: - - connection - get: - consumes: - - application/json - description: '[RegionList] Region 리스트를 조회합니다.' - parameters: - - description: is_cb - in: query - name: is_cb - required: true - type: string - - description: filterKeyParam - in: query - name: filterKeyParam - required: true - type: string - - description: filterValParam - in: query - name: filterValParam - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'',''Region'':''regionList''}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Region 리스트 조회 - tags: - - connection - post: - consumes: - - application/json - description: '[RegionCreate] Region을 생성합니다.' - parameters: - - description: spider.RegionInfo - in: body - name: regionInfo - required: true - schema: - $ref: '#/definitions/spider.RegionInfo' - - description: is_cb - in: query - name: is_cb - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'',}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Region 생성 - tags: - - connection - /api/settings/connection/region/all: - get: - consumes: - - application/json - description: '[RegionAllList] Region의 모든 리스트를 조회합니다.' - produces: - - application/json - responses: - "200": - description: OK - schema: - items: - $ref: '#/definitions/models.Region' - type: array - summary: Region 모든 리스트를 조회 - tags: - - connection - /api/settings/connection/region/id/{paramRegion}/: - get: - consumes: - - application/json - description: '[RegionGet] Region 단건 조회합니다.' - parameters: - - description: paramRegion - in: path - name: paramRegion - required: true - type: string - - description: is_cb - in: query - name: is_cb - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''respStatus'',''Region'':''resionInfo''}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Region 단건 조회 - tags: - - connection - /api/settings/connection/region/sync/: - get: - consumes: - - application/json - description: '[SyncRegion] CB 조회내역을 DB 에 저장합니다. Region 동기화[handler.SyncRegion(c)]' - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''respStatus''}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Region 동기화 - tags: - - connection - /api/settings/connection/spider/: - get: - consumes: - - application/json - description: '[SpiderConnectionList] SPIDER connection 리스트를 조회합니다.' - produces: - - application/json - responses: - "200": - description: OK - schema: - type: string - summary: SPIDER ConnectionList 목록조회 - tags: - - connection - /api/settings/connection/spider/id/{connectionId}/: - get: - consumes: - - application/json - description: '[SpiderConnectionGet] SPIDER connection 단건을 조회합니다.' - parameters: - - description: connectionId - in: path - name: connectionId - required: true - type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - type: string - summary: SPIDER Connection 단건조회 - tags: - - connection - /api/settings/connection/sync/: - get: - consumes: - - application/json - description: '[SyncConnection] CB 조회내역을 DB 에 저장합니다. Connection 동기화[handler.SyncConnection(c)]' - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''respStatus''}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Connection 동기화 - tags: - - connection - /api/settings/resources/datadisk/: - get: - consumes: - - application/json - description: '[DataDiskList] Data Disk List를 조회합니다.' - parameters: - - description: option - in: query - name: option - required: true - type: string - - description: filterKey - in: query - name: filterKey - required: true - type: string - - description: filterVal - in: query - name: filterVal - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'',''defaultNameSpaceID'': - namespaceID,''status'': respStatus.StatusCode,}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Data Disk List 조회 - tags: - - datadisk - post: - consumes: - - application/json - description: '[DataDiskReg] Data Disk를 생성합니다.' - parameters: - - description: tbmcir.TbDataDiskReq - in: body - name: dataDiskRegInfo - required: true - schema: - $ref: '#/definitions/mcir.TbDataDiskReq' - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'',}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: DataDisk 생성 - tags: - - datadisk - /api/settings/resources/datadisk/availabledisk/: - get: - consumes: - - application/json - description: '[McisVmAvailableDataDiskList] VM 이사용가능한 DataDisk Id 목록 조회' - parameters: - - description: mcisId - in: query - name: mcisId - required: true - type: string - - description: vmID - in: query - name: vmID - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'',''dataDiskInfoList'':dataDiskInfoList}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Mcis Vm Available Data Disk List 조회 - tags: - - datadisk - /api/settings/resources/datadisk/id/{dataDiskId}/: - delete: - consumes: - - application/json - description: '[DataDiskDel] Data Disk를 삭제합니다.' - parameters: - - description: dataDiskId - in: path - name: dataDiskId - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200''}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Data Disk 삭제 - tags: - - datadisk - get: - consumes: - - application/json - description: '[DataDiskGet] Data Disk를 dataDiskId로 조회합니다.' - parameters: - - description: dataDiskId - in: path - name: dataDiskId - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'',''dataDiskInfo'': - dataDiskInfo}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Data Disk 단건 조회 - tags: - - datadisk - put: - consumes: - - application/json - description: '[DataDiskPut] Data Disk를 변경합니다.' - parameters: - - description: dataDiskId - in: path - name: dataDiskId - required: true - type: string - - description: tbmcir.TbDataDiskUpsizeReq - in: body - name: dataDiskUpsizeReq - required: true - schema: - $ref: '#/definitions/mcir.TbDataDiskUpsizeReq' - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'',''DataDiskInfo'': - DataDiskInfo}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Data Disk 변경 - tags: - - datadisk - /api/settings/resources/datadisk/lookup/: - get: - consumes: - - application/json - description: |- - [AvailableDataDiskTypeList] Provider, Region에서 사용가능한 DiskType 조회(DiskLookup) - spider의 cloudos_meta.yaml 참조 - parameters: - - description: providerId - in: query - name: providerId - required: true - type: string - - description: regionName - in: query - name: regionName - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'',''DiskInfoList'':availableDiskTypeList}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Available Data Disk List 조회 - tags: - - datadisk - /api/settings/resources/datadisk/mngdata/: - post: - consumes: - - application/json - description: |- - [DataDiskMng] Data Disk Mng(CRD) 합니다. - Create, Update, Delete가 한번에 일어나는 경우 사용 - ex) table에 addRow로 추가하고 delet로 삭제한 것들을 한번에 저장할 때. - parameters: - - description: webtool.DataDiskMngReq - in: body - name: dataDiskRegInfo - required: true - schema: - $ref: '#/definitions/webtool.DataDiskMngReq' - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'',}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Data Disk CRD 한번에 - tags: - - datadisk - /api/settings/resources/datadisk/region/: - get: - consumes: - - application/json - description: |- - [DataDiskListByRegion] Data Disk List를 connection으로 조회합니다. - 해당리전에 등록 된 DataDisk 목록. connection 필요 - UI 에서 용이하게 쓰기 위함 (콤보 선택용) - parameters: - - description: option - in: query - name: option - required: true - type: string - - description: connectionName - in: query - name: filterValParam - required: true - type: string - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''200'',''defaultNameSpaceID'': - namespaceID,''dataDiskInfoList'': dataDiskInfoList,}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: Data Disk List 조회 (connection) - tags: - - datadisk - /api/test/apitest/searchapi/: - post: - description: '[ApiSearch] Api 핸들러를 찾아 Swagger 로 이동합니다.' - produces: - - text/html - responses: - "200": - description: redirect - schema: - type: html - summary: 'Api Search swagger : todo : 삭제' - tags: - - debug - /api/test/connection/list/: - get: - consumes: - - application/json - description: '[CloudConnectionAllList] 모든 connection을 조회합니다.' - produces: - - application/json - responses: - "200": - description: OK - schema: - items: - $ref: '#/definitions/models.CloudConnection' - type: array - summary: 모든 connection 조회 - tags: - - debug - /api/test/connection/list/bycred: - post: - consumes: - - application/json - description: '[TestCloudConnection] credential로 가능한 Connection 조회합니다.' - parameters: - - description: models.Credentials - in: body - name: credential - required: true - schema: - items: - $ref: '#/definitions/models.Credential' - type: array - produces: - - application/json - responses: - "200": - description: '{''message'':''success'',''status'':''respStatus''}' - schema: - type: string - "500": - description: '{''error'': err.Error(),''status'': ''500'',}' - schema: - type: string - summary: credential로 가능한 Connection 조회 - tags: - - debug - /auth/landing/mngform/: - get: - description: '[AuthLandingForm] 렌딩 화면을 렌더링합니다. AuthLanding shows a landing page - to login' - produces: - - text/html - responses: - "200": - description: auth/landing.html - schema: - type: html - summary: 렌딩 화면 렌더링 - tags: - - auth - /auth/signin/mngform/: - get: - description: '[AuthNewForm] 로그인 화면을 렌더링합니다. AuthNew loads the signin page' - produces: - - text/html - responses: - "200": - description: auth/new.html - schema: - type: html - summary: 로그인 화면 렌더링 - tags: - - auth - /operations/globaldashboard/mngform/: - get: - description: '[GlobalDashboardGet] Global Dashboard 폼을 렌더링 합니다. GlobalDashboardMngForm - default implementation.' - produces: - - text/html - responses: - "200": - description: operations/globaldashboard/mngform.html - schema: - type: html - summary: 'Global Dashboard 폼 렌더링 : TODO' - tags: - - globaldashboard - /settings/connection/mngform/: - get: - description: '[ConnectionMngForm] ConnectionForm은 Connection 설정 폼을 렌더링합니다.' - produces: - - text/html - responses: - "200": - description: settings/connection/mngform.html - schema: - type: html - summary: Connection 설정 폼 렌더링 - tags: - - connection - /settings/resources/datadisk/mngform/: - get: - description: '[DataDiskMngForm] 데이터 디스크 화면을 렌더링합니다.' - produces: - - text/html - responses: - "200": - description: settings/datadisk/mngform.html - schema: - type: html - summary: 데이터 디스크 화면 렌더링 - tags: - - datadisk - /test/apitest/mngform/: - get: - description: '[ApiTestForm] ApiTest를 렌더링 합니다.' - produces: - - text/html - responses: - "200": - description: adminconfig/apitest/mngform.html - schema: - type: html - summary: 'Api test mngform : todo : 삭제' - tags: - - debug -swagger: "2.0" diff --git a/mc_web_console_api/fwmodels/CloudConnectionInfo.go b/mc_web_console_api/fwmodels/CloudConnectionInfo.go deleted file mode 100644 index 22c40a0e..00000000 --- a/mc_web_console_api/fwmodels/CloudConnectionInfo.go +++ /dev/null @@ -1,15 +0,0 @@ -package fwmodels - -// ConnectionConfigData와 뭐가 다른건지... TODO : ConnectionConfigData와 합칠 수 있는지 검토할 것 --> 사용하지 않는것으로 보임 -type CloudConnectionInfo struct { - ID string `json:"id"` - ConfigName string `json:"ConfigName"` - ProviderName string `json:"ProviderName"` - DriverName string `json:"DriverName"` - CredentialName string `json:"CredentialName"` - RegionName string `json:"RegionName"` - Description string `json:"description"` - - ProviderID string `json:"ProviderId"` -} -type CloudConnectionInfos []CloudConnectionInfo diff --git a/mc_web_console_api/fwmodels/ErrorInfo.go b/mc_web_console_api/fwmodels/ErrorInfo.go deleted file mode 100644 index bccd9cf1..00000000 --- a/mc_web_console_api/fwmodels/ErrorInfo.go +++ /dev/null @@ -1,11 +0,0 @@ -package fwmodels - -// client와 서버가 통신하면서 사용자정보로 이용할 객체 -// 최초로그인 시 Username set. -// page redirect 될 때 default namespace 설정 -// - namespace가 없으면 새로 생성 -// - namespace가 1개면 default로 set -// - namespace가 2개 이상이면 화면에서 default set 하도록 -type ErrorInfo struct { - Message string `json:"message"` -} diff --git a/mc_web_console_api/fwmodels/LoginInfo.go b/mc_web_console_api/fwmodels/LoginInfo.go deleted file mode 100644 index 245627c3..00000000 --- a/mc_web_console_api/fwmodels/LoginInfo.go +++ /dev/null @@ -1,15 +0,0 @@ -package fwmodels - -// client와 서버가 통신하면서 사용자정보로 이용할 객체 -// 최초로그인 시 Username set. -// page redirect 될 때 default namespace 설정 -// - namespace가 없으면 새로 생성 -// - namespace가 1개면 default로 set -// - namespace가 2개 이상이면 화면에서 default set 하도록 -type LoginInfo struct { - UserID string `json:"UserID"` - Username string `json:"Username"` - DefaultNameSpaceID string `json:"DefaultNameSpaceID"` - DefaultNameSpaceName string `json:"DefaultNameSpaceName"` - AccessToken string `json:"AccessToken"` -} diff --git a/mc_web_console_api/fwmodels/McisRequest.go b/mc_web_console_api/fwmodels/McisRequest.go deleted file mode 100644 index 5dfe252e..00000000 --- a/mc_web_console_api/fwmodels/McisRequest.go +++ /dev/null @@ -1,11 +0,0 @@ -package fwmodels - -// 사용하지 않는것으로 보임 -type McisRequest struct { - VmSpec []string `form:"vmspec"` - NameSpace string `form:"namespace"` - McisName string `form:"mcis_name"` - VmName []string `form:"vmName"` - Provider []string `form:"provider"` - SecurityGroupIds []string `form:"sg"` -} diff --git a/mc_web_console_api/fwmodels/README.md b/mc_web_console_api/fwmodels/README.md deleted file mode 100644 index c1b9b9d9..00000000 --- a/mc_web_console_api/fwmodels/README.md +++ /dev/null @@ -1,21 +0,0 @@ -DB model - -- 대상 system에 따라 folder 로 분류 : dragonfly, ladybug, spider, tumblebug -- 기본 struct : 업무Info 등 -- 조회(request용) struct : 업무reqInfo 등 기본 struct에서 요청에 필요한 것들만 추출 - -- list의 경우 [] 를 사용한다. -- 첫번째 자리 : 변수명 -- 두번째 자리 : 자료형 -- 세번째 자리 : json객체명 - type InspectResourcesResponse struct { - ResourcesOnCsp ResourcesOnCsp `json:"resourcesOnCsp"` - ResourcesOnSpider ResourcesOnSpider `json:"resourcesOnSpider"` - ResourcesOnTumblebug []ResourcesOnTumblebug `json:"resourcesOnTumblebug"` - } - -. Renderling 할 때에는 변수명을 사용하나 -axios 등 통신을 할 경우에는 json객체명을 사용 - -. 변수명의 경우 첫글자 대문자 -. json 인 경우 첫글자 소문자 diff --git a/mc_web_console_api/fwmodels/ReqInfo.go b/mc_web_console_api/fwmodels/ReqInfo.go deleted file mode 100644 index 247251b2..00000000 --- a/mc_web_console_api/fwmodels/ReqInfo.go +++ /dev/null @@ -1,9 +0,0 @@ -package fwmodels - -// 사용하지 않는것으로 보임 -type ReqInfo struct { - UserID string `json:"userid"` - UserName string `json:"username"` - Email string `json:"email"` - Password string `json:"password"` -} diff --git a/mc_web_console_api/fwmodels/ResultInfo.go b/mc_web_console_api/fwmodels/ResultInfo.go deleted file mode 100644 index ff3522c9..00000000 --- a/mc_web_console_api/fwmodels/ResultInfo.go +++ /dev/null @@ -1,8 +0,0 @@ -package fwmodels - -// 호출 후 결과값을 return하기 위한 객체 -// Create, Delete 등의 결과로 message만 넘기는 경우가 있어 필요함. -type ResultInfo struct { - Message string `json:"message"` - Result string `json:"result"` -} diff --git a/mc_web_console_api/fwmodels/User.go b/mc_web_console_api/fwmodels/User.go deleted file mode 100644 index fd3ace1b..00000000 --- a/mc_web_console_api/fwmodels/User.go +++ /dev/null @@ -1,12 +0,0 @@ -package fwmodels - -// 사용하지 않는것으로 보임 -type User struct { - //user(username, password, email) - UserID string `json:"userid"` - Username string `json:"username"` - Email string `json:"email"` - Password string `json:"password"` -} - -type Users []User diff --git a/mc_web_console_api/fwmodels/WebStatus.go b/mc_web_console_api/fwmodels/WebStatus.go deleted file mode 100644 index 396b4cd0..00000000 --- a/mc_web_console_api/fwmodels/WebStatus.go +++ /dev/null @@ -1,7 +0,0 @@ -package fwmodels - -// 호출 후 상태값을 return하기 위한 객체 -type WebStatus struct { - StatusCode int `json:"code"` - Message string `json:"message"` -} diff --git a/mc_web_console_api/fwmodels/dragonfly/McisMonitoringOnDemandInfo.go b/mc_web_console_api/fwmodels/dragonfly/McisMonitoringOnDemandInfo.go deleted file mode 100644 index 8f55981e..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/McisMonitoringOnDemandInfo.go +++ /dev/null @@ -1,10 +0,0 @@ -package dragonfly - -// 멀티 클라우드 인프라 MCIS 온디맨드 모니터링 정보 결과용 -type McisMonitoringOnDemandInfo struct { - Result string `json:"result"` - Unit string `json:"unit"` - Desc string `json:"desc"` - Elapsed string `json:"elapsed"` - Specid string `json:"specid"` -} diff --git a/mc_web_console_api/fwmodels/dragonfly/McisMonitoringOnDemandInfoReq.go b/mc_web_console_api/fwmodels/dragonfly/McisMonitoringOnDemandInfoReq.go deleted file mode 100644 index 467c1ac2..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/McisMonitoringOnDemandInfoReq.go +++ /dev/null @@ -1,10 +0,0 @@ -package dragonfly - -// 멀티 클라우드 인프라 MCIS 온디맨드 모니터링 정보 결과용 -type McisMonitoringOnDemandInfoReq struct { - NameSpaceID string `json:"ns_id"` - McisID string `json:"mcis_id"` - VmID string `json:"vm_id"` - AgentIp string `json:"agent_ip"` - MetricName string `json:"metric_name"` // InitDB, ResetDB, CpuM, CpuS, MemR, MemW, FioW, FioR, DBW, DBR, Rtt, Mrtt -} diff --git a/mc_web_console_api/fwmodels/dragonfly/MonitoringConfig.go b/mc_web_console_api/fwmodels/dragonfly/MonitoringConfig.go deleted file mode 100644 index 6602b75a..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/MonitoringConfig.go +++ /dev/null @@ -1,23 +0,0 @@ -package dragonfly - -// 모니터링 정책 설정 -type MonitoringConfig struct { - //AgentInterval int `json:"agent_interval"` //모니터링 에이전트 수집 주기 - //CollectorInterval int `json:"collector_interval"` //모니터링 콜렉터 Aggregate 주기 - - // ScheduleInterval int `json:"schedule_interval"` - MaxHostCount int `json:"max_host_count"` // 단일 콜렉터에서 수집하는 최대 가상머신 수 - // AgentTTL int `json:"agent_TTL"` - MonitoringPolicy string `json:"monitoring_policy"` - - DefaultPolicy string `json:"default_policy"` // push - PullerInterval int `json:"puller_interval"` // - PullerAggregateInterval int `json:"puller_aggregate_interval"` - AggregateType string `json:"aggregate_type"` // avg - DeployType string `json:"deploy_type"` // compose - McisAgentInterval int `json:"mcis_agent_interval"` //모니터링 에이전트 수집 주기 - McisCollectorInterval int `json:"mcis_collector_interval"` //모니터링 콜렉터 Aggregate 주기 - Mck8sAgentInterval int `json:"mck8s_agent_interval"` //모니터링 에이전트 수집 주기 - Mck8sCollectorInterval int `json:"mck8s_collector_interval"` //모니터링 콜렉터 Aggregate 주기 - -} diff --git a/mc_web_console_api/fwmodels/dragonfly/MonitoringConfigReg.go b/mc_web_console_api/fwmodels/dragonfly/MonitoringConfigReg.go deleted file mode 100644 index 60059019..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/MonitoringConfigReg.go +++ /dev/null @@ -1,19 +0,0 @@ -package dragonfly - -// 모니터링 정책 설정 Put 할때는 아래 3가지만 보냄 -type MonitoringConfigReg struct { - //AgentInterval int `json:"agent_interval"` //모니터링 에이전트 수집 주기 - //CollectorInterval int `json:"collector_interval"` //모니터링 콜렉터 Aggregate 주기 - McisAgentInterval int `json:"mcis_agent_interval"` //모니터링 에이전트 수집 주기 - McisCollectorInterval int `json:"mcis_collector_interval"` //모니터링 콜렉터 Aggregate 주기 - Mck8sAgentInterval int `json:"mck8s_agent_interval"` //모니터링 에이전트 수집 주기 - Mck8sCollectorInterval int `json:"mck8s_collector_interval"` //모니터링 콜렉터 Aggregate 주기 - - MaxHostCount int `json:"max_host_count"` // 단일 콜렉터에서 수집하는 최대 가상머신 수 - MonitoringPolicy string `json:"monitoring_policy"` // "agentCount" - DefaultPolicy string `json:"default_policy"` // push - PullerInterval int `json:"puller_interval"` // - PullerAggregateInterval int `json:"puller_aggregate_interval"` - AggregateType string `json:"aggregate_type"` // avg - DeployType string `json:"deploy_type"` // compose -} diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertEventHandlerInfo.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertEventHandlerInfo.go deleted file mode 100644 index d2713eb1..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertEventHandlerInfo.go +++ /dev/null @@ -1,15 +0,0 @@ -package dragonfly - -// 알람 이벤트 핸들러 -type VmMonitoringAlertEventHandlerInfo struct { - EventHandlerID string `json:"id"` // 네임스페이스 아이디 - Name string `json:"name"` // 이벤트 핸들러 이름 - Type string `json:"type"` // 네임스페이스 아이디 - Options EventHandlerOption `json:"options"` // - -} - -type EventHandlerOption struct { - Url string `json:"url"` - Channel string `json:"channel"` -} diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertEventHandlerInfoReg.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertEventHandlerInfoReg.go deleted file mode 100644 index c9254c44..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertEventHandlerInfoReg.go +++ /dev/null @@ -1,10 +0,0 @@ -package dragonfly - -// 알람 이벤트 핸들러 -type VmMonitoringAlertEventHandlerInfoReg struct { - Name string `json:"name"` // 이벤트 핸들러 이름 - Type string `json:"type"` // 네임스페이스 아이디 - //Options EventHandlerOption `json:"options"` // - Url string `json:"url"` - Channel string `json:"channel"` -} diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertEventHandlerSlackInfo.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertEventHandlerSlackInfo.go deleted file mode 100644 index 72e99262..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertEventHandlerSlackInfo.go +++ /dev/null @@ -1,15 +0,0 @@ -package dragonfly - -// 알람 이벤트 핸들러 -// type이 slack이면 option항목에 url, channel -type VmMonitoringAlertEventHandlerSlackInfo struct { - EventHandlerID string `json:"id"` // 네임스페이스 아이디 - Name string `json:"name"` // 이벤트 핸들러 이름 - Type string `json:"type"` // 이벤트 핸들러 유형 ( "slack" | "smtp" ) - Options EventHandlerOptionSlack `json:"options"` // -} - -type EventHandlerOptionSlack struct { - Url string `json:"url"` // slack hook URL - Channel string `json:"channel"` // slack 알람 채널 (#kapacitor-alert) -} diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertEventHandlerSmtpInfo.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertEventHandlerSmtpInfo.go deleted file mode 100644 index 014abf6b..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertEventHandlerSmtpInfo.go +++ /dev/null @@ -1,19 +0,0 @@ -package dragonfly - -// 알람 이벤트 핸들러 -// type이 slack이면 option항목에 url, channel -type VmMonitoringAlertEventHandlerSmtpInfo struct { - EventHandlerID string `json:"id"` // 네임스페이스 아이디 - Name string `json:"name"` // 이벤트 핸들러 이름 - Type string `json:"type"` // 이벤트 핸들러 유형 ( "slack" | "smtp" ) - Options EventHandlerOptionSmtp `json:"options"` // -} - -type EventHandlerOptionSmtp struct { - Host string `json:"host"` // 서버 ex)localhost - Port string `json:"port"` // - Username string `json:"username"` // - Password string `json:"password"` // - FromDomain string `json:"from"` // - ToDomains []string `json:"to"` // -} diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertInfo.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertInfo.go deleted file mode 100644 index d256bb72..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertInfo.go +++ /dev/null @@ -1,17 +0,0 @@ -package dragonfly - -type VmMonitoringAlertInfo struct { - AlertName string `json:"name"` // 알람 이름 - Measurement string `json:"measurement"` // 알람 메트릭 유형 ( "cpu" | "mem" | "disk" ) - TargetType string `json:"target_type"` // 알람 임계치 타겟 유형 ( "NS" | "MCIS" | "VM" ) - TargetID string `json:"target_id"` // 알람 임계치 타겟 아이디 - EventDuration string `json:"event_duration"` // 알람 주기 - Metric string `json:"metric"` // 알람 메트릭 - AlertMathExpression string `json:"alert_math_expression"` // 알람 임계치 정규식 ( "equal" | "greater" | "equalgreater" | "less" | "equalless" ) - AlertThreshold int `json:"alert_threshold"` // 알람 임계치 값 - WarnEventCnt int `json:"warn_event_cnt"` // 알람 임계치 횟수 (warn) - CriticEventCnt int `json:"critic_event_cnt"` // 알람 임계치 횟수 (critic) - AlertEventType string `json:"alert_event_type"` // 이벤트 핸들러 유형 ( "slack" | "smtp" ) - AlertEventName string `json:"alert_event_name"` // 이벤트 핸들러 이름 - AlertEventMessage string `json:"alert_event_message"` // 이벤트 핸들러 메세지 -} diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertLog.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertLog.go deleted file mode 100644 index 25f0b8f8..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringAlertLog.go +++ /dev/null @@ -1,23 +0,0 @@ -package dragonfly - -import ( - "time" - // "fmt" -) - -type VmMonitoringAlertLog struct { - Id string `json:"id"` - Time time.Time `json:"time"` - Level string `json:"level"` - Message string `json:"message"` -} - -// type JSONTime struct { -// time.Time -// } - -// func (t JSONTime)MarshalJSON() ([]byte, error) { -// //do your serializing here -// stamp := fmt.Sprintf("\"%s\"", time.Time(t).Format("Mon Jan _2")) -// return []byte(stamp), nil -// } diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInfo.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInfo.go deleted file mode 100644 index 205acfe5..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInfo.go +++ /dev/null @@ -1,16 +0,0 @@ -package dragonfly - -// Monitoring 수신 Data return용. parameter에 따라 return받는 객체가 다름.. -//type VmMonitoringInfo struct { -// Name string `json:"name"` -// Tags VmMonitoringTag `json:"tags"` -// ValuesList []interface{} `json:"values"` -// //ValuesList []VmMonitoringValue `json:"values"` -//} - -type VmMonitoringInfo struct { - ValuesByCpu VmMonitoringInfoByCpu - ValuesByDisk VmMonitoringInfoByDisk - ValuesByMemory VmMonitoringInfoByMemory - ValuesByNetwork VmMonitoringInfoByNetwork -} diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInfoByCpu.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInfoByCpu.go deleted file mode 100644 index d5bb15f8..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInfoByCpu.go +++ /dev/null @@ -1,24 +0,0 @@ -package dragonfly - -// Monitoring 수신 Data return용 - -type VmMonitoringInfoByCpu struct { - Name string `json:"name"` - Tags VmMonitoringTag `json:"tags"` - ValuesList []VmMonitoringValueByCpu `json:"values"` -} - -type VmMonitoringValueByCpu struct { - CpuGuest float64 `json:"cpu_guest"` - CpuGuestNice float64 `json:"cpu_guest_nice"` - CpuHintr float64 `json:"cpu_hintr"` - CpuIdle float64 `json:"cpu_idle"` - CpuIowait float64 `json:"cpu_iowait"` - CpuNice float64 `json:"cpu_nice"` - CpuSintr float64 `json:"cpu_sintr"` - CpuSteal float64 `json:"cpu_steal"` - CpuSystem float64 `json:"cpu_system"` - CpuUser float64 `json:"cpu_user"` - CpuUtilization float64 `json:"cpu_utilization"` - Time string `json:"time"` -} diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInfoByDisk.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInfoByDisk.go deleted file mode 100644 index 5f4815c8..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInfoByDisk.go +++ /dev/null @@ -1,21 +0,0 @@ -package dragonfly - -// Monitoring 수신 Data return용 -type VmMonitoringInfoByDisk struct { - Name string `json:"name"` - Tags VmMonitoringTag `json:"tags"` - ValuesList []VmMonitoringValueByDisk `json:"values"` -} -type VmMonitoringValueByDisk struct { - Free float64 `json:"free"` - ReadBytes float64 `json:"read_bytes"` - ReadTime float64 `json:"read_time"` - Reads float64 `json:"reads"` - Total float64 `json:"total"` - Used float64 `json:"used"` - UsedPercent float64 `json:"used_percent"` - WriteBytes float64 `json:"write_bytes"` - WriteTime float64 `json:"write_time"` - Writes float64 `json:"writes"` - Time string `json:"time"` -} diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInfoByMemory.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInfoByMemory.go deleted file mode 100644 index eb78094a..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInfoByMemory.go +++ /dev/null @@ -1,17 +0,0 @@ -package dragonfly - -// Monitoring 수신 Data return용 -type VmMonitoringInfoByMemory struct { - Name string `json:"name"` - Tags VmMonitoringTag `json:"tags"` - ValuesList []VmMonitoringValueByMemory `json:"values"` -} -type VmMonitoringValueByMemory struct { - MemCached float64 `json:"mem_cached"` - MemFree float64 `json:"mem_free"` - MemShared float64 `json:"mem_shared"` - MemTotal float64 `json:"mem_total"` - MemUsed float64 `json:"mem_used"` - MemUtilization float64 `json:"mem_utilization"` - Time string `json:"time"` -} diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInfoByNetwork.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInfoByNetwork.go deleted file mode 100644 index 6cf1ba59..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInfoByNetwork.go +++ /dev/null @@ -1,15 +0,0 @@ -package dragonfly - -// Monitoring 수신 Data return용 -type VmMonitoringInfoByNetwork struct { - Name string `json:"name"` - Tags VmMonitoringTag `json:"tags"` - ValuesList []VmMonitoringValueByNetwork `json:"values"` -} -type VmMonitoringValueByNetwork struct { - BytesIn float64 `json:"bytes_in"` - BytesOut float64 `json:"bytes_out"` - PktsIn float64 `json:"pkts_in"` - PktsOut float64 `json:"pkts_out"` - Time string `json:"time"` -} diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInstallReg.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInstallReg.go deleted file mode 100644 index 23afbd5b..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringInstallReg.go +++ /dev/null @@ -1,15 +0,0 @@ -package dragonfly - -// Dragonfly에서 사용하는 AgentInstall -type VmMonitoringInstallReg struct { - NameSpaceID string `json:"ns_id"` // 네임스페이스 아이디 - McisID string `json:"mcis_id"` // MCIS 아이디 - VmID string `json:"vm_id"` // VM 아이디 - PublicIp string `json:"public_ip"` // VM의 퍼블릭 아이피 - UserName string `json:"user_name"` // VM의 SSH 접속 계정(cb-user) - SshKey string `json:"ssh_key"` // VM의 SSH 접근 키 - SshKeyName string `json:"ssh_key_name"` - CspType string `json:"cspType"` // VM의 CSP 정보 (aws ... 등) - Port string `json:"port"` - //Port int `json:"port"` -} diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringOnDemand.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringOnDemand.go deleted file mode 100644 index 0fc4d21c..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringOnDemand.go +++ /dev/null @@ -1,10 +0,0 @@ -package dragonfly - -// 멀티 클라우드 인프라 VM 온디맨드 모니터링 정보 조회용 -type VmMonitoringOnDemand struct { - NameSpaceID string `json:"ns_id"` - McisID string `json:"mcis_id"` - VmID string `json:"vm_id"` - AgentIp string `json:"agent_ip"` - MetricName string `json:"metric_name"` // 메트릭 정보 ( "InitDB" | "ResetDB" | "CpuM" | "CpuS" | "MemR" | "MemW" | "FioW" | "FioR" | "DBW" | DBR" | "Rtt" | "Mrtt" ) -} diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringOnDemandInfo.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringOnDemandInfo.go deleted file mode 100644 index 53498b98..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringOnDemandInfo.go +++ /dev/null @@ -1,22 +0,0 @@ -package dragonfly - -// 멀티 클라우드 인프라 VM 온디맨드 모니터링 정보 결과용 -type VmMonitoringOnDemandInfo struct { - NameSpaceID string `json:"name"` - VmMonitoringTags VmMonitoringTagOnDemand `json:"tags"` - Time string `json:"time"` - VmMonitoringValues VmMonitoringValueOnDemand `json:"values"` -} - -type VmMonitoringTagOnDemand struct { - McisId string `json:"mcisId"` - NsId string `json:"nsId"` - VmId string `json:"vmId"` -} - -type VmMonitoringValueOnDemand struct { - BytesIn int `json:"bytes_in"` - BytesOut int `json:"bytes_out"` - PktsIn int `json:"pkts_in"` - PktsOut int `json:"pkts_out"` -} diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringReq.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringReq.go deleted file mode 100644 index 9f761084..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringReq.go +++ /dev/null @@ -1,14 +0,0 @@ -package dragonfly - -// VM Monitoring 시 parameter 전달용 -type VmMonitoringReq struct { - NameSpaceID string `json:"nameSpaceID"` - McisID string `json:"mcisID"` - VmID string `json:"vmID"` - AgentIp string `json:"agentIp"` - Metric string `json:"metric"` - PeriodType string `json:"periodType"` - StatisticsCriteria string `json:"statisticsCriteria"` - Duration string `json:"duration"` - WatchTime string `json:"watchTime"` -} diff --git a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringTag.go b/mc_web_console_api/fwmodels/dragonfly/VmMonitoringTag.go deleted file mode 100644 index 5534bca4..00000000 --- a/mc_web_console_api/fwmodels/dragonfly/VmMonitoringTag.go +++ /dev/null @@ -1,5 +0,0 @@ -package dragonfly - -type VmMonitoringTag struct { - VmID string `json:"vmId"` -} diff --git a/mc_web_console_api/fwmodels/ladybug/ClusterConfig.go b/mc_web_console_api/fwmodels/ladybug/ClusterConfig.go deleted file mode 100644 index 36bc6b3e..00000000 --- a/mc_web_console_api/fwmodels/ladybug/ClusterConfig.go +++ /dev/null @@ -1,13 +0,0 @@ -package ladybug - -type ClusterConfig struct { - InstallMonAgent string `json:"installMonAgent"` - Kubernetes Kubernetes `json:"kubernetes"` -} - -type Kubernetes struct { - NetworkCni string `json:"networkCni"` - PodCidr string `json:"podCidr"` - ServiceCidr string `json:"serviceCidr"` - ServiceDnsDomain string `json:"serviceDnsDomain"` -} diff --git a/mc_web_console_api/fwmodels/ladybug/ClusterConfigReq.go b/mc_web_console_api/fwmodels/ladybug/ClusterConfigReq.go deleted file mode 100644 index 0c049029..00000000 --- a/mc_web_console_api/fwmodels/ladybug/ClusterConfigReq.go +++ /dev/null @@ -1,24 +0,0 @@ -package ladybug - -type ClusterConfigReq struct { - InstallMonAgent string `json:"installMonAgent"` - Kubernetes ClusterConfigKubernetesReq `json:"kubernetes"` -} - -type ClusterConfigKubernetesReq struct { - Etcd string `json:"etcd"` - Loadbalancer string `json:"loadbalancer"` - - NetworkCni string `json:"networkCni"` - PodCidr string `json:"podCidr"` - ServiceCidr string `json:"serviceCidr"` - ServiceDnsDomain string `json:"serviceDnsDomain"` - - Storageclass ClusterStorageClassNfsReq `json:"storageclass"` - Version string `json:"version"` -} - -type ClusterStorageClassNfsReq struct { - Path string `json:"path"` - Server string `json:"server"` -} diff --git a/mc_web_console_api/fwmodels/ladybug/ClusterInfo.go b/mc_web_console_api/fwmodels/ladybug/ClusterInfo.go deleted file mode 100644 index 832bb08d..00000000 --- a/mc_web_console_api/fwmodels/ladybug/ClusterInfo.go +++ /dev/null @@ -1,25 +0,0 @@ -package ladybug - -// ladybug : cb-mcks 의 model.Cluster -type ClusterInfo struct { - ClusterConfig string `json:"clusterConfig"` - CpGroup string `json:"cpGroup"` - CpLeader string `json:"cpLeader"` - CreatedTime string `json:"createdTime"` - Description string `json:"description"` - Etcd string `json:"etcd"` //local, external - - InstallMonAgent string `json:"installMonAgent"` - K8sVersion string `json:"k8sVersion"` - - Kind int `json:"kind"` - Label int `json:"label"` - Loadbalancer int `json:"loadbalancer"` //haproxy, nlb - Mcis string `json:"mcis"` - Name string `json:"name"` - NameSpace string `json:"namespace"` - NetworkCni string `json:"networkCni"` //canal, kilo - Status ClusterStatus `json:"status"` - //UID string `json:"uid"`// deprecated - Nodes []NodeInfo `json:"nodes"` -} diff --git a/mc_web_console_api/fwmodels/ladybug/ClusterList.go b/mc_web_console_api/fwmodels/ladybug/ClusterList.go deleted file mode 100644 index fe4b0b89..00000000 --- a/mc_web_console_api/fwmodels/ladybug/ClusterList.go +++ /dev/null @@ -1,7 +0,0 @@ -package ladybug - -// ladybug -type ClusterList struct { - Kind string `json:"kind"` - Clusters []ClusterInfo `json:"items"` -} diff --git a/mc_web_console_api/fwmodels/ladybug/ClusterRegReq.go b/mc_web_console_api/fwmodels/ladybug/ClusterRegReq.go deleted file mode 100644 index 489a4e74..00000000 --- a/mc_web_console_api/fwmodels/ladybug/ClusterRegReq.go +++ /dev/null @@ -1,17 +0,0 @@ -package ladybug - -// ladybug : ClusterReq -type ClusterRegReq struct { - // ControlPlaneNodeCount int `json:"controlPlaneNodeCount"` - // ControlPlaneNodeSpec string `json:"controlPlaneNodeSpec"` - // Name string `json:"name"` - // WorkerNodeCount int `json:"workerNodeCount"` - // WorkerNodeSpec string `json:"workerNodeSpec"` - - Name string `json:"name"` - Label string `json:"label"` - Description string `json:"description"` - Config ClusterConfigReq `json:"config"` - ControlPlane []NodeSetReq `json:"controlPlane"` - Worker []NodeSetReq `json:"worker"` -} diff --git a/mc_web_console_api/fwmodels/ladybug/ClusterSimpleInfo.go b/mc_web_console_api/fwmodels/ladybug/ClusterSimpleInfo.go deleted file mode 100644 index 8ba77dc9..00000000 --- a/mc_web_console_api/fwmodels/ladybug/ClusterSimpleInfo.go +++ /dev/null @@ -1,18 +0,0 @@ -package ladybug - -// ClusterInfo의 간단버전. -type ClusterSimpleInfo struct { - ClusterConfig string `json:"clusterConfig"` - CpLeader string `json:"cpLeader"` - Kind int `json:"kind"` - Mcis string `json:"mcis"` - Name string `json:"name"` - NameSpace string `json:"namespace"` - NetworkCni string `json:"networkCni"` - Status string `json:"status"` - McksStatus string `json:"mcksStatus"` // icon(RUNNING, STOPPED, TERMINATED)를 나타내기 위한 변수 - UID string `json:"uid"` - Nodes []NodeSimpleInfo `json:"nodes"` - TotalNodeCount int `json:"totalNodeCount"` - NodeCountMap map[string]int `json:"nodeCountMap"` -} diff --git a/mc_web_console_api/fwmodels/ladybug/ClusterStatus.go b/mc_web_console_api/fwmodels/ladybug/ClusterStatus.go deleted file mode 100644 index e30b6566..00000000 --- a/mc_web_console_api/fwmodels/ladybug/ClusterStatus.go +++ /dev/null @@ -1,7 +0,0 @@ -package ladybug - -type ClusterStatus struct { - Message string `json:"message"` - Phase string `json:"phase"` //Pending, Provisioning, Provisioned, Failed - Reason int `json:"reason"` -} diff --git a/mc_web_console_api/fwmodels/ladybug/NodeConfig.go b/mc_web_console_api/fwmodels/ladybug/NodeConfig.go deleted file mode 100644 index 35bb3407..00000000 --- a/mc_web_console_api/fwmodels/ladybug/NodeConfig.go +++ /dev/null @@ -1,7 +0,0 @@ -package ladybug - -type NodeConfig struct { - Connection string `json:"connection"` - Count int `json:"count"` - Spec string `json:"spec"` -} diff --git a/mc_web_console_api/fwmodels/ladybug/NodeInfo.go b/mc_web_console_api/fwmodels/ladybug/NodeInfo.go deleted file mode 100644 index 353a2d9c..00000000 --- a/mc_web_console_api/fwmodels/ladybug/NodeInfo.go +++ /dev/null @@ -1,17 +0,0 @@ -package ladybug - -// ladybug -type NodeInfo struct { - CreatedTime string `json:"createdTime"` - Credential string `json:"credential"` - Csp string `json:"csp"` - CspLabel string `json:"cspLable"` - ZoneLabel string `json:"zoneLable"` - Kind string `json:"kind"` // Node 냐 cluster냐 - Name string `json:"name"` - PublicIp string `json:"publicIp"` - Role string `json:"role"` // Control-plane냐, Worker냐 - Spec string `json:"spec"` - //UID string `json:"uid"` -} -type Nodes []NodeInfo diff --git a/mc_web_console_api/fwmodels/ladybug/NodeList.go b/mc_web_console_api/fwmodels/ladybug/NodeList.go deleted file mode 100644 index 08e52d34..00000000 --- a/mc_web_console_api/fwmodels/ladybug/NodeList.go +++ /dev/null @@ -1,8 +0,0 @@ -package ladybug - -// ladybug -// Node의 array이나 parameter 추가된 것(kind)이 있음. Nodes 와 NodeList는 다른것임. -type NodeList struct { - Items []NodeInfo `json:"items"` - Kind string `json:"kind"` -} diff --git a/mc_web_console_api/fwmodels/ladybug/NodeOnlyRegReq.go b/mc_web_console_api/fwmodels/ladybug/NodeOnlyRegReq.go deleted file mode 100644 index 088d3980..00000000 --- a/mc_web_console_api/fwmodels/ladybug/NodeOnlyRegReq.go +++ /dev/null @@ -1,8 +0,0 @@ -package ladybug - -// Node만 추가시에는 ControlPlane 없이 Worker만 사용한다. -type NodeOnlyRegReq struct { - // ControlPlane []NodeConfig `json:"controlPlane"` - //Worker []NodeReq `json:"worker"` - Worker []NodeReq `json:"worker"` -} diff --git a/mc_web_console_api/fwmodels/ladybug/NodeRegReq.go b/mc_web_console_api/fwmodels/ladybug/NodeRegReq.go deleted file mode 100644 index 44a85f31..00000000 --- a/mc_web_console_api/fwmodels/ladybug/NodeRegReq.go +++ /dev/null @@ -1,8 +0,0 @@ -package ladybug - -// ladybug -type NodeRegReq struct { - // ControlPlane []NodeConfig `json:"controlPlane"` - //Worker []NodeConfig `json:"worker"` - Worker []NodeSetReq `json:"worker"` -} diff --git a/mc_web_console_api/fwmodels/ladybug/NodeReq.go b/mc_web_console_api/fwmodels/ladybug/NodeReq.go deleted file mode 100644 index f61cbe49..00000000 --- a/mc_web_console_api/fwmodels/ladybug/NodeReq.go +++ /dev/null @@ -1,8 +0,0 @@ -package ladybug - -// ladybug -type NodeReq struct { - Config string `json:"config"` - WorkerNodeCount int `json:"workerNodeCount"` - WorkerNodeSpec string `json:"workerNodeSpec"` -} diff --git a/mc_web_console_api/fwmodels/ladybug/NodeSetReq.go b/mc_web_console_api/fwmodels/ladybug/NodeSetReq.go deleted file mode 100644 index beea727d..00000000 --- a/mc_web_console_api/fwmodels/ladybug/NodeSetReq.go +++ /dev/null @@ -1,13 +0,0 @@ -package ladybug - -type NodeSetReq struct { - Connection string `json:"connection"` - Count int `json:"count"` - Spec string `json:"spec"` - RootDisk RootDiskInfo `json:"rootDisk"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/ladybug/NodeSimpleInfo.go b/mc_web_console_api/fwmodels/ladybug/NodeSimpleInfo.go deleted file mode 100644 index ff0415aa..00000000 --- a/mc_web_console_api/fwmodels/ladybug/NodeSimpleInfo.go +++ /dev/null @@ -1,15 +0,0 @@ -package ladybug - -// NodeInfo 의 간단버전 credential 등 제거 -type NodeSimpleInfo struct { - NodeIndex int `json:"nodeIndex"` - TotalNodeCount int `json:"totalNodeCount"` - NodeCsp string `json:"csp"` - NodeKind string `json:"kind"` - NodeName string `json:"name"` - NodePublicIp string `json:"publicIp"` - NodeRole string `json:"role"` - NodeSpec string `json:"spec"` - // NodeUID string `json:"uid"` -} -type NodeSimpleInfos []NodeSimpleInfo diff --git a/mc_web_console_api/fwmodels/ladybug/RootDiskInfo.go b/mc_web_console_api/fwmodels/ladybug/RootDiskInfo.go deleted file mode 100644 index e3f449ef..00000000 --- a/mc_web_console_api/fwmodels/ladybug/RootDiskInfo.go +++ /dev/null @@ -1,6 +0,0 @@ -package ladybug - -type RootDiskInfo struct { - Type string `json:"type"` - Size string `json:"size"` -} diff --git a/mc_web_console_api/fwmodels/ladybug/StatusInfo.go b/mc_web_console_api/fwmodels/ladybug/StatusInfo.go deleted file mode 100644 index 85cb2eef..00000000 --- a/mc_web_console_api/fwmodels/ladybug/StatusInfo.go +++ /dev/null @@ -1,8 +0,0 @@ -package ladybug - -// ladybug -type StatusInfo struct { - Code int `json:"code"` - Kind string `json:"kind"` - Message string `json:"message"` -} diff --git a/mc_web_console_api/fwmodels/spider/CloudConnectionConfigInfo.go b/mc_web_console_api/fwmodels/spider/CloudConnectionConfigInfo.go deleted file mode 100644 index a20e391c..00000000 --- a/mc_web_console_api/fwmodels/spider/CloudConnectionConfigInfo.go +++ /dev/null @@ -1,14 +0,0 @@ -package spider - -// ConnectionConfigData -> CloudConnectionConfigInfo 로 변경 -type CloudConnectionConfigInfo struct { - //user(username, password, email) - ConfigName string `json:"ConfigName"` - ProviderName string `json:"ProviderName"` - DriverName string `json:"DriverName"` - CredentialName string `json:"CredentialName"` - RegionName string `json:"RegionName"` - - ProviderID string `json:"ProviderId"` -} -type CloudConnectionConfigInfos []CloudConnectionConfigInfo diff --git a/mc_web_console_api/fwmodels/spider/ClusterInfo.go b/mc_web_console_api/fwmodels/spider/ClusterInfo.go deleted file mode 100644 index 2c694d8d..00000000 --- a/mc_web_console_api/fwmodels/spider/ClusterInfo.go +++ /dev/null @@ -1,15 +0,0 @@ -package spider - -type ClusterInfo struct { - Name string `json:"Name"` - Version string `json:"Version"` - VPCName string `json:"VPCName"` - SubnetNames []string `json:"SubnetNames"` - SecurityGroupNames []string `json:"SecurityGroupNames"` - NodeGroupList []NodeGroupInfo `json:"NodeGroupList"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/spider/ClusterReqInfo.go b/mc_web_console_api/fwmodels/spider/ClusterReqInfo.go deleted file mode 100644 index e9b801ba..00000000 --- a/mc_web_console_api/fwmodels/spider/ClusterReqInfo.go +++ /dev/null @@ -1,7 +0,0 @@ -package spider - -type ClusterReqInfo struct { - NameSpace string `json:"Namespace"` - ConnectionName string `json:"ConnectionName"` - ReqInfo ClusterInfo `json:"ReqInfo"` -} diff --git a/mc_web_console_api/fwmodels/spider/ConfigInfo.go b/mc_web_console_api/fwmodels/spider/ConfigInfo.go deleted file mode 100644 index f93938e7..00000000 --- a/mc_web_console_api/fwmodels/spider/ConfigInfo.go +++ /dev/null @@ -1,8 +0,0 @@ -package spider - -type ConfigInfo struct { - ID string `json:"id"` - Name string `json:"name"` - Value string `json:"value"` -} -type ConfigInfos []ConfigInfo diff --git a/mc_web_console_api/fwmodels/spider/CredentialInfo.go b/mc_web_console_api/fwmodels/spider/CredentialInfo.go deleted file mode 100644 index 307949bc..00000000 --- a/mc_web_console_api/fwmodels/spider/CredentialInfo.go +++ /dev/null @@ -1,9 +0,0 @@ -package spider - -type CredentialInfo struct { - //user(username, password, email) - CredentialName string `json:"CredentialName"` - ProviderName string `json:"ProviderName"` - KeyValueInfoList SpKeyValueList `json:"KeyValueInfoList"` -} -type CredentialInfos []CredentialInfo diff --git a/mc_web_console_api/fwmodels/spider/DriverInfo.go b/mc_web_console_api/fwmodels/spider/DriverInfo.go deleted file mode 100644 index 043e6de8..00000000 --- a/mc_web_console_api/fwmodels/spider/DriverInfo.go +++ /dev/null @@ -1,9 +0,0 @@ -package spider - -type DriverInfo struct { - //user(username, password, email) - DriverName string `json:"DriverName"` - ProviderName string `json:"ProviderName"` - DriverLibFileName string `json:"DriverLibFileName"` -} -type DriverInfos []DriverInfo diff --git a/mc_web_console_api/fwmodels/spider/NodeGroupInfo.go b/mc_web_console_api/fwmodels/spider/NodeGroupInfo.go deleted file mode 100644 index 7184f970..00000000 --- a/mc_web_console_api/fwmodels/spider/NodeGroupInfo.go +++ /dev/null @@ -1,19 +0,0 @@ -package spider - -type NodeGroupInfo struct { - Name string `json:"Name"` - ImageName string `json:"ImageName"` - VMSpecName string `json:"VMSpecName"` - KeyPairName string `json:"KeyPairName"` - OnAutoScaling string `json:"OnAutoScaling"` - DesiredNodeSize string `json:"DesiredNodeSize"` - MinNodeSize string `json:"MinNodeSize"` - MaxNodeSize string `json:"MaxNodeSize"` - RootDiskType string `json:"RootDiskType"` - RootDiskSize string `json:"RootDiskSize"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/spider/NodeGroupReqInfo.go b/mc_web_console_api/fwmodels/spider/NodeGroupReqInfo.go deleted file mode 100644 index e79cbe7f..00000000 --- a/mc_web_console_api/fwmodels/spider/NodeGroupReqInfo.go +++ /dev/null @@ -1,7 +0,0 @@ -package spider - -type NodeGroupReqInfo struct { - NameSpace string `json:"NameSpace"` - ConnectionName string `json:"ConnectionName"` - ReqInfo NodeGroupInfo `json:"ReqInfo"` -} diff --git a/mc_web_console_api/fwmodels/spider/RegionInfo.go b/mc_web_console_api/fwmodels/spider/RegionInfo.go deleted file mode 100644 index e39cf278..00000000 --- a/mc_web_console_api/fwmodels/spider/RegionInfo.go +++ /dev/null @@ -1,9 +0,0 @@ -package spider - -type RegionInfo struct { - RegionName string `json:"RegionName"` - ProviderName string `json:"ProviderName"` - KeyValueInfoList SpKeyValueList `json:"KeyValueInfoList"` -} - -type RegionInfos []RegionInfo diff --git a/mc_web_console_api/fwmodels/spider/SpClusterAccessInfo.go b/mc_web_console_api/fwmodels/spider/SpClusterAccessInfo.go deleted file mode 100644 index 464bb0e0..00000000 --- a/mc_web_console_api/fwmodels/spider/SpClusterAccessInfo.go +++ /dev/null @@ -1,6 +0,0 @@ -package spider - -type SpClusterAccessInfo struct { - Endpoint string `json:"Endpoint"` //ex)https://1.2.3.4:56 - Kubeconfig string `json:"Kubeconfig"` -} diff --git a/mc_web_console_api/fwmodels/spider/SpClusterInfo.go b/mc_web_console_api/fwmodels/spider/SpClusterInfo.go deleted file mode 100644 index dd794300..00000000 --- a/mc_web_console_api/fwmodels/spider/SpClusterInfo.go +++ /dev/null @@ -1,40 +0,0 @@ -package spider - -type SpClusterInfo struct { - Addons SpKeyValueList `json:"Addons"` - CreatedTime string `json:"CreatedTime"` - IId SpIID `json:"IId"` - Status string `json:"Status"` - Version string `json:"Version"` - KeyValueList SpKeyValueList `json:"KeyValueList"` - Network SpClusterNetworkInfo `json:"Network"` - NodeGroupList SpNodeGroupList `json:"NodeGroupList"` - AccessInfo SpClusterAccessInfo `json:"AccessInfo"` - - ConnectionName string `json:"ConnectionName"` // Spider 미제공으로 추가한 항목. - ProviderName string `json:"ProviderName"` // Spider 미제공으로 추가한 항목. -} - -type SpClusterInfoList []SpClusterInfo - -// Connection이 다른 namespace내 모든 Cluster의 List -type SpAllClusterInfoList struct { - Connection string `json:"Connection"` - Provider string `json:"Provider"` - - ClusterList SpClusterInfoList `json:"ClusterList"` - //ClusterList []SpClusterInfo `json:"ClusterList"` -} - -type AllClusterReqInfo struct { - NameSpace string `json:"_NameSpace"` - ConnectionNames []string `json:"_ConnectionNames"` -} - -type SpTotalClusterInfoList struct { - AllClusterList []SpAllClusterInfoList `json:"AllClusterList"` -} - -type RespClusterInfo struct { - ClusterInfo SpClusterInfo `json:"ClusterInfo"` -} diff --git a/mc_web_console_api/fwmodels/spider/SpClusterNetworkInfo.go b/mc_web_console_api/fwmodels/spider/SpClusterNetworkInfo.go deleted file mode 100644 index 5207ceb7..00000000 --- a/mc_web_console_api/fwmodels/spider/SpClusterNetworkInfo.go +++ /dev/null @@ -1,9 +0,0 @@ -package spider - -type SpClusterNetworkInfo struct { - VpcIID SpIID `json:"VpcIID"` - SubnetIIDs SpIIDList `json:"SubnetIIDs"` - SecurityGroupIIDs SpIIDList `json:"SecurityGroupIIDs"` - - KeyValueList SpKeyValueList `json:"KeyValueList"` -} diff --git a/mc_web_console_api/fwmodels/spider/SpError.go b/mc_web_console_api/fwmodels/spider/SpError.go deleted file mode 100644 index ec36de8a..00000000 --- a/mc_web_console_api/fwmodels/spider/SpError.go +++ /dev/null @@ -1,16 +0,0 @@ -package spider - -type SpError struct { - Message string `json:"message"` -} - -//type SpError struct { -// Code string `json:"code"` -// Message SpErrorDetail `json:"message"` -//} - -type SpErrorDetail struct { - Message string `json:"message"` - RequestId string `json:"requestId"` - Status string `json:"status"` -} diff --git a/mc_web_console_api/fwmodels/spider/SpIID.go b/mc_web_console_api/fwmodels/spider/SpIID.go deleted file mode 100644 index 71d51444..00000000 --- a/mc_web_console_api/fwmodels/spider/SpIID.go +++ /dev/null @@ -1,8 +0,0 @@ -package spider - -type SpIID struct { - NameId string `json:"NameId"` - SystemId string `json:"SystemId"` -} - -type SpIIDList []SpIID diff --git a/mc_web_console_api/fwmodels/spider/SpKeyValueInfo.go b/mc_web_console_api/fwmodels/spider/SpKeyValueInfo.go deleted file mode 100644 index 0d52853f..00000000 --- a/mc_web_console_api/fwmodels/spider/SpKeyValueInfo.go +++ /dev/null @@ -1,9 +0,0 @@ -package spider - -// Spider 에서 KeyValue 를 인자로 갖는 응답에서 사용 -type SpKeyValueInfo struct { - Key string `json:"Key"` - Value string `json:"Value"` -} - -type SpKeyValueList []SpKeyValueInfo diff --git a/mc_web_console_api/fwmodels/spider/SpNodeGroupInfo.go b/mc_web_console_api/fwmodels/spider/SpNodeGroupInfo.go deleted file mode 100644 index 762e2788..00000000 --- a/mc_web_console_api/fwmodels/spider/SpNodeGroupInfo.go +++ /dev/null @@ -1,20 +0,0 @@ -package spider - -type SpNodeGroupInfo struct { - IId SpIID `json:"IId"` - ImageIID SpIID `json:"ImageIID"` - KeyPairIID SpIID `json:"KeyPairIID"` - - DesiredNodeSize int `json:"DesiredNodeSize"` - MaxNodeSize int `json:"MaxNodeSize"` - MinNodeSize int `json:"MinNodeSize"` - Nodes SpIIDList `json:"Nodes"` - - OnAutoScaling bool `json:"OnAutoScaling"` - RootDiskSize int `json:"RootDiskSize"` - RootDiskType string `json:"RootDiskType"` - Status string `json:"Status"` - VMSpecName string `json:"VMSpecName"` -} - -type SpNodeGroupList []SpNodeGroupInfo diff --git a/mc_web_console_api/fwmodels/spider/SpSecurityGroupInfo.go b/mc_web_console_api/fwmodels/spider/SpSecurityGroupInfo.go deleted file mode 100644 index 6fe5184f..00000000 --- a/mc_web_console_api/fwmodels/spider/SpSecurityGroupInfo.go +++ /dev/null @@ -1,11 +0,0 @@ -package spider - -type SpSecurityGroupInfo struct { - IId SpIID `json:"IId"` - VpcIID SpIID `json:"VpcIId"` - Direction string `json:"Direction"` - SecurityRules SpSecurityRuleList `json:"SecurityRules"` - KeyValueList []SpKeyValueInfo `json:"KeyValueList"` -} - -type SpSecurityGroupList []SpSecurityGroupInfo diff --git a/mc_web_console_api/fwmodels/spider/SpSecurityRule.go b/mc_web_console_api/fwmodels/spider/SpSecurityRule.go deleted file mode 100644 index a3b0b395..00000000 --- a/mc_web_console_api/fwmodels/spider/SpSecurityRule.go +++ /dev/null @@ -1,10 +0,0 @@ -package spider - -type SpSecurityRule struct { - FromPort string `json:"FromPort"` - ToPort string `json:"ToPort"` - IPProtocol string `json:"IPProtocol"` - Direction string `json:"Direction"` -} - -type SpSecurityRuleList []SpSecurityRule diff --git a/mc_web_console_api/fwmodels/spider/SpSubnetInfo.go b/mc_web_console_api/fwmodels/spider/SpSubnetInfo.go deleted file mode 100644 index ed7236f8..00000000 --- a/mc_web_console_api/fwmodels/spider/SpSubnetInfo.go +++ /dev/null @@ -1,8 +0,0 @@ -package spider - -type SpSubnetInfo struct { - IId SpIID `json:"IId"` - IPv4_CIDR string `json:"IPv4_CIDR"` - KeyValueList []SpKeyValueInfo `json:"KeyValueList"` -} -type SpSubnetList []SpSubnetInfo diff --git a/mc_web_console_api/fwmodels/spider/SpVpcInfo.go b/mc_web_console_api/fwmodels/spider/SpVpcInfo.go deleted file mode 100644 index 4f2f42e3..00000000 --- a/mc_web_console_api/fwmodels/spider/SpVpcInfo.go +++ /dev/null @@ -1,7 +0,0 @@ -package spider - -type SpVpcInfo struct { - IId SpIID `json:"IId"` - IPv4_CIDR string `json:"IPv4_CIDR"` - SubnetInfoList SpSubnetList `json:"SubnetInfoList"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/TbHello.go b/mc_web_console_api/fwmodels/tumblebug/TbHello.go deleted file mode 100644 index 4f5101b3..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/TbHello.go +++ /dev/null @@ -1,5 +0,0 @@ -package tumblebug - -type TbHello struct { - Hello string `json:"hello"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbConfigInfo.go b/mc_web_console_api/fwmodels/tumblebug/common/TbConfigInfo.go deleted file mode 100644 index 046bef7a..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbConfigInfo.go +++ /dev/null @@ -1,8 +0,0 @@ -package common - -// TB의 common.ConfigInfo -> TBConfigInfo로 ConfigInfo가 spider에도 있으므로 common package는 모두 TB를 붙이도록 한다 -type TbConfigInfo struct { - ID string `json:"id"` - Name string `json:"name"` - Value string `json:"value"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbConfigReq.go b/mc_web_console_api/fwmodels/tumblebug/common/TbConfigReq.go deleted file mode 100644 index f9bf1f3b..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbConfigReq.go +++ /dev/null @@ -1,7 +0,0 @@ -package common - -// TB의 common.ConfigInfo -> TBConfigInfo로 ConfigInfo가 spider에도 있으므로 common package는 모두 TB를 붙이도록 한다 -type TbConfigReq struct { - Name string `json:"name"` - Value string `json:"value"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbConnConfig.go b/mc_web_console_api/fwmodels/tumblebug/common/TbConnConfig.go deleted file mode 100644 index c06a6e99..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbConnConfig.go +++ /dev/null @@ -1,15 +0,0 @@ -package common - -// TB의 common.ConfigInfo -> TBConfigInfo로 ConfigInfo가 spider에도 있으므로 common package는 모두 TB를 붙이도록 한다 -type TbConConfig struct { - ConfigName string `json:"configName"` - ProviderName string `json:"providerName"` - CredentialName string `json:"credentialName"` - DriverName string `json:"driverName"` - RegionName string `json:"regionName"` - Location TbGeoLocation `json:"location"` - - ProviderID string `json:"providerId"` -} - -type TbConConfigs []TbConConfig diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbConnectionName.go b/mc_web_console_api/fwmodels/tumblebug/common/TbConnectionName.go deleted file mode 100644 index c13aa8e0..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbConnectionName.go +++ /dev/null @@ -1,5 +0,0 @@ -package common - -type TbConnectionName struct { - ConnectionName string `json:"connectionName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbGeoLocation.go b/mc_web_console_api/fwmodels/tumblebug/common/TbGeoLocation.go deleted file mode 100644 index d65e240d..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbGeoLocation.go +++ /dev/null @@ -1,9 +0,0 @@ -package common - -type TbGeoLocation struct { - BriefAddr string `json:"briefAddr"` - CloudType string `json:"cloudType"` - Latitude string `json:"latitude"` - Longitude string `json:"longitude"` - NativeRegion string `json:"nativeRegion"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbIID.go b/mc_web_console_api/fwmodels/tumblebug/common/TbIID.go deleted file mode 100644 index 4a509ec7..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbIID.go +++ /dev/null @@ -1,7 +0,0 @@ -package common - -// TB의 common.ConfigInfo -> TBConfigInfo로 ConfigInfo가 spider에도 있으므로 common package는 모두 TB를 붙이도록 한다 -type TbIID struct { - NameID string `json:"nameId"` - SystemID string `json:"systemId"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbIdList.go b/mc_web_console_api/fwmodels/tumblebug/common/TbIdList.go deleted file mode 100644 index 1146f0d4..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbIdList.go +++ /dev/null @@ -1,6 +0,0 @@ -package common - -type TbIdList struct { - //IDList []string `json:"idList"` - IDList []string `json:"output"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbKeyValue.go b/mc_web_console_api/fwmodels/tumblebug/common/TbKeyValue.go deleted file mode 100644 index 232c1832..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbKeyValue.go +++ /dev/null @@ -1,9 +0,0 @@ -package common - -// Tumblebug 에서 KeyValue 를 인자로 갖는 응답에서 사용 -type TbKeyValue struct { - Key string `json:"key"` - Value string `json:"value"` -} - -type TbKeyValues []TbKeyValue diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbNsInfo.go b/mc_web_console_api/fwmodels/tumblebug/common/TbNsInfo.go deleted file mode 100644 index b37852f2..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbNsInfo.go +++ /dev/null @@ -1,9 +0,0 @@ -package common - -type TbNsInfo struct { - ID string `json:"id"` - Name string `json:"name" validate:"required"` - Description string `json:"description"` -} - -type TbNsInfos []TbNsInfo diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbNsReq.go b/mc_web_console_api/fwmodels/tumblebug/common/TbNsReq.go deleted file mode 100644 index 19c3962a..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbNsReq.go +++ /dev/null @@ -1,6 +0,0 @@ -package common - -type TbNsReq struct { - Name string `json:"name" validate:"required"` - Description string `json:"description"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbRegion.go b/mc_web_console_api/fwmodels/tumblebug/common/TbRegion.go deleted file mode 100644 index a91efaa0..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbRegion.go +++ /dev/null @@ -1,11 +0,0 @@ -package common - -type TbRegion struct { - ProviderName string `json:"providerName"` - RegionName string `regionName:"regionName"` - KeyValueInfoList []TbKeyValue `json:"keyValueInfoList"` - - ProviderID string `json:"providerId"` -} - -type TbRegions []TbRegion diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbRequestDetails.go b/mc_web_console_api/fwmodels/tumblebug/common/TbRequestDetails.go deleted file mode 100644 index 9276b591..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbRequestDetails.go +++ /dev/null @@ -1,13 +0,0 @@ -package common - -import ( - "time" -) -type TbRequestDetails struct { - StartTime time.Time `json:"startTime"` // The time when the request was received by the server. - EndTime time.Time `json:"endTime"` // The time when the request was fully processed. - Status string `json:"status"` // The current status of the request (e.g., "Handling", "Error", "Success"). - RequestInfo TbRequestInfo `json:"requestInfo"` // Extracted information about the request. - ResponseData interface{} `json:"responseData"` // The data sent back in response to the request. - ErrorResponse string `json:"errorResponse"` // A message describing any error that occurred during request processing. -} \ No newline at end of file diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbRequestInfo.go b/mc_web_console_api/fwmodels/tumblebug/common/TbRequestInfo.go deleted file mode 100644 index 0bf2a9d2..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbRequestInfo.go +++ /dev/null @@ -1,9 +0,0 @@ -package common - - -type TbRequestInfo struct { - Method string `json:"method"` // HTTP method (GET, POST, etc.), indicating the request's action type. - URL string `json:"url"` // The URL the request is made to. - Header map[string]string `json:"header"` // Key-value pairs of the request headers. - Body interface{} `json:"body,omitempty"` // Optional: request body -} \ No newline at end of file diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbRestGetAllConfigResponse.go b/mc_web_console_api/fwmodels/tumblebug/common/TbRestGetAllConfigResponse.go deleted file mode 100644 index 8053dbfd..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbRestGetAllConfigResponse.go +++ /dev/null @@ -1,6 +0,0 @@ -package common - -type TbRestGetAllConfigResponse struct { - Name string `json:"name"` - ConfigInfo TbConfigInfo `json:"configInfo"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbRestInspectResourcesRequest.go b/mc_web_console_api/fwmodels/tumblebug/common/TbRestInspectResourcesRequest.go deleted file mode 100644 index 6807e4fb..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbRestInspectResourcesRequest.go +++ /dev/null @@ -1,6 +0,0 @@ -package common - -type RestInspectResourcesRequest struct { - ConnectionName string `json:"connectionName"` - ResourceType string `json:"resourceType"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbRestRegisterCspNativeResourcesRequest.go b/mc_web_console_api/fwmodels/tumblebug/common/TbRestRegisterCspNativeResourcesRequest.go deleted file mode 100644 index d2715182..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbRestRegisterCspNativeResourcesRequest.go +++ /dev/null @@ -1,7 +0,0 @@ -package common - -type RestRegisterCspNativeResourcesRequest struct { - ConnectionName string `json:"connectionName"` - McisName string `json:"mcisName"` - NsId string `json:"nsId"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbRestRegisterCspNativeResourcesRequestAll.go b/mc_web_console_api/fwmodels/tumblebug/common/TbRestRegisterCspNativeResourcesRequestAll.go deleted file mode 100644 index 96a24676..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbRestRegisterCspNativeResourcesRequestAll.go +++ /dev/null @@ -1,6 +0,0 @@ -package common - -type RestRegisterCspNativeResourcesRequestAll struct { - McisName string `json:"mcisName"` - NsId string `json:"nsId"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/common/TbSimpleMsg.go b/mc_web_console_api/fwmodels/tumblebug/common/TbSimpleMsg.go deleted file mode 100644 index b6fd9c69..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/common/TbSimpleMsg.go +++ /dev/null @@ -1,6 +0,0 @@ -package common - -// TB의 common.ConfigInfo -> TBConfigInfo로 ConfigInfo가 spider에도 있으므로 common package는 모두 TB를 붙이도록 한다 -type TbSimpleMsg struct { - Message string `json:"message"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/FilterSpecsByRangeRequest.go b/mc_web_console_api/fwmodels/tumblebug/mcir/FilterSpecsByRangeRequest.go deleted file mode 100644 index 21fffdb9..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/FilterSpecsByRangeRequest.go +++ /dev/null @@ -1,42 +0,0 @@ -package mcir - -type FilterSpecsByRangeRequest struct { - ID string `json:"id"` - Name string `json:"name"` - ProviderID string `json:"providerId"` // 실제 tb에서 사용하지는 않으나 mcone에서 사용할 용도. - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - Description string `json:"description"` - ConnectionName string `json:"connectionName"` - CspSpecName string `json:"cspSpecName"` - OsType string `json:"osType"` - - CostPerHour Range `json:"costPerHour"` - EbsBwMbps Range `json:"ebsBwMbps"` - - EvaluationScore01 Range `json:"evaluationScore01"` - EvaluationScore02 Range `json:"evaluationScore02"` - EvaluationScore03 Range `json:"evaluationScore03"` - EvaluationScore04 Range `json:"evaluationScore04"` - EvaluationScore05 Range `json:"evaluationScore05"` - EvaluationScore06 Range `json:"evaluationScore06"` - EvaluationScore07 Range `json:"evaluationScore07"` - EvaluationScore08 Range `json:"evaluationScore08"` - EvaluationScore09 Range `json:"evaluationScore09"` - EvaluationScore10 Range `json:"evaluationScore10"` - EvaluationStatus string `json:"evaluationStatus"` - - GpuModel string `json:"gpuModel"` - GpuP2p string `json:"gpuP2p"` - - MaxNumStorage Range `json:"maxNumStorage"` - MaxTotalStorageTiB Range `json:"maxTotalStorageTiB"` - MemGiB Range `json:"memGiB"` - - NetBwGbps Range `json:"netBwGbps"` - NumCore Range `json:"numCore"` - NumGpu Range `json:"numGpu"` - NumStorage Range `json:"numStorage"` - NumVCPU Range `json:"numvCPU"` - StorageGiB Range `json:"storageGiB"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/Range.go b/mc_web_console_api/fwmodels/tumblebug/mcir/Range.go deleted file mode 100644 index 929efdb0..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/Range.go +++ /dev/null @@ -1,6 +0,0 @@ -package mcir - -type Range struct { - MAX int `json:"max"` - MIN int `json:"min"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/RestFilterSpecsResponse.go b/mc_web_console_api/fwmodels/tumblebug/mcir/RestFilterSpecsResponse.go deleted file mode 100644 index bd1ddab1..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/RestFilterSpecsResponse.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcir - -type RestFilterSpecsResponse struct { - SpaceInfo []TbSpecInfo `json:"spec"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAllImageResponse.go b/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAllImageResponse.go deleted file mode 100644 index 22126b6c..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAllImageResponse.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcir - -type RestGetAllImageResponse struct { - Image []TbImageInfo `json:"image"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAllSecurityGroupResponse.go b/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAllSecurityGroupResponse.go deleted file mode 100644 index 8ede8bc8..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAllSecurityGroupResponse.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcir - -type RestGetAllSecurityGroupResponse struct { - SecurityGroup TbSecurityGroupInfo `json:"securityGroup"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAllSpecResponse.go b/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAllSpecResponse.go deleted file mode 100644 index 8ed01107..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAllSpecResponse.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcir - -type RestGetAllSpecResponse struct { - Spec []TbSpecInfo `json:"spec"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAllSshKeyResponse.go b/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAllSshKeyResponse.go deleted file mode 100644 index b5f4ab06..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAllSshKeyResponse.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcir - -type RestGetAllSshKeyResponse struct { - SshKey TbSshKeyInfo `json:"sshKey"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAllVNetResponse.go b/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAllVNetResponse.go deleted file mode 100644 index ef8478d2..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAllVNetResponse.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcir - -type RestGetAllVNetResponse struct { - vNet TbVNetInfo `json:"sshKey"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAvailableDataDisksResponse.go b/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAvailableDataDisksResponse.go deleted file mode 100644 index e91115bc..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/RestGetAvailableDataDisksResponse.go +++ /dev/null @@ -1,6 +0,0 @@ -package mcir - -type RestGetAvailableDataDisksResponse struct { - //DataDisk []string `json:"dataDisk"` - DataDisk []TbDataDiskInfo `json:"dataDisk"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/RestLookupImageRequest.go b/mc_web_console_api/fwmodels/tumblebug/mcir/RestLookupImageRequest.go deleted file mode 100644 index 562a2948..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/RestLookupImageRequest.go +++ /dev/null @@ -1,6 +0,0 @@ -package mcir - -type RestLookupImageRequest struct { - ConnectionName string `json:"connectionName"` - CspImageId string `json:"cspImageId"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/RestLookupSpecRequest.go b/mc_web_console_api/fwmodels/tumblebug/mcir/RestLookupSpecRequest.go deleted file mode 100644 index 24765f91..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/RestLookupSpecRequest.go +++ /dev/null @@ -1,6 +0,0 @@ -package mcir - -type RestLookupSpecRequest struct { - ConnectionName string `json:"connectionName"` - CspSpecName string `json:"cspSpecName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/RestSearchImageRequest.go b/mc_web_console_api/fwmodels/tumblebug/mcir/RestSearchImageRequest.go deleted file mode 100644 index d8402f96..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/RestSearchImageRequest.go +++ /dev/null @@ -1,11 +0,0 @@ -package mcir - -type RestSearchImageRequest struct { - Keywords []string `json:"keywords"` - - // connection 을 provider, regname으로 대체를 위해 추가 - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderGpuInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderGpuInfo.go deleted file mode 100644 index ce423b25..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderGpuInfo.go +++ /dev/null @@ -1,9 +0,0 @@ -package mcir - -type SpiderGpuInfo struct { - Count string `json:"count"` - Mem string `json:"mem"` - Mfr string `json:"mfr"` - Model string `json:"model"` -} -type SpiderGpuInfos []SpiderGpuInfo diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderImageInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderImageInfo.go deleted file mode 100644 index 5a48a82e..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderImageInfo.go +++ /dev/null @@ -1,15 +0,0 @@ -package mcir - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type SpiderImageInfo struct { - GuestOS string `json:"guestOS"` - IID tbcommon.TbIID `json:"iid"` - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` - Name string `json:"name"` - Status string `json:"status"` -} - -type SpiderImageInfos []SpiderImageInfo diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderSpecInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderSpecInfo.go deleted file mode 100644 index 7da8b836..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderSpecInfo.go +++ /dev/null @@ -1,16 +0,0 @@ -package mcir - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type SpiderSpecInfo struct { - Gpu SpiderGpuInfo `json:"gpu"` - KeyValueList tbcommon.TbKeyValue `json:"keyValueList"` - Mem string `json:"mem"` - Name string `json:"name"` - Region string `json:"region"` - Vcpu SpiderVCpuInfo `json:"vCpu"` -} - -type SpiderSpecInfos []SpiderSpecInfo diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderSubnetInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderSubnetInfo.go deleted file mode 100644 index 455fd59c..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderSubnetInfo.go +++ /dev/null @@ -1,13 +0,0 @@ -package mcir - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type SpiderSubnetInfo struct { - IID tbcommon.TbIID `json:"iid"` - Ipv4_CIDR string `json:"ipv4_CIDR"` - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` -} - -type SpiderSubnetInfos []SpiderSubnetInfo diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderSubnetReqInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderSubnetReqInfo.go deleted file mode 100644 index dc7c34bc..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderSubnetReqInfo.go +++ /dev/null @@ -1,16 +0,0 @@ -package mcir - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type SpiderSubnetReqInfo struct { - Name string `json:"name"` - Ipv4_CIDR string `json:"ipv4_CIDR"` - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderVCpuInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderVCpuInfo.go deleted file mode 100644 index a5b7d27b..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/SpiderVCpuInfo.go +++ /dev/null @@ -1,7 +0,0 @@ -package mcir - -type SpiderVCpuInfo struct { - Clock string `json:"clock"` - // GHz string `json:""` - Count string `json:"count"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbAttachDetachDataDiskReq.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbAttachDetachDataDiskReq.go deleted file mode 100644 index fcb47acb..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbAttachDetachDataDiskReq.go +++ /dev/null @@ -1,10 +0,0 @@ -package mcir - -type TbAttachDetachDataDiskReq struct { - DataDiskId string `json:"dataDiskId"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbCustomImageInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbCustomImageInfo.go deleted file mode 100644 index 6b26dcc0..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbCustomImageInfo.go +++ /dev/null @@ -1,27 +0,0 @@ -package mcir - -import tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - -type TbCustomImageInfo struct { - AssociatedObjectList []string `json:"associatedObjectList"` - ConnectionName string `json:"connectionName"` - CreationDate string `json:"creationDate"` - CspCustomImageId string `json:"cspCustomImageId"` - CspCustomImageName string `json:"cspCustomImageName"` - Description string `json:"description"` - GuestOS string `json:"guestOS"` - ID string `json:"id"` - isAutoGenerated bool `json:"isAutoGenerated"` - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` - Name string `json:"name"` - NameSpaceID string `json:"namespace"` - Status string `json:"status"` - SystemLabel string `json:"systemLabel"` - SourceVmId string `json:"sourceVmId"` - - // connection 을 provider, regname으로 대체를 위해 추가 - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbCustomImageReq.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbCustomImageReq.go deleted file mode 100644 index 30c44676..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbCustomImageReq.go +++ /dev/null @@ -1,17 +0,0 @@ -package mcir - -type TbCustomImageReq struct { - ConnectionName string `json:"connectionName"` - CspCustomImageId string `json:"cspCustomImageId"` - - Description string `json:"description"` - Name string `json:"name"` - - SourceVmID string `json:"sourceVmId"` - - // connection 을 provider, regname으로 대체를 위해 추가 - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbDataDiskInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbDataDiskInfo.go deleted file mode 100644 index 2661b334..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbDataDiskInfo.go +++ /dev/null @@ -1,27 +0,0 @@ -package mcir - -import tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - -type TbDataDiskInfo struct { - AssociatedObjectList []string `json:"associatedObjectList"` - ConnectionName string `json:"connectionName"` - CreatedTime string `json:"createdTime"` - CspDataDiskId string `json:"cspDataDiskId"` - CspDataDiskName string `json:"cspDataDiskName"` - Description string `json:"description"` - DiskSize string `json:"diskSize"` - DiskType string `json:"diskType"` - - ID string `json:"id"` - isAutoGenerated bool `json:"isAutoGenerated"` - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` - Name string `json:"name"` - Status string `json:"status"` - SystemLabel string `json:"systemLabel"` - - // connection 을 provider, regname으로 대체를 위해 추가 - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbDataDiskReq.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbDataDiskReq.go deleted file mode 100644 index f70a775a..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbDataDiskReq.go +++ /dev/null @@ -1,17 +0,0 @@ -package mcir - -type TbDataDiskReq struct { - ConnectionName string `json:"connectionName"` - CspDataDiskId string `json:"cspDataDiskId"` - Description string `json:"description"` - DiskSize string `json:"diskSize"` - DiskType string `json:"diskType"` - - Name string `json:"name"` - - // connection 을 provider, regname으로 대체를 위해 추가 - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbDataDiskUpsizeReq.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbDataDiskUpsizeReq.go deleted file mode 100644 index e65745eb..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbDataDiskUpsizeReq.go +++ /dev/null @@ -1,11 +0,0 @@ -package mcir - -type TbDataDiskUpsizeReq struct { - Description string `json:"description"` - DiskSize string `json:"diskSize"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbFirewallRuleInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbFirewallRuleInfo.go deleted file mode 100644 index 61fe5fa1..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbFirewallRuleInfo.go +++ /dev/null @@ -1,9 +0,0 @@ -package mcir - -type TbFirewallRuleInfo struct { - Cidr string `json:"cidr"` - Direction string `json:"direction" validate:"required"` - FromPort string `json:"fromPort" validate:"required"` - ToPort string `json:"toPort" validate:"required"` - IpProtocol string `json:"ipProtocol" validate:"required"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbFirewallRulesWrapper.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbFirewallRulesWrapper.go deleted file mode 100644 index 08629192..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbFirewallRulesWrapper.go +++ /dev/null @@ -1,10 +0,0 @@ -package mcir - -type TbFirewallRulesWrapper struct { - FirewallRules []TbFirewallRuleInfo `json:"firewallRules"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbImageInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbImageInfo.go deleted file mode 100644 index c14fb7d7..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbImageInfo.go +++ /dev/null @@ -1,32 +0,0 @@ -package mcir - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type TbImageInfo struct { - AssociatedObjectList []string `json:"associatedObjectList"` - - ConnectionName string `json:"connectionName"` - CreationDate string `json:"creationDate"` - CspImageId string `json:"cspImageId"` - CspImageName string `json:"cspImageName"` - Description string `json:"description"` - GuestOS string `json:"guestOS"` - ID string `json:"id"` - IsAutoGenerated string `json:"isAutoGenerated"` - - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` - Name string `json:"name"` - Namespace string `json:"namespace"` //required - Status string `json:"status"` - SystemLabel string `json:"systemLabel"` - - // connection 을 provider, regname으로 대체를 위해 추가 - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} - -type TbImageInfos []TbImageInfo diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbImageReq.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbImageReq.go deleted file mode 100644 index 9c7151ca..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbImageReq.go +++ /dev/null @@ -1,12 +0,0 @@ -package mcir - -type TbImageReq struct { - ConnectionName string `json:"connectionName"` - CspImageId string `json:"cspImageId"` - Name string `json:"name"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSecurityGroupInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbSecurityGroupInfo.go deleted file mode 100644 index 2b494fdd..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSecurityGroupInfo.go +++ /dev/null @@ -1,30 +0,0 @@ -package mcir - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type TbSecurityGroupInfo struct { - AssociatedObjectList []string `json:"associatedObjectList"` - - ConnectionName string `json:"connectionName"` - CspSecurityGroupId string `json:"cspSecurityGroupId"` - CspSecurityGroupName string `json:"cspSecurityGroupName"` - Description string `json:"description"` - FirewallRules []TbFirewallRuleInfo `json:"firewallRules"` - ID string `json:"id"` - IsAutoGenerated string `json:"isAutoGenerated"` - - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` - Name string `json:"name"` - SystemLabel string `json:"systemLabel"` - VNetID string `json:"vNetId"` - - // connection 을 provider, regname으로 대체를 위해 추가 - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} - -type TbSecurityGroupInfos []TbSecurityGroupInfo diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSecurityGroupReq.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbSecurityGroupReq.go deleted file mode 100644 index bdccf29e..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSecurityGroupReq.go +++ /dev/null @@ -1,15 +0,0 @@ -package mcir - -type TbSecurityGroupReq struct { - ConnectionName string `json:"connectionName"` - Description string `json:"description"` - FirewallRules []TbFirewallRuleInfo `json:"firewallRules"` - Name string `json:"name"` - VNetID string `json:"vNetId"` - CspSecurityGroupId string `json:"cspSecurityGroupId"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSpecInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbSpecInfo.go deleted file mode 100644 index 4759e557..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSpecInfo.go +++ /dev/null @@ -1,51 +0,0 @@ -package mcir - -type TbSpecInfo struct { - AssociatedObjectList []string `json:"associatedObjectList"` - - ConnectionName string `json:"connectionName"` - ProviderID string `json:"providerId"` // 실제 tb에서 사용하지는 않으나 mcone에서 사용할 용도. - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - SystemLabel string `json:"systemLabel"` - CostPerHour float32 `json:"costPerHour"` - CspSpecName string `json:"cspSpecName"` - Description string `json:"description"` - EbsBwMbps int `json:"ebsBwMbps"` - - EvaluationScore01 float32 `json:"evaluationScore01"` - EvaluationScore02 float32 `json:"evaluationScore02"` - EvaluationScore03 float32 `json:"evaluationScore03"` - EvaluationScore04 float32 `json:"evaluationScore04"` - EvaluationScore05 float32 `json:"evaluationScore05"` - EvaluationScore06 float32 `json:"evaluationScore06"` - EvaluationScore07 float32 `json:"evaluationScore07"` - EvaluationScore08 float32 `json:"evaluationScore08"` - EvaluationScore09 float32 `json:"evaluationScore09"` - EvaluationScore10 float32 `json:"evaluationScore10"` - EvaluationStatus string `json:"evaluationStatus"` - - GpuMemGiB float32 `json:"gpuMemGiB"` - GpuModel string `json:"gpuModel"` - GpuP2p string `json:"gpuP2p"` - ID string `json:"id"` - IsAutoGenerated bool `json:"isAutoGenerated"` - MaxNumStorage int `json:"maxNumStorage"` - MaxTotalStorageTiB int `json:"maxTotalStorageTiB"` - MemGiB float32 `json:"memGiB"` - Name string `json:"name"` - Namespace string `json:"namespace"` - - NetBwGbps int `json:"netBwGbps"` - NumCore int `json:"numCore"` - NumGpu int `json:"numGpu"` - NumStorage int `json:"numStorage"` - NumVCPU int `json:"numvCPU"` - OrderInFilteredResult int `json:"orderInFilteredResult"` - OsType string `json:"osType"` - StorageGiB int `json:"storageGiB"` - RootDiskSize string `json:"rootDiskSize"` - RootDiskType string `json:"rootDiskType"` -} - -type TbSpecInfos []TbSpecInfo diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSpecReq.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbSpecReq.go deleted file mode 100644 index 8ae02b63..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSpecReq.go +++ /dev/null @@ -1,13 +0,0 @@ -package mcir - -type TbSpecReq struct { - ConnectionName string `json:"connectionName"` - CspSpecName string `json:"cspSpecName"` - Description string `json:"description"` - Name string `json:"name"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSshKeyInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbSshKeyInfo.go deleted file mode 100644 index 266cbe21..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSshKeyInfo.go +++ /dev/null @@ -1,33 +0,0 @@ -package mcir - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type TbSshKeyInfo struct { - AssociatedObjectList []string `json:"associatedObjectList"` - - ConnectionName string `json:"connectionName"` - CspSshKeyName string `json:"cspSshKeyName"` - CspSshKeyId string `json:"cspSshKeyId"` - SystemLabel string `json:"systemLabel"` - - Description string `json:"description"` - Fingerprint string `json:"fingerprint"` - ID string `json:"id"` - IsAutoGenerated bool `json:"isAutoGenerated"` - KeyValueInfos []tbcommon.TbKeyValue `json:"keyValueList"` - - Name string `json:"name"` - PrivateKey string `json:"privateKey"` - PublicKey string `json:"publicKey"` - Username string `json:"username"` - VerifiedUsername string `json:"verifiedUsername"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} - -type TbSshKeyInfos []TbSshKeyInfo diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSshKeyReq.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbSshKeyReq.go deleted file mode 100644 index 2c9e224e..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSshKeyReq.go +++ /dev/null @@ -1,18 +0,0 @@ -package mcir - -type TbSshKeyReq struct { - ConnectionName string `json:"connectionName"` - CspSshKeyId string `json:"cspSshKeyId"` - Description string `json:"description"` - Fingerprint string `json:"fingerprint"` - Name string `json:"name"` - PrivateKey string `json:"privateKey"` - PublicKey string `json:"publicKey"` - Username string `json:"username"` - VerifiedUsername string `json:"verifiedUsername"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSubnetInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbSubnetInfo.go deleted file mode 100644 index 840c56dc..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSubnetInfo.go +++ /dev/null @@ -1,16 +0,0 @@ -package mcir - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type TbSubnetInfo struct { - Description string `json:"description"` - ID string `json:"id"` - Ipv4_CIDR string `json:"ipv4_CIDR" validate:"required"` - KeyValueInfos []tbcommon.TbKeyValue `json:"keyValueList"` - - Name string `json:"name" validate:"required"` -} - -type TbSubnetInfos []TbSubnetInfo diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSubnetReq.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbSubnetReq.go deleted file mode 100644 index 63d4d96d..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbSubnetReq.go +++ /dev/null @@ -1,19 +0,0 @@ -package mcir - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type TbSubnetReq struct { - Name string `json:"name"` - Description string `json:"description"` - Ipv4_CIDR string `json:"ipv4_CIDR"` - KeyValueInfos []tbcommon.TbKeyValue `json:"keyValueList"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} - -type TbSubnetReqs []TbSubnetReq diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbVNetInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbVNetInfo.go deleted file mode 100644 index e5745b66..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbVNetInfo.go +++ /dev/null @@ -1,32 +0,0 @@ -package mcir - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type TbVNetInfo struct { - AssociatedObjectList []string `json:"associatedObjectList"` - - CidrBlock string `json:"cidrBlock"` - ConnectionName string `json:"connectionName"` - CspVNetID string `json:"cspVNetId"` - CspVNetName string `json:"cspVNetName"` - - Description string `json:"description"` - ID string `json:"id"` - IsAutoGenerated bool `json:"isAutoGenerated"` - KeyValueInfos []tbcommon.TbKeyValue `json:"keyValueList"` - - Name string `json:"name"` - Statue string `json:"status"` - SubnetInfoList []TbSubnetInfo `json:"subnetInfoList"` - SystemLabel string `json:"systemLabel"` - - // connection 을 provider, regname으로 대체를 위해 추가 - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} - -type TbVNetInfos []TbVNetInfo diff --git a/mc_web_console_api/fwmodels/tumblebug/mcir/TbVNetReq.go b/mc_web_console_api/fwmodels/tumblebug/mcir/TbVNetReq.go deleted file mode 100644 index ae0346c9..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcir/TbVNetReq.go +++ /dev/null @@ -1,15 +0,0 @@ -package mcir - -type TbVNetReq struct { - CidrBlock string `json:"cidrBlock"` - ConnectionName string `json:"connectionName"` - CspVNetId string `json:"cspVNetId"` - Description string `json:"description"` - Name string `json:"name"` - SubnetInfoList []TbSubnetReq `json:"subnetInfoList"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/AgentInstallContent.go b/mc_web_console_api/fwmodels/tumblebug/mcis/AgentInstallContent.go deleted file mode 100644 index 04881924..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/AgentInstallContent.go +++ /dev/null @@ -1,8 +0,0 @@ -package mcis - -type AgentInstallContent struct { - McisID string `json:"mcisId"` - Result string `json:"result"` - VmID string `json:"vmId"` - VmIp string `json:"vmIp"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/AgentInstallContentWrapper.go b/mc_web_console_api/fwmodels/tumblebug/mcis/AgentInstallContentWrapper.go deleted file mode 100644 index 354aa083..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/AgentInstallContentWrapper.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcis - -type AgentInstallContentWrapper struct { - ResultArray AgentInstallContent `json:"resultArray"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/AutoAction.go b/mc_web_console_api/fwmodels/tumblebug/mcis/AutoAction.go deleted file mode 100644 index a2d180b4..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/AutoAction.go +++ /dev/null @@ -1,8 +0,0 @@ -package mcis - -type AutoAction struct { - ActionType string `json:"actionType"` - PlacementAlgo string `json:"placementAlgo"` - PostCommand McisCmdReq `json:"postCommand"` - Vm TbVmInfo `json:"vm"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/AutoCondition.go b/mc_web_console_api/fwmodels/tumblebug/mcis/AutoCondition.go deleted file mode 100644 index 6b824e71..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/AutoCondition.go +++ /dev/null @@ -1,10 +0,0 @@ -package mcis - -type AutoCondition struct { - EvaluationPeriod string `json:"evaluationPeriod"` - EvaluationValue []string `json:"evaluationValue"` - - Metric string `json:"metric"` - Operand string `json:"operand"` - Operator string `json:"operator"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/BenchmarkInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/BenchmarkInfo.go deleted file mode 100644 index 4e4c90c8..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/BenchmarkInfo.go +++ /dev/null @@ -1,16 +0,0 @@ -package mcis - -type BenchmarkInfo struct { - Desc string `json:"desc"` - Elapsed string `json:"elapsed"` - Result string `json:"result"` - ResultArray StructElementCycle `json:"struct-element-cycle"` //? - SpecID string `json:"specid"` - Unit string `json:"unit"` -} - -type BenchmarkInfos []BenchmarkInfo - -type StructElementCycle struct { - Cycle string `json:"cycle"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/CheckMcisDynamicReqInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/CheckMcisDynamicReqInfo.go deleted file mode 100644 index f08c050c..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/CheckMcisDynamicReqInfo.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcis - -type CheckMcisDynamicReqInfo struct { - ReqCheck []CheckVmDynamicReqInfo `json:"reqCheck"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/CheckVmDynamicReqInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/CheckVmDynamicReqInfo.go deleted file mode 100644 index d4319547..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/CheckVmDynamicReqInfo.go +++ /dev/null @@ -1,13 +0,0 @@ -package mcis - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" -) - -type CheckVmDynamicReqInfo struct { - ConnectionConfigCandidates []string `json:"connectionConfigCandidates"` - Region tbcommon.TbRegion `json:"region"` - SystemMessage string `json:"systemMessage"` - VmSpec tbmcir.TbSpecInfo `json:"vmSpec"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/DeploymentPlan.go b/mc_web_console_api/fwmodels/tumblebug/mcis/DeploymentPlan.go deleted file mode 100644 index 5dc504f5..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/DeploymentPlan.go +++ /dev/null @@ -1,7 +0,0 @@ -package mcis - -type DeploymentPlan struct { - Filter FilterInfo `json:"filter"` - Limit string `json:"limit"` - Priority PriorityInfo `json:"priority"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/FilterCondition.go b/mc_web_console_api/fwmodels/tumblebug/mcis/FilterCondition.go deleted file mode 100644 index 4ac2558e..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/FilterCondition.go +++ /dev/null @@ -1,6 +0,0 @@ -package mcis - -type FilterCondition struct { - Condition []Operation `json:"condition"` - Metric string `json:"metric"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/FilterInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/FilterInfo.go deleted file mode 100644 index 3f081271..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/FilterInfo.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcis - -type FilterInfo struct { - Policy []FilterCondition `json:"policy"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/InspectOverview.go b/mc_web_console_api/fwmodels/tumblebug/mcis/InspectOverview.go deleted file mode 100644 index 538d7a52..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/InspectOverview.go +++ /dev/null @@ -1,8 +0,0 @@ -package mcis - -type InspectOverview struct { - SecurityGroup int `json:"securityGroup"` - SshKey int `json:"sshKey"` - VNet int `json:"vNet"` - Vm int `json:"vm"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/InspectResource.go b/mc_web_console_api/fwmodels/tumblebug/mcis/InspectResource.go deleted file mode 100644 index 33959ad6..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/InspectResource.go +++ /dev/null @@ -1,9 +0,0 @@ -package mcis - -type InspectResource struct { - ConnectionName string `json:"connectionName"` - ResourceOverview ResourceCountOverview `json:"resourceOverview"` - ResourceType string `json:"resourceType"` - Resources ResourcesByManageType `json:"resources"` - SystemMessage string `json:"systemMessage"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/InspectResourceAllResult.go b/mc_web_console_api/fwmodels/tumblebug/mcis/InspectResourceAllResult.go deleted file mode 100644 index b4c7783f..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/InspectResourceAllResult.go +++ /dev/null @@ -1,10 +0,0 @@ -package mcis - -type InspectResourceAllResult struct { - AvailableConnection int `json:"availableConnection"` - CspOnlyOverview InspectOverview `json:"cspOnlyOverview"` - ElapsedTime int `json:"elapsedTime"` - InspectResult []InspectResourceResult `json:"inspectResult"` - RegisteredConnection int `json:"registeredConnection"` - TumblebugOverview InspectOverview `json:"tumblebugOverview"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/InspectResourceResult.go b/mc_web_console_api/fwmodels/tumblebug/mcis/InspectResourceResult.go deleted file mode 100644 index ce1dab87..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/InspectResourceResult.go +++ /dev/null @@ -1,9 +0,0 @@ -package mcis - -type InspectResourceResult struct { - ConnectionName string `json:"connectionName"` - CspOnlyOverview InspectOverview `json:"cspOnlyOverview"` - ElapsedTime int `json:"elapsedTime"` - SystemMessage string `json:"systemMessage"` - TumblebugOverview InspectOverview `json:"tumblebugOverview"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/McisCmdReq.go b/mc_web_console_api/fwmodels/tumblebug/mcis/McisCmdReq.go deleted file mode 100644 index 6d732a26..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/McisCmdReq.go +++ /dev/null @@ -1,6 +0,0 @@ -package mcis - -type McisCmdReq struct { - Command string `json:"command"` - UserName string `json:"userName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/McisConnectionConfigCandidatesReq.go b/mc_web_console_api/fwmodels/tumblebug/mcis/McisConnectionConfigCandidatesReq.go deleted file mode 100644 index 3843ecd6..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/McisConnectionConfigCandidatesReq.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcis - -type McisConnectionConfigCandidatesReq struct { - CommonSpec []string `json:"commonSpec"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/McisPolicyInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/McisPolicyInfo.go deleted file mode 100644 index 54e766b1..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/McisPolicyInfo.go +++ /dev/null @@ -1,9 +0,0 @@ -package mcis - -type McisPolicyInfo struct { - ID string `json:"id"` - Name string `json:"name"` - ActionLog string `json:"actionLog"` - Description string `json:"description"` - policy Policy `json:"policy"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/McisStatusInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/McisStatusInfo.go deleted file mode 100644 index b13da358..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/McisStatusInfo.go +++ /dev/null @@ -1,19 +0,0 @@ -package mcis - -type McisStatusInfo struct { - ID string `json:"id"` - InstallMonAgent string `json:"installMonAgent"` // yes, no - Label string `json:"label"` - MasterIp string `json:"masterIp"` - MasterSSHPort string `json:"masterSSHPort"` - MasterVmID string `json:"masterVmId"` - Name string `json:"name"` - Status string `json:"status"` - StatusCount StatusCountInfo `json:"statusCount"` - SystemLabel string `json:"systemLabel"` - TargetAction string `json:"targetAction"` - TargetStatus string `json:"targetStatus"` - Vm []TbVmStatusInfo `json:"vm"` -} - -type McisStatusInfos []McisStatusInfo diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/MonResultSimple.go b/mc_web_console_api/fwmodels/tumblebug/mcis/MonResultSimple.go deleted file mode 100644 index 1ee4b38f..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/MonResultSimple.go +++ /dev/null @@ -1,8 +0,0 @@ -package mcis - -type MonResultSimple struct { - Err string `json:"err"` - Metric string `json:"metric"` // yes, no - Value string `json:"value"` - VmId string `json:"vmId"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/MonResultSimpleResponse.go b/mc_web_console_api/fwmodels/tumblebug/mcis/MonResultSimpleResponse.go deleted file mode 100644 index 2ba0cf7c..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/MonResultSimpleResponse.go +++ /dev/null @@ -1,7 +0,0 @@ -package mcis - -type MonResultSimpleResponse struct { - McisID string `json:"mcisId"` - McisMonitoring []MonResultSimple `json:"mcisMonitoring"` // yes, no - NamespaceID string `json:"nsId"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/NetworkReq.go b/mc_web_console_api/fwmodels/tumblebug/mcis/NetworkReq.go deleted file mode 100644 index 174b65d3..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/NetworkReq.go +++ /dev/null @@ -1,6 +0,0 @@ -package mcis - -type NetworkReq struct { - EtcdEndpoints []string `json:"etcdEndpoints"` - ServiceEndpoint string `json:"serviceEndpoint"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/NodeGroupStatus.go b/mc_web_console_api/fwmodels/tumblebug/mcis/NodeGroupStatus.go deleted file mode 100644 index 9b00060e..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/NodeGroupStatus.go +++ /dev/null @@ -1,11 +0,0 @@ -package mcis - -type NodeGroupStatus string - -const ( - NodeGroupCreating NodeGroupStatus = "Creating" - NodeGroupActive NodeGroupStatus = "Active" - NodeGroupInactive NodeGroupStatus = "Inactive" - NodeGroupUpdating NodeGroupStatus = "Updating" - NodeGroupDeleting NodeGroupStatus = "Deleting" -) diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/Operation.go b/mc_web_console_api/fwmodels/tumblebug/mcis/Operation.go deleted file mode 100644 index 79a78435..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/Operation.go +++ /dev/null @@ -1,6 +0,0 @@ -package mcis - -type Operation struct { - Operand string `json:"operand"` - Operator string `json:"operator"` // >=, =, <=, == -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/ParameterKeyVal.go b/mc_web_console_api/fwmodels/tumblebug/mcis/ParameterKeyVal.go deleted file mode 100644 index b8554f3e..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/ParameterKeyVal.go +++ /dev/null @@ -1,6 +0,0 @@ -package mcis - -type ParameterKeyVal struct { - Key string `json:"key"` - Val []string `json:"val"` // >=, =, <=, == -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/Policy.go b/mc_web_console_api/fwmodels/tumblebug/mcis/Policy.go deleted file mode 100644 index 938d5e26..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/Policy.go +++ /dev/null @@ -1,9 +0,0 @@ -package mcis - -type Policy struct { - AutoAction AutoAction `json:"autoAction"` - AutoCondition AutoCondition `json:"autoCondition"` - Status string `json:"status"` -} - -type Policies []Policy diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/PriorityCondition.go b/mc_web_console_api/fwmodels/tumblebug/mcis/PriorityCondition.go deleted file mode 100644 index 43f4da9a..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/PriorityCondition.go +++ /dev/null @@ -1,7 +0,0 @@ -package mcis - -type PriorityCondition struct { - Metric string `json:"metric"` - Parameter []ParameterKeyVal `json:"parameter"` - Weight string `json:"weight"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/PriorityInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/PriorityInfo.go deleted file mode 100644 index 93b89d80..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/PriorityInfo.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcis - -type PriorityInfo struct { - Policy []PriorityCondition `json:"policy"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/RegionInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/RegionInfo.go deleted file mode 100644 index 6e7f5a99..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/RegionInfo.go +++ /dev/null @@ -1,6 +0,0 @@ -package mcis - -type RegionInfo struct { - Region string `json:"region"` - Zone string `json:"zone"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/RegisterResourceAllResult.go b/mc_web_console_api/fwmodels/tumblebug/mcis/RegisterResourceAllResult.go deleted file mode 100644 index 1a1beb87..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/RegisterResourceAllResult.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcis - -type RegisterResourceAllResult struct { - RegisterationResult []RegisterResourceResult `json:"registerationResult"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/RegisterResourceResult.go b/mc_web_console_api/fwmodels/tumblebug/mcis/RegisterResourceResult.go deleted file mode 100644 index 91bac24a..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/RegisterResourceResult.go +++ /dev/null @@ -1,13 +0,0 @@ -package mcis - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type RegisterResourceResult struct { - ConnectionName string `json:"connectionName"` - ElapsedTime int `json:"elapsedTime"` - RegisterationOutputs tbcommon.TbIdList `json:"registerationOutputs"` - RegisterationOverview RegisterationOverview `json:"registerationOverview"` - SystemMessage string `json:"systemMessage"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/RegisterationOverview.go b/mc_web_console_api/fwmodels/tumblebug/mcis/RegisterationOverview.go deleted file mode 100644 index 8e0a3fda..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/RegisterationOverview.go +++ /dev/null @@ -1,9 +0,0 @@ -package mcis - -type RegisterationOverview struct { - Failed int `json:"failed"` - SecurityGroup int `json:"securityGroup"` - SshKey int `json:"sshKey"` - VNet int `json:"vNet"` - Vm int `json:"vm"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceCountOverview.go b/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceCountOverview.go deleted file mode 100644 index dd084fa9..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceCountOverview.go +++ /dev/null @@ -1,8 +0,0 @@ -package mcis - -type ResourceCountOverview struct { - OnCspOnly int `json:"onCspOnly"` - OnCspTotal int `json:"onCspTotal"` - OnSpider int `json:"onSpider"` - OnTumblebug int `json:"onTumblebug"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnCsp.go b/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnCsp.go deleted file mode 100644 index a4d439e4..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnCsp.go +++ /dev/null @@ -1,7 +0,0 @@ -package mcis - -// ResourcesOnCsp 와 ResourcesOnSpider 가 동일하여 ResourecesOnCspOrSpider 로 사용하는 것 같음. -type ResourceOnCsp struct { - Count int `json:"count"` - Info []ResourceOnCspInfo `json:"info"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnCspInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnCspInfo.go deleted file mode 100644 index f2f0a206..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnCspInfo.go +++ /dev/null @@ -1,6 +0,0 @@ -package mcis - -type ResourceOnCspInfo struct { - IdByCsp string `json:"idByCsp"` - RefNameOrId string `json:"refNameOrId"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnSpider.go b/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnSpider.go deleted file mode 100644 index f6850030..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnSpider.go +++ /dev/null @@ -1,7 +0,0 @@ -package mcis - -// ResourcesOnCsp 와 ResourcesOnSpider 가 동일하여 ResourecesOnCspOrSpider 로 사용하는 것 같음. -type ResourceOnSpider struct { - Count int `json:"count"` - Info []ResourceOnSpiderInfo `json:"info"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnSpiderInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnSpiderInfo.go deleted file mode 100644 index 8a5f3ca5..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnSpiderInfo.go +++ /dev/null @@ -1,6 +0,0 @@ -package mcis - -type ResourceOnSpiderInfo struct { - IdByCsp string `json:"idByCsp"` - IdBySp string `json:"idBySp"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnTumblebug.go b/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnTumblebug.go deleted file mode 100644 index a3fd736c..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnTumblebug.go +++ /dev/null @@ -1,6 +0,0 @@ -package mcis - -type ResourceOnTumblebug struct { - Count int `json:"count"` - Info []ResourceOnTumblebugInfo `json:"info"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnTumblebugInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnTumblebugInfo.go deleted file mode 100644 index 6620ef06..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourceOnTumblebugInfo.go +++ /dev/null @@ -1,9 +0,0 @@ -package mcis - -type ResourceOnTumblebugInfo struct { - IdByCsp string `json:"idByCsp"` - IdByTb string `json:"idByTb"` - McisId string `json:"mcisId"` - NsId string `json:"nsId"` - ObjectKey string `json:"objectKey"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourcesByManageType.go b/mc_web_console_api/fwmodels/tumblebug/mcis/ResourcesByManageType.go deleted file mode 100644 index c9c896e6..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/ResourcesByManageType.go +++ /dev/null @@ -1,8 +0,0 @@ -package mcis - -type ResourcesByManageType struct { - OnCspOnly ResourceOnCsp `json:"onCspOnly"` - OnCspTotal ResourceOnCsp `json:"onCspTotal"` - OnSpider ResourceOnSpider `json:"onSpider"` - OnTumblebug ResourceOnTumblebug `json:"onTumblebug"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/RestGetAllBenchmarkRequest.go b/mc_web_console_api/fwmodels/tumblebug/mcis/RestGetAllBenchmarkRequest.go deleted file mode 100644 index 6bafa715..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/RestGetAllBenchmarkRequest.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcis - -type RestGetAllBenchmarkRequest struct { - Host string `json:"host"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/RestGetAllMcisPolicyResponse.go b/mc_web_console_api/fwmodels/tumblebug/mcis/RestGetAllMcisPolicyResponse.go deleted file mode 100644 index 3eeee6f9..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/RestGetAllMcisPolicyResponse.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcis - -type RestGetAllMcisPolicyResponse struct { - McisPolicy McisPolicyInfo `json:"mcisPolicy"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/RestGetAllMcisResponse.go b/mc_web_console_api/fwmodels/tumblebug/mcis/RestGetAllMcisResponse.go deleted file mode 100644 index 38aca3b5..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/RestGetAllMcisResponse.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcis - -type RestGetAllMcisResponse struct { - Mcis []TbMcisInfo `json:"mcis"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/RestGetBenchmarkRequest.go b/mc_web_console_api/fwmodels/tumblebug/mcis/RestGetBenchmarkRequest.go deleted file mode 100644 index d75864cd..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/RestGetBenchmarkRequest.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcis - -type RestGetBenchmarkRequest struct { - Host string `json:"host"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/RestPostCmdMcisResponse.go b/mc_web_console_api/fwmodels/tumblebug/mcis/RestPostCmdMcisResponse.go deleted file mode 100644 index 409bb3db..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/RestPostCmdMcisResponse.go +++ /dev/null @@ -1,8 +0,0 @@ -package mcis - -type RestPostCmdMcisResponse struct { - McisID string `json:"mcisId"` - Result string `json:"result"` - VmID string `json:"vmId"` - VmIp string `json:"vmIp"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/RestPostCmdMcisResponseWrapper.go b/mc_web_console_api/fwmodels/tumblebug/mcis/RestPostCmdMcisResponseWrapper.go deleted file mode 100644 index a3437f87..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/RestPostCmdMcisResponseWrapper.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcis - -type RestPostCmdMcisResponseWrapper struct { - ResultArray []RestPostCmdMcisResponse `json:"resultArray"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/RestPostCmdMcisVmResponse.go b/mc_web_console_api/fwmodels/tumblebug/mcis/RestPostCmdMcisVmResponse.go deleted file mode 100644 index 2c4aa7c5..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/RestPostCmdMcisVmResponse.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcis - -type RestPostCmdMcisVmResponse struct { - Result string `json:"result"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/SpiderVMInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/SpiderVMInfo.go deleted file mode 100644 index d410d351..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/SpiderVMInfo.go +++ /dev/null @@ -1,43 +0,0 @@ -package mcis - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type SpiderVMInfo struct { - CspId string `json:"cspid"` - IID tbcommon.TbIID `json:"iid"` - ImageIID tbcommon.TbIID `json:"imageIId"` - KeyPairIID tbcommon.TbIID `json:"keyPairIId"` - KeyPairName string `json:"keyPairName"` - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` - Name string `json:"name"` - NetworkInterface string `json:"networkInterface"` - - PrivateDns string `json:"networkInterface"` - PrivateIP string `json:"privateIP"` - PublicDns string `json:"publicDns"` - PublicIP string `json:"publicIP"` - Region RegionInfo `json:"region"` - SecurityGroupIIds []tbcommon.TbIID `json:"securityGroupIIds"` - SecurityGroupNames []string `json:"securityGroupNames"` - - SshaccessPoint string `json:"sshaccessPoint"` - StartTime string `json:"startTime"` - - SubnetIID tbcommon.TbIID `json:"subnetIID"` - SubnetName string `json:"subnetName"` - - VmblockDisk string `json:"vmblockDisk"` - VmbootDisk string `json:"vmbootDisk"` - VmspecName string `json:"vmspecName"` - VmuserId string `json:"vmuserId"` - VmuserPasswd string `json:"vmuserPasswd"` - - RootDeviceName string `json:"rootDeviceName"` - RootDiskSize string `json:"rootDiskSize"` - RootDiskType string `json:"rootDiskType"` - - VpcIID tbcommon.TbIID `json:"vpcIID"` - VpcName string `json:"vpcName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/StatusCountInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/StatusCountInfo.go deleted file mode 100644 index 36f5b4de..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/StatusCountInfo.go +++ /dev/null @@ -1,15 +0,0 @@ -package mcis - -type StatusCountInfo struct { - CountCreating int `json:"countCreating"` - CountFailed int `json:"countFailed"` - CountRebooting int `json:"countRebooting"` - CountResuming int `json:"countResuming"` - CountRunning int `json:"countRunning"` - CountSuspended int `json:"countSuspended"` - CountSuspending int `json:"countSuspending"` - CountTerminated int `json:"countTerminated"` - CountTerminating int `json:"countTerminating"` - CountTotal int `json:"countTotal"` - CountUndefined int `json:"countUndefined"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterAccessInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterAccessInfo.go deleted file mode 100644 index 69bca6eb..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterAccessInfo.go +++ /dev/null @@ -1,7 +0,0 @@ -package mcis - -// TbClusterAccessInfo is a struct to handle Cluster Access information from the CB-Tumblebug's REST API response -type TbClusterAccessInfo struct { - Endpoint string `json:"endpoint" example:"http://1.2.3.4:6443"` - Kubeconfig string `json:"kubeconfig"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterAddonsInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterAddonsInfo.go deleted file mode 100644 index e3c7ad73..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterAddonsInfo.go +++ /dev/null @@ -1,8 +0,0 @@ -package mcis - -import tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - -// TbClusterAddonsInfo is a struct to handle Cluster Addons information from the CB-Tumblebug's REST API response -type TbClusterAddonsInfo struct { - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterInfo.go deleted file mode 100644 index 14650693..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterInfo.go +++ /dev/null @@ -1,36 +0,0 @@ -package mcis - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - "time" -) - -type TbClusterInfo struct { // Tumblebug - Id string `json:"id"` - Name string `json:"name"` - ConnectionName string `json:"connectionName"` - - Version string `json:"version" example:"1.23.3"` // Kubernetes Version, ex) 1.23.3 - Network TbClusterNetworkInfo - - // --- - - NodeGroupList []TbClusterNodeGroupInfo - AccessInfo TbClusterAccessInfo - Addons TbClusterAddonsInfo - - Status TbClusterStatus `json:"status" example:"Creating"` // Creating, Active, Inactive, Updating, Deleting - - CreatedTime time.Time `json:"createdTime" example:"1970-01-01T00:00:00.00Z"` - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` - - Description string `json:"description"` - CspClusterId string `json:"cspClusterId"` - CspClusterName string `json:"cspClusterName"` - - // Latest system message such as error message - SystemMessage string `json:"systemMessage" example:"Failed because ..." default:""` // systeam-given string message - - // SystemLabel is for describing the MCIR in a keyword (any string can be used) for special System purpose - SystemLabel string `json:"systemLabel" example:"Managed by CB-Tumblebug" default:""` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterNetworkInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterNetworkInfo.go deleted file mode 100644 index 01eec9dd..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterNetworkInfo.go +++ /dev/null @@ -1,13 +0,0 @@ -package mcis - -import tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - -type TbClusterNetworkInfo struct { - VNetId string `json:"vNetId"` - SubnetIds []string `json:"subnetIds"` - SecurityGroupIds []string `json:"securityGroupIds"` - - // --- - - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterNodeGroupInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterNodeGroupInfo.go deleted file mode 100644 index d1bd3d50..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterNodeGroupInfo.go +++ /dev/null @@ -1,27 +0,0 @@ -package mcis - -import tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - -type TbClusterNodeGroupInfo struct { - Id string `json:"id"` - //Name string `json:"name"` - - // VM config. - ImageId string `json:"imageId"` - SpecId string `json:"specId"` - RootDiskType string `json:"rootDiskType"` - RootDiskSize string `json:"rootDiskSize"` - SshKeyId string `json:"sshKeyId"` - - // Scaling config. - OnAutoScaling bool `json:"onAutoScaling"` - DesiredNodeSize int `json:"desiredNodeSize"` - MinNodeSize int `json:"minNodeSize"` - MaxNodeSize int `json:"maxNodeSize"` - - // --- - Status NodeGroupStatus `json:"status" example:"Creating"` // Creating, Active, Inactive, Updating, Deleting - Nodes []string `json:"nodes"` // id for nodes - - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterReq.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterReq.go deleted file mode 100644 index 4b4d6b28..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterReq.go +++ /dev/null @@ -1,24 +0,0 @@ -package mcis - -// TbClusterReq is a struct to handle 'Create cluster' request toward CB-Tumblebug. -type TbClusterReq struct { // Tumblebug - //Namespace string `json:"namespace" validate:"required" example:"ns01"` - ConnectionName string `json:"connectionName" validate:"required" example:"testcloud01-seoul"` - Description string `json:"description"` - - // (1) Cluster Info - Id string `json:"id" validate:"required" example:"testcloud01-seoul-cluster"` - Version string `json:"version" example:"1.23.4"` - - // (2) Network Info - VNetId string `json:"vNetId" validate:"required"` - SubnetIds []string `json:"subnetIds" validate:"required"` - SecurityGroupIds []string `json:"securityGroupIds" validate:"required"` - - // (3) NodeGroupInfo List - NodeGroupList []TbNodeGroupReq `json:"nodeGroupList"` - - // Fields for "Register existing cluster" feature - // CspClusterId is required to register a cluster from CSP (option=register) - CspClusterId string `json:"cspClusterId"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterStatus.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterStatus.go deleted file mode 100644 index 438eac35..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbClusterStatus.go +++ /dev/null @@ -1,13 +0,0 @@ -package mcis - -// 2023-11-14 https://github.com/cloud-barista/cb-spider/blob/fa4bd91fdaa6bb853ea96eca4a7b4f58a2abebf2/cloud-control-manager/cloud-driver/interfaces/resources/ClusterHandler.go#L15 - -type TbClusterStatus string - -const ( - ClusterCreating TbClusterStatus = "Creating" - ClusterActive TbClusterStatus = "Active" - ClusterInactive TbClusterStatus = "Inactive" - ClusterUpdating TbClusterStatus = "Updating" - ClusterDeleting TbClusterStatus = "Deleting" -) diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbCustomImageInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbCustomImageInfo.go deleted file mode 100644 index 04d01429..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbCustomImageInfo.go +++ /dev/null @@ -1,23 +0,0 @@ -package mcis - -import tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - -type TbCustomImageInfo struct { - AssociatedObjectList []string `json:"associatedObjectList"` - ConnectionName string `json:"connectionName"` - CreatedTime string `json:"createdTime"` - CspCustomImageId string `json:"cspCustomImageId"` - CspCustomImageName string `json:"cspCustomImageName"` - Description string `json:"description"` - GuestOS string `json:"guestOS"` - - ID string `json:"id"` - isAutoGenerated bool `json:"isAutoGenerated"` - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` - Name string `json:"name"` - NameSpace string `json:"namespace"` - SourceVmId string `json:"sourceVmId"` - - Status string `json:"status"` - SystemLabel string `json:"systemLabel"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbMcisDynamicReq.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbMcisDynamicReq.go deleted file mode 100644 index e2782540..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbMcisDynamicReq.go +++ /dev/null @@ -1,10 +0,0 @@ -package mcis - -type TbMcisDynamicReq struct { - Description string `json:"description"` - InstallMonAgent string `json:"installMonAgent"` - Label string `json:"label"` - Name string `json:"name"` - SystemLabel string `json:"systemLabel"` - Vm []TbVmDynamicReq `json:"vm"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbMcisInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbMcisInfo.go deleted file mode 100644 index ddf6a52e..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbMcisInfo.go +++ /dev/null @@ -1,18 +0,0 @@ -package mcis - -type TbMcisInfo struct { - ConfigureCloudAdaptiveNetwork string `json:"configureCloudAdaptiveNetwork"` - ID string `json:"id"` - Description string `json:"description"` - InstallMonAgent string `json:"installMonAgent"` - Label string `json:"label"` - SystemLabel string `json:"systemLabel"` - Name string `json:"name"` - PlacementAlgo string `json:"placementAlgo"` - Status string `json:"status"` - StatusCount StatusCountInfo `json:"statusCount"` - TargetAction string `json:"targetAction"` - TargetStatus string `json:"targetStatus"` - - Vm []TbVmInfo `json:"vm"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbMcisReq.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbMcisReq.go deleted file mode 100644 index 31fd5a22..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbMcisReq.go +++ /dev/null @@ -1,13 +0,0 @@ -package mcis - -type TbMcisReq struct { - Description string `json:"description"` - InstallMonAgent string `json:"installMonAgent"` - Label string `json:"label"` - Name string `json:"name"` - PlacementAlgo string `json:"placementAlgo"` - SystemLabel string `json:"systemLabel"` - - // Vm TbVmInfo `json:"vm"` - Vm []TbVmReq `json:"vm"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBAddRemoveVMReq.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBAddRemoveVMReq.go deleted file mode 100644 index de17ee7d..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBAddRemoveVMReq.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcis - -type TbNLBAddRemoveVMReq struct { - TargetGroup []TbNLBTargetGroup `json:"targetGroup"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBHealthCheckerInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBHealthCheckerInfo.go deleted file mode 100644 index ec8b1830..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBHealthCheckerInfo.go +++ /dev/null @@ -1,16 +0,0 @@ -package mcis - -import tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - -type TbNLBHealthCheckerInfo struct { - CspID string `json:"cspID"` - - Protocol string `json:"protocol"` - Port string `json:"port"` - - Interval int `json:"interval"` - Threshold int `json:"threshold"` - Timeout int `json:"timeout"` - - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBHealthCheckerReq.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBHealthCheckerReq.go deleted file mode 100644 index fb2540d3..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBHealthCheckerReq.go +++ /dev/null @@ -1,10 +0,0 @@ -package mcis - -type TbNLBHealthCheckerReq struct { - // Protocol string `json:"protocol"` - // Port string `json:"port"` - - Interval string `json:"interval"` - Threshold string `json:"threshold"` - Timeout string `json:"timeout"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBInfo.go deleted file mode 100644 index a6af8260..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBInfo.go +++ /dev/null @@ -1,31 +0,0 @@ -package mcis - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type TbNLBInfo struct { - AssociatedObjectList []string `json:"associatedObjectList"` - ConnectionName string `json:"connectionName"` - CreatedTime string `json:"createdTime"` - CspNlbId string `json:"cspNlbId"` - CspNlbName string `json:"cspNlbName"` - Description string `json:"description"` - - HealthChecker TbNLBHealthCheckerInfo `json:"healthChecker"` - Listener TbNLBListenerInfo `json:"listener"` - Location tbcommon.TbGeoLocation `json:"location"` - TargetGroup TbNLBTargetGroup `json:"targetGroup"` - - ID string `json:"id"` - IsAutoGenerated bool `json:"isAutoGenerated"` - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` - Name string `json:"name"` - Status string `json:"status"` - SystemLabel string `json:"systemLabel"` - - Scope string `json:"scope"` - Type string `json:"type"` - - McisID string `json:"mcisId"` // TB에서 해당항목이 없지만 NLB는 McisID가 필수라 추가함. -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBListenerInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBListenerInfo.go deleted file mode 100644 index 2817997e..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBListenerInfo.go +++ /dev/null @@ -1,15 +0,0 @@ -package mcis - -import tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - -type TbNLBListenerInfo struct { - CspID string `json:"cspID"` - DnsName string `json:"dnsName"` - - Ip string `json:"ip"` - - Protocol string `json:"protocol"` - Port string `json:"port"` - - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBReq.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBReq.go deleted file mode 100644 index 9880b03d..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBReq.go +++ /dev/null @@ -1,28 +0,0 @@ -package mcis - -import tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - -type TbNLBReq struct { - ConnectionName string `json:"connectionName"` - CspNlbId string `json:"cspNlbId"` - Description string `json:"description"` - Name string `json:"name"` - Scope string `json:"scope"` - Type string `json:"type"` - - VNetId string `json:"vNetId"` - - HealthCheckerReq TbNLBHealthCheckerReq `json:"healthCheckerReq"` - Listener TbNLBListenerInfo `json:"listener"` - TargetGroup TbNLBTargetGroup `json:"targetGroup"` - - IsAutoGenerated bool `json:"isAutoGenerated"` - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` - Status string `json:"status"` - SystemLabel string `json:"systemLabel"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBTargetGroup.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBTargetGroup.go deleted file mode 100644 index 51abbf3f..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNLBTargetGroup.go +++ /dev/null @@ -1,15 +0,0 @@ -package mcis - -import tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - -type TbNLBTargetGroup struct { - CspID string `json:"cspID"` - - Protocol string `json:"protocol"` - Port string `json:"port"` - - SubGroupId string `json:"subGroupId"` - Vms []string `json:"vms"` - - KeyValueList []tbcommon.TbKeyValue `json:"keyValueList"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNodeGroupReq.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbNodeGroupReq.go deleted file mode 100644 index 620c12f2..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbNodeGroupReq.go +++ /dev/null @@ -1,17 +0,0 @@ -package mcis - -// TbNodeGroupReq is a struct to handle requests related to NodeGroup toward CB-Tumblebug. -type TbNodeGroupReq struct { - Name string `json:"name"` - ImageId string `json:"imageId"` - SpecId string `json:"specId"` - RootDiskType string `json:"rootDiskType" example:"default, TYPE1, ..."` // "", "default", "TYPE1", AWS: ["standard", "gp2", "gp3"], Azure: ["PremiumSSD", "StandardSSD", "StandardHDD"], GCP: ["pd-standard", "pd-balanced", "pd-ssd", "pd-extreme"], ALIBABA: ["cloud_efficiency", "cloud", "cloud_ssd"], TENCENT: ["CLOUD_PREMIUM", "CLOUD_SSD"] - RootDiskSize string `json:"rootDiskSize" example:"default, 30, 42, ..."` // "default", Integer (GB): ["50", ..., "1000"] - SshKeyId string `json:"sshKeyId"` - - // autoscale config. - OnAutoScaling string `json:"onAutoScaling"` - DesiredNodeSize string `json:"desiredNodeSize"` - MinNodeSize string `json:"minNodeSize"` - MaxNodeSize string `json:"maxNodeSize"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbScaleOutVmGroupReq.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbScaleOutVmGroupReq.go deleted file mode 100644 index e4d115ba..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbScaleOutVmGroupReq.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcis - -type TbScaleOutSubGroupReq struct { - NumVMsToAdd string `json:"numVMsToAdd"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbStatusInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbStatusInfo.go deleted file mode 100644 index 947302a5..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbStatusInfo.go +++ /dev/null @@ -1,7 +0,0 @@ -package mcis - -type StatusInfo struct { - Code int `json:"code"` - Kind string `json:"kind"` - Message string `json:"message"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmDynamicReq.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmDynamicReq.go deleted file mode 100644 index fdc5528d..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmDynamicReq.go +++ /dev/null @@ -1,18 +0,0 @@ -package mcis - -type TbVmDynamicReq struct { - CommonImage string `json:"commonImage"` - CommonSpec string `json:"commonSpec"` - ConnectionName string `json:"connectionName"` - Description string `json:"description"` - Label string `json:"label"` - Name string `json:"name"` - RootDiskSize string `json:"rootDiskSize"` - RootDiskType string `json:"rootDiskType"` - SubGroupSize string `json:"subGroupSize"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmInfo.go deleted file mode 100644 index a6e175cf..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmInfo.go +++ /dev/null @@ -1,51 +0,0 @@ -package mcis - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type TbVmInfo struct { - ConnectionName string `json:"connectionName"` - CreatedTime string `json:"createdTime"` - - CspViewVmDetail SpiderVMInfo `json:"cspViewVmDetail"` - - Description string `json:"description"` - ID string `json:"id"` - IdByCSP string `json:"idByCSP"` - ImageID string `json:"imageId"` - Label string `json:"label"` - Location tbcommon.TbGeoLocation `json:"location"` - - MonAgentStatus string `json:"monAgentStatus"` - - Name string `json:"name"` - NetworkAgentStatus string `json:"networkAgentStatus"` - PrivateDns string `json:"privateDns"` - PrivateIP string `json:"privateIP"` - PublicDNS string `json:"publicDNS"` - PublicIP string `json:"publicIP"` - Region RegionInfo `json:"region"` - - RootDeviceName string `json:"rootDeviceName"` - RootDiskSize string `json:"rootDiskSize"` - RootDiskType string `json:"rootDiskType"` - DataDiskIds []string `json:"dataDiskIds"` - - SecurityGroupIDs []string `json:"securityGroupIds"` - - SpecID string `json:"specId"` - SshKeyID string `json:"sshKeyId"` - SshPort string `json:"sshPort"` - Status string `json:"status"` - SubnetID string `json:"subnetId"` - SystemMessage string `json:"systemMessage"` - TargetAction string `json:"targetAction"` - TargetStatus string `json:"targetStatus"` - VNetID string `json:"vNetId"` - VmBlockDisk string `json:"vmBlockDisk"` - VmBootDisk string `json:"vmBootDisk"` - SubGroupID string `json:"subGroupId"` - VmUserAccount string `json:"vmUserAccount"` - VmUserPassword string `json:"vmUserPassword"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmRecommendReq.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmRecommendReq.go deleted file mode 100644 index e7524514..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmRecommendReq.go +++ /dev/null @@ -1,16 +0,0 @@ -package mcis - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type TbVmRecommendReq struct { - DiskSize string `json:"diskSize"` - MaxResultNum string `json:"maxResultNum"` - MemorySize string `json:"memorySize"` - PlacementAlgo string `json:"placementAlgo"` - PlacementParam []tbcommon.TbKeyValue `json:"placementParam"` - - RequestName string `json:"requestName"` - VcpuSize string `json:"vcpuSize"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmReq.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmReq.go deleted file mode 100644 index 41054f8e..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmReq.go +++ /dev/null @@ -1,35 +0,0 @@ -package mcis - -type TbVmReqs struct { - VmReqList []TbVmReq `json:"vm"` -} - -type TbVmReq struct { - ConnectionName string `json:"connectionName"` - Description string `json:"description"` - IdByCsp string `json:"idByCsp"` - ImageID string `json:"imageId"` - ImageType string `json:"imageType"` - Label string `json:"label"` - Name string `json:"name"` - - RootDiskSize string `json:"rootDiskSize"` - RootDiskType string `json:"rootDiskType"` - - SecurityGroupIDs []string `json:"securityGroupIds"` - - SpecID string `json:"specId"` - SshKeyID string `json:"sshKeyId"` - SubnetID string `json:"subnetId"` - VNetID string `json:"vNetId"` - SubGroupSize string `json:"subGroupSize"` - VmUserAccount string `json:"vmUserAccount"` - VmUserPassword string `json:"vmUserPassword"` - - DataDiskIds []string `json:"dataDiskIds"` - - ProviderID string `json:"providerId"` - ProviderName string `json:"providerName"` - RegionName string `json:"regionName"` - ZoneName string `json:"zoneName"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmSnapshotReq.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmSnapshotReq.go deleted file mode 100644 index d621ce2c..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmSnapshotReq.go +++ /dev/null @@ -1,5 +0,0 @@ -package mcis - -type TbVmSnapshotReq struct { - Name string `json:"name"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmStatusInfo.go b/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmStatusInfo.go deleted file mode 100644 index b77b771a..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/mcis/TbVmStatusInfo.go +++ /dev/null @@ -1,25 +0,0 @@ -package mcis - -import ( - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" -) - -type TbVmStatusInfo struct { - CreatedTime string `json:"createdTime"` - CspVmID string `json:"cspVmId"` - - ID string `json:"id"` - Location tbcommon.TbGeoLocation `json:"location"` - - MonAgentStatus string `json:"monAgentStatus"` - - Name string `json:"name"` - NativeStatus string `json:"nativeStatus"` - PrivateIP string `json:"privateIP"` - PublicIP string `json:"publicIP"` - SshPort string `json:"sshPort"` - Status string `json:"status"` - SystemMessage string `json:"systemMessage"` - TargetAction string `json:"targetAction"` - TargetStatus string `json:"targetStatus"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/netutil/Network.go b/mc_web_console_api/fwmodels/tumblebug/netutil/Network.go deleted file mode 100644 index f6b54750..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/netutil/Network.go +++ /dev/null @@ -1,7 +0,0 @@ -package netutil - -type Network struct { - CIDRBlock string `json:"cidrBlock"` - Name string `json:"name,omitempty"` - Subnets []Network `json:"subnets,omitempty"` -} \ No newline at end of file diff --git a/mc_web_console_api/fwmodels/tumblebug/netutil/NetworkConfig.go b/mc_web_console_api/fwmodels/tumblebug/netutil/NetworkConfig.go deleted file mode 100644 index 87d6cd7e..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/netutil/NetworkConfig.go +++ /dev/null @@ -1,5 +0,0 @@ -package netutil - -type NetworkConfig struct { - NetworkConfiguration Network `json:"networkConfiguration"` -} \ No newline at end of file diff --git a/mc_web_console_api/fwmodels/tumblebug/netutil/NetworkDetails.go b/mc_web_console_api/fwmodels/tumblebug/netutil/NetworkDetails.go deleted file mode 100644 index 6b754b90..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/netutil/NetworkDetails.go +++ /dev/null @@ -1,11 +0,0 @@ -package netutil - -type NetworkDetails struct { -// Network - Network Network `json:"network"` - NetworkAddress string `json:"networkAddress,omitempty"` - BroadcastAddress string `json:"broadcastAddress,omitempty"` - Prefix int `json:"prefix,omitempty"` - Netmask string `json:"netmask,omitempty"` - HostCapacity int `json:"hostCapacity,omitempty"` -} \ No newline at end of file diff --git a/mc_web_console_api/fwmodels/tumblebug/netutil/RestPostUtilToDesignNetworkRequest.go b/mc_web_console_api/fwmodels/tumblebug/netutil/RestPostUtilToDesignNetworkRequest.go deleted file mode 100644 index 4e8fdae0..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/netutil/RestPostUtilToDesignNetworkRequest.go +++ /dev/null @@ -1,11 +0,0 @@ -package netutil - -type RestPostUtilToDesignNetworkRequest struct { - //SubnettingRequest - SubnettingRequest SubnettingRequest `json:"subnettingRequest"` -} - -type RestPostUtilToDesignNetworkReponse struct { - //Network - Network Network `json:"setwork"` -} \ No newline at end of file diff --git a/mc_web_console_api/fwmodels/tumblebug/netutil/RestPostUtilToValidateNetworkRequest.go b/mc_web_console_api/fwmodels/tumblebug/netutil/RestPostUtilToValidateNetworkRequest.go deleted file mode 100644 index a28d48cf..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/netutil/RestPostUtilToValidateNetworkRequest.go +++ /dev/null @@ -1,6 +0,0 @@ -package netutil - -type RestPostUtilToValidateNetworkRequest struct { - //netutil.NetworkConfig - NetworkConfig NetworkConfig `json:"networkConfig"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/netutil/SubnettingRequest.go b/mc_web_console_api/fwmodels/tumblebug/netutil/SubnettingRequest.go deleted file mode 100644 index da55c242..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/netutil/SubnettingRequest.go +++ /dev/null @@ -1,7 +0,0 @@ -package netutil - - -type SubnettingRequest struct { - CIDRBlock string `json:"cidrBlock" example:"192.168.0.0/16"` - SubnettingRules []SubnettingRule `json:"subnettingRules"` -} diff --git a/mc_web_console_api/fwmodels/tumblebug/netutil/SubnettingRule.go b/mc_web_console_api/fwmodels/tumblebug/netutil/SubnettingRule.go deleted file mode 100644 index 48f4182f..00000000 --- a/mc_web_console_api/fwmodels/tumblebug/netutil/SubnettingRule.go +++ /dev/null @@ -1,13 +0,0 @@ -package netutil - -// type SubnettingRule struct { -// Type SubnettingRuleType `json:"type" example:"minSubnets" enum:"minSubnets,minHosts"` -// Value int `json:"value" example:"2"` -// } -type SubnettingRule struct { - SubnettingRuleType string `json:"type" example:"minSubnets" enum:"minSubnets,minHosts"` - Value int `json:"value" example:"2"` -} - -// SubnettingRuleType defines the type for subnetting rules. -type SubnettingRuleType string \ No newline at end of file diff --git a/mc_web_console_api/fwmodels/webconsole/AvailableDiskType.go b/mc_web_console_api/fwmodels/webconsole/AvailableDiskType.go deleted file mode 100644 index e12f342e..00000000 --- a/mc_web_console_api/fwmodels/webconsole/AvailableDiskType.go +++ /dev/null @@ -1,14 +0,0 @@ -package webconsole - -type AvailableDiskType struct { - // create disk list - ProviderID string `json:"providerId"` - - RootDiskType []string `json:"rootdisktype"` - - // - DataDiskType []string `json:"datadisktype"` - - // disk size range by diskType - DiskSize []string `json:"disksize"` -} diff --git a/mc_web_console_api/fwmodels/webconsole/DataDiskCreateReq.go b/mc_web_console_api/fwmodels/webconsole/DataDiskCreateReq.go deleted file mode 100644 index bcb255aa..00000000 --- a/mc_web_console_api/fwmodels/webconsole/DataDiskCreateReq.go +++ /dev/null @@ -1,17 +0,0 @@ -package webconsole - -type DataDiskCreateReq struct { - - //tbmcir.TbDataDiskReq - Name string `json:"name"` - ConnectionName string `json:"connectionName"` - CspDataDiskId string `json:"cspDataDiskId"` - Description string `json:"description"` - DiskSize string `json:"diskSize"` - DiskType string `json:"diskType"` - - // Attach VMID - McisID string `json:"mcisId"` - //VmID string `json:"vmId"` - AttachVmID string `json:"attachVmId"` -} diff --git a/mc_web_console_api/fwmodels/webconsole/DataDiskMngReq.go b/mc_web_console_api/fwmodels/webconsole/DataDiskMngReq.go deleted file mode 100644 index ca0f9b7a..00000000 --- a/mc_web_console_api/fwmodels/webconsole/DataDiskMngReq.go +++ /dev/null @@ -1,17 +0,0 @@ -package webconsole - -type DataDiskMngReq struct { - // create disk list - CreateDataDiskList []DataDiskCreateReq `json:"createDataDiskList"` - - // attach list - AttachDataDiskList []string `json:"attachDataDiskList"` - - // detach list - DetachDataDiskList []string `json:"detachDataDiskList"` - - // del disk list - DeleteDataDiskList []string `json:"dataDiskList"` - - // update :TbDataDiskUpsizeReq -} diff --git a/mc_web_console_api/fwmodels/webconsole/LookupDiskInfo.go b/mc_web_console_api/fwmodels/webconsole/LookupDiskInfo.go deleted file mode 100644 index 342f5a47..00000000 --- a/mc_web_console_api/fwmodels/webconsole/LookupDiskInfo.go +++ /dev/null @@ -1,14 +0,0 @@ -package webconsole - -type LookupDiskInfo struct { - // create disk list - ProviderID string `json:"providerId"` - - RootDiskType []string `json:"rootdisktype"` - - // - DataDiskType []string `json:"datadisktype"` - - // disk size range by diskType - DiskSize []string `json:"disksize"` -} diff --git a/mc_web_console_api/fwmodels/webconsole/McisLifeCycle.go b/mc_web_console_api/fwmodels/webconsole/McisLifeCycle.go deleted file mode 100644 index fcef25f7..00000000 --- a/mc_web_console_api/fwmodels/webconsole/McisLifeCycle.go +++ /dev/null @@ -1,10 +0,0 @@ -package webconsole - -// Life Cycle command 전송용 : VM과 Lifecycle 이 다를 수 있으므로 각각 사용 -type McisLifeCycle struct { - NameSpaceID string `json:"nameSpaceID"` - McisID string `json:"mcisID"` - Action string `json:"action"` - Force string `json:"force"` - //QueryParams []string `json:"queryParams"` // queryParams에 들어올 수 있는 값: action, force / action : create, suspend, resume, terminate, delete : Const.MCIS_LIFECYCLE_xxx / force : false, true -} diff --git a/mc_web_console_api/fwmodels/webconsole/McisSimpleInfo.go b/mc_web_console_api/fwmodels/webconsole/McisSimpleInfo.go deleted file mode 100644 index dac7efd1..00000000 --- a/mc_web_console_api/fwmodels/webconsole/McisSimpleInfo.go +++ /dev/null @@ -1,38 +0,0 @@ -package webconsole - -// MCIS의 일부정보만 추려서 -type McisSimpleInfo struct { - // ID string `json:"id"` - // Name string `json:"name"` - // Status string `json:"status"` - // VMNum string `json:"vm_num"` - - // mcis.ID, mcis.status, mcis.name, mcis.description - ID string `json:"id"` - Name string `json:"name"` - Status string `json:"status"` - McisStatus string `json:"mcisStatus"` - Description string `json:"description"` - - InstallMonAgent string `json:"installMonAgent"` - Label string `json:"label"` - - ConnectionCount int `json:"connectionCount"` - - // vm_cnt : 해당 mcis의 vm cnt - // vm_run_cnt, vm_stop_cnt - VmCount int `json:"vmCount"` - VmStatusNames string `json:"vmStatusNames"` - VmSimpleList []VmSimpleInfo `json:"vmSimpleList"` - VmStatusCountMap map[string]int `json:"vmStatusCountMap"` - // VmRunningCount int `json:"vnRunningCount"` - // VmStoppedCount int `json:"vmStopped"` - // VmTerminatedCount int `json:"vmTerminated"` - - // csp : 해당 mcis의 connection cnt - ConnectionConfigProviderMap map[string]int `json:"connectionConfigProviderMap"` - ConnectionConfigProviderNames string `json:"connectionConfigProviderNames"` // 해당 MCIS 등록된 connection의 provider 목록 - // ConnectionConfigProviderNames []string `json:"connectionConfigProviderNames"` // 해당 MCIS 등록된 connection의 provider 목록 - ConnectionConfigProviderCount int `json:"connectionConfigProviderCount"` -} -type McisSimpleInfos []McisSimpleInfo diff --git a/mc_web_console_api/fwmodels/webconsole/UserNamespaceReq.go b/mc_web_console_api/fwmodels/webconsole/UserNamespaceReq.go deleted file mode 100644 index 6a5ccbc0..00000000 --- a/mc_web_console_api/fwmodels/webconsole/UserNamespaceReq.go +++ /dev/null @@ -1,6 +0,0 @@ -package webconsole - -type UserNamespaceReq struct { - Ns []string `json:"ns"` - Us []string `json:"us"` -} diff --git a/mc_web_console_api/fwmodels/webconsole/VmLifeCycle.go b/mc_web_console_api/fwmodels/webconsole/VmLifeCycle.go deleted file mode 100644 index 4597a954..00000000 --- a/mc_web_console_api/fwmodels/webconsole/VmLifeCycle.go +++ /dev/null @@ -1,10 +0,0 @@ -package webconsole - -// Life Cycle command 전송용 -type VmLifeCycle struct { - NameSpaceID string `json:"nameSpaceID"` - McisID string `json:"mcisID"` - VmID string `json:"vmID"` - Action string `json:"action"` // reboot, create, suspend, resume, terminate, delete : Const.VM_LIFECYCLE_xxx - Force string `json:"force"` -} diff --git a/mc_web_console_api/fwmodels/webconsole/VmSimpleInfo.go b/mc_web_console_api/fwmodels/webconsole/VmSimpleInfo.go deleted file mode 100644 index f49dd0fc..00000000 --- a/mc_web_console_api/fwmodels/webconsole/VmSimpleInfo.go +++ /dev/null @@ -1,30 +0,0 @@ -package webconsole - -// VM의 상태정보 -// 원래는 상태정보(VmStatus), 위치정보(Latitude, Longitude) 만 있었으나 -// export 기능 추가로 param 추가 됨. -type VmSimpleInfo struct { - VmIndex int `json:"vmIndex"` - VmID string `json:"vmID"` - VmName string `json:"vmName"` - VmStatus string `json:"vmStatus"` - - // Latitude float64 `json:"latitude"` - // Longitude float64 `json:"longitude"` - Latitude string `json:"latitude"` - Longitude string `json:"longitude"` - - // export 를 위한 param들 추가 - VmConnectionName string `json:"vmConnectionName"` - VmDescription string `json:"vmDescription"` - VmImageId string `json:"vmImageId"` - VmLabel string `json:"vmLabel"` - VmSecurityGroupIds []string `json:"vmSecurityGroupIds"` //"securityGroupIIds": [ { "nameId": "string", "systemId": "string" } ], - VmSpecId string `json:"vmSpecId"` - VmSshKeyId string `json:"vmSshKeyId"` - VmSubnetId string `json:"vmSubnetId"` - VmVnetId string `json:"vmVnetId"` - SubGroupSize int `json:"subGroupSize"` //subGroupId만 있는데... - VmUserAccount string `json:"vmUserAccount"` - VmUserPassword string `json:"vmUserPassword"` -} diff --git a/mc_web_console_api/fwmodels/websocket/WebSocketMessage.go b/mc_web_console_api/fwmodels/websocket/WebSocketMessage.go deleted file mode 100644 index 6f2f1574..00000000 --- a/mc_web_console_api/fwmodels/websocket/WebSocketMessage.go +++ /dev/null @@ -1,30 +0,0 @@ -package websocket - -// client와 서버가 통신하면서 비동기로 처리된 data 알림용 -// echo session에서 값을 저장하는 key=socketdata 이며 map안에 WebSocketMessage 객체가 들어감 ex) store.Get("socketdata"), store.Set("socketdata", socketDataMap) -// 추후 필요시 userid 추가 -// Send 는 기본 false 이며 전송이 되면 true 바꾼다. -// 생성에 관해서는 생성, 중단, 재가동, 삭제 등이 life cycle이므로 lifeCycle 상태값이 다르므로 해당 상태값을 사용한다. ex) create_request -> creating -> created or create completed 등 -// 처리 상태는 해당 job에서 사용하는 상태를 사용. 임시로 요청상태(request), 진행중(ing), 완료(complete), 실패(fail) - -import ( - "time" -) - -type WebSocketMessage struct { - TaskType string `json:"taskType"` // 처리되는 Operation 구분. ex) mcis, mcks, vm, vnet, connection .... - TaskKey string `json:"taskKey"` // session에서 값을 찾기 위한 key namespace || tasktype || id or name ex) ns01||mcis||testmcis01 TODO : unique할까?? taskType에 대해서는 unique 할 듯. - LifeCycle string `json:"lifeCycle"` // 처리 구분 create, suspend, resume, terminate, delete ... 등 - Status string `json:"status"` // 처리상태 ( request, ing, complete ...) tb에서 보내는 상태에 따라 달라질 수 있음. - Send bool `json:"send"` // 메세지 전송여부(UI로 Push 했는지) - Message string `json:"message"` // 전달 할 Message - Event string `json:"event"` // 화면이 열렸을 때(open), 닫혔을 때(close), 요청(req), 응답(res) - ProcessTime time.Time `json:"processTime"` // 상태변경 시간. 마지막으로 수신한 processTime 을 UI에서 가지고 해당 시간을 넘기면 lastProcessTime 이후꺼만 조회하면 될 듯. -} - -type SocketMessage struct { - SaveTime int64 `json:"saveTime"` - Message WebSocketMessage `json:"message"` -} - -type SocketMessageList []SocketMessage diff --git a/mc_web_console_api/go.mod b/mc_web_console_api/go.mod index ac81c748..6cde04c5 100644 --- a/mc_web_console_api/go.mod +++ b/mc_web_console_api/go.mod @@ -3,7 +3,6 @@ module mc_web_console_api go 1.21.0 require ( - github.com/davecgh/go-spew v1.1.1 github.com/gobuffalo/buffalo v1.1.0 github.com/gobuffalo/buffalo-pop/v3 v3.0.7 github.com/gobuffalo/envy v1.10.2 @@ -12,48 +11,39 @@ require ( github.com/gobuffalo/mw-forcessl v1.0.2 github.com/gobuffalo/mw-i18n/v2 v2.0.3 github.com/gobuffalo/mw-paramlogger v1.0.2 - github.com/gobuffalo/nulls v0.4.2 github.com/gobuffalo/pop/v6 v6.1.1 - github.com/gobuffalo/suite/v4 v4.0.4 - github.com/gobuffalo/validate v2.0.4+incompatible github.com/gobuffalo/validate/v3 v3.3.3 github.com/gobuffalo/x v0.0.0-20190224155809-6bb134105960 github.com/gofrs/uuid v4.4.0+incompatible - github.com/golang-jwt/jwt/v4 v4.5.0 - github.com/mitchellh/mapstructure v1.5.0 - github.com/pkg/errors v0.9.1 - github.com/swaggo/swag v1.16.1 + github.com/golang-jwt/jwt v3.2.2+incompatible + github.com/lestrrat-go/jwx v1.2.29 + github.com/opentracing/opentracing-go v1.2.0 github.com/unrolled/secure v1.14.0 - golang.org/x/crypto v0.11.0 ) require ( github.com/BurntSushi/toml v1.3.2 // indirect - github.com/KyleBanks/depth v1.2.1 // indirect github.com/Masterminds/semver/v3 v3.2.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/fatih/color v1.15.0 // indirect github.com/fatih/structs v1.1.0 // indirect github.com/felixge/httpsnoop v1.0.3 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/go-openapi/jsonpointer v0.19.6 // indirect - github.com/go-openapi/jsonreference v0.20.2 // indirect - github.com/go-openapi/spec v0.20.9 // indirect - github.com/go-openapi/swag v0.22.4 // indirect github.com/go-sql-driver/mysql v1.7.1 // indirect github.com/gobuffalo/events v1.4.3 // indirect github.com/gobuffalo/fizz v1.14.4 // indirect github.com/gobuffalo/flect v1.0.2 // indirect github.com/gobuffalo/github_flavored_markdown v1.1.4 // indirect github.com/gobuffalo/helpers v0.6.7 // indirect - github.com/gobuffalo/httptest v1.5.2 // indirect github.com/gobuffalo/logger v1.0.7 // indirect github.com/gobuffalo/meta v0.3.3 // indirect - github.com/gobuffalo/middleware v1.0.0 // indirect + github.com/gobuffalo/nulls v0.4.2 // indirect github.com/gobuffalo/plush/v4 v4.1.18 // indirect github.com/gobuffalo/refresh v1.13.3 // indirect github.com/gobuffalo/tags/v3 v3.1.4 // indirect + github.com/goccy/go-json v0.10.3 // indirect github.com/gorilla/css v1.0.0 // indirect github.com/gorilla/handlers v1.5.1 // indirect github.com/gorilla/mux v1.8.0 // indirect @@ -70,11 +60,14 @@ require ( github.com/jackc/pgx/v4 v4.18.1 // indirect github.com/jmoiron/sqlx v1.3.5 // indirect github.com/joho/godotenv v1.5.1 // indirect - github.com/josharian/intern v1.0.0 // indirect github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect github.com/kr/pretty v0.3.0 // indirect + github.com/lestrrat-go/backoff/v2 v2.0.8 // indirect + github.com/lestrrat-go/blackmagic v1.0.2 // indirect + github.com/lestrrat-go/httpcc v1.0.1 // indirect + github.com/lestrrat-go/iter v1.0.2 // indirect + github.com/lestrrat-go/option v1.0.1 // indirect github.com/luna-duclos/instrumentedsql v1.1.3 // indirect - github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.19 // indirect github.com/mattn/go-sqlite3 v2.0.3+incompatible // indirect @@ -83,23 +76,22 @@ require ( github.com/monoculum/formam v3.5.5+incompatible // indirect github.com/nicksnyder/go-i18n v1.10.1 // indirect github.com/pelletier/go-toml v1.9.5 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/pkg/errors v0.9.1 // indirect github.com/rogpeppe/go-internal v1.11.0 // indirect - github.com/serenize/snaker v0.0.0-20171204205717-a683aaf2d516 // indirect github.com/sergi/go-diff v1.3.1 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d // indirect github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e // indirect github.com/spf13/cobra v1.7.0 // indirect github.com/spf13/pflag v1.0.5 // indirect - github.com/stretchr/testify v1.8.2 // indirect - golang.org/x/mod v0.12.0 // indirect - golang.org/x/net v0.12.0 // indirect - golang.org/x/sync v0.3.0 // indirect - golang.org/x/sys v0.10.0 // indirect - golang.org/x/term v0.10.0 // indirect - golang.org/x/text v0.11.0 // indirect - golang.org/x/tools v0.11.0 // indirect + golang.org/x/crypto v0.24.0 // indirect + golang.org/x/mod v0.17.0 // indirect + golang.org/x/net v0.26.0 // indirect + golang.org/x/sync v0.7.0 // indirect + golang.org/x/sys v0.21.0 // indirect + golang.org/x/term v0.21.0 // indirect + golang.org/x/text v0.16.0 // indirect + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/mc_web_console_api/go.sum b/mc_web_console_api/go.sum index d65d112c..f7b6875a 100644 --- a/mc_web_console_api/go.sum +++ b/mc_web_console_api/go.sum @@ -3,8 +3,6 @@ github.com/BurntSushi/toml v1.2.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbi github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8= github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= -github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= -github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= github.com/Masterminds/semver v1.4.2/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= github.com/Masterminds/semver/v3 v3.2.1 h1:RN9w6+7QoMeJVGyfmbcgs28Br8cvmnucEXnY0rYXWg0= @@ -26,6 +24,10 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/decred/dcrd/crypto/blake256 v1.0.1/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 h1:rpfIENRNNilwHwZeG5+P150SMrnNEcHYvcCuK6dPZSg= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dustin/go-humanize v0.0.0-20180713052910-9f541cc9db5d/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= @@ -46,20 +48,6 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= -github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE= -github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= -github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo= -github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE= -github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= -github.com/go-openapi/spec v0.20.9 h1:xnlYNQAwKd2VQRRfwTEI0DcK+2cbuvI/0c7jx3gA8/8= -github.com/go-openapi/spec v0.20.9/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= -github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= -github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= -github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= -github.com/go-openapi/swag v0.22.4 h1:QLMzNJnMGPRNDCbySlcj1x01tzU8/9LTTL9hZZZogBU= -github.com/go-openapi/swag v0.22.4/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= @@ -160,8 +148,6 @@ github.com/gobuffalo/meta v0.0.0-20181018192820-8c6cef77dab3/go.mod h1:E94EPzx9N github.com/gobuffalo/meta v0.0.0-20181025145500-3a985a084b0a/go.mod h1:YDAKBud2FP7NZdruCSlmTmDOZbVSa6bpK7LJ/A/nlKg= github.com/gobuffalo/meta v0.3.3 h1:GwPWdbdnp4JrKASvMLa03OtmzISq7z/nE7T6aMqzoYM= github.com/gobuffalo/meta v0.3.3/go.mod h1:o4B099IUFUfK4555Guqxz1zHAqyuUQ/KtHXi8WvVeFE= -github.com/gobuffalo/middleware v1.0.0 h1:7k3jWjdit45aK5Ri9DAKBKAp1QL3bXe2PCtWBBomMww= -github.com/gobuffalo/middleware v1.0.0/go.mod h1:ubE1XogeGL39dXeS0PEKLeEAdFcGXRMMwTW3RGXK/b4= github.com/gobuffalo/mw-basicauth v1.0.3/go.mod h1:dg7+ilMZOKnQFHDefUzUHufNyTswVUviCBgF244C1+0= github.com/gobuffalo/mw-basicauth v1.0.6/go.mod h1:RFyeGeDLZlVgp/eBflqu2eavFqyv0j0fVVP87WPYFwY= github.com/gobuffalo/mw-basicauth v1.0.7/go.mod h1:xJ9/OSiOWl+kZkjaSun62srODr3Cx8OB4AKr+G4FlS4= @@ -219,8 +205,6 @@ github.com/gobuffalo/release v1.0.52/go.mod h1:RPs7EtafH4oylgetOJpGP0yCZZUiO4vqH github.com/gobuffalo/release v1.0.53/go.mod h1:FdF257nd8rqhNaqtDWFGhxdJ/Ig4J7VcS3KL7n/a+aA= github.com/gobuffalo/release v1.0.54/go.mod h1:Pe5/RxRa/BE8whDpGfRqSI7D1a0evGK1T4JDm339tJc= github.com/gobuffalo/shoulders v1.0.1/go.mod h1:V33CcVmaQ4gRUmHKwq1fiTXuf8Gp/qjQBUL5tHPmvbA= -github.com/gobuffalo/suite/v4 v4.0.4 h1:q5Tnn1sv5N7jWufkq51RtUcsvWz4zDtAl/0uu3F23nE= -github.com/gobuffalo/suite/v4 v4.0.4/go.mod h1:bASFS5vBqxzFX947kyUmct4bqRgaOuFXs34GUs/LGDA= github.com/gobuffalo/tags v2.0.11+incompatible/go.mod h1:9XmhOkyaB7UzvuY4UoZO4s67q8/xRMVJEaakauVQYeY= github.com/gobuffalo/tags/v3 v3.1.4 h1:X/ydLLPhgXV4h04Hp2xlbI2oc5MDaa7eub6zw8oHjsM= github.com/gobuffalo/tags/v3 v3.1.4/go.mod h1:ArRNo3ErlHO8BtdA0REaZxijuWnWzF6PUXngmMXd2I0= @@ -228,8 +212,6 @@ github.com/gobuffalo/uuid v2.0.3+incompatible/go.mod h1:ErhIzkRhm0FtRuiE/PeORqcw github.com/gobuffalo/uuid v2.0.4+incompatible/go.mod h1:ErhIzkRhm0FtRuiE/PeORqcw4cVi1RtSpnwYrxuvkfE= github.com/gobuffalo/uuid v2.0.5+incompatible/go.mod h1:ErhIzkRhm0FtRuiE/PeORqcw4cVi1RtSpnwYrxuvkfE= github.com/gobuffalo/validate v2.0.3+incompatible/go.mod h1:N+EtDe0J8252BgfzQUChBgfd6L93m9weay53EWFVsMM= -github.com/gobuffalo/validate v2.0.4+incompatible h1:ZTxozrIw8qQ5nfhShmc4izjYPTsPhfdXTdhXOd5OS9o= -github.com/gobuffalo/validate v2.0.4+incompatible/go.mod h1:N+EtDe0J8252BgfzQUChBgfd6L93m9weay53EWFVsMM= github.com/gobuffalo/validate/v3 v3.3.3 h1:o7wkIGSvZBYBd6ChQoLxkz2y1pfmhbI4jNJYh6PuNJ4= github.com/gobuffalo/validate/v3 v3.3.3/go.mod h1:YC7FsbJ/9hW/VjQdmXPvFqvRis4vrRYFxr69WiNZw6g= github.com/gobuffalo/x v0.0.0-20181003152136-452098b06085/go.mod h1:WevpGD+5YOreDJznWevcn8NTmQEW5STSBgIkpkjzqXc= @@ -238,14 +220,17 @@ github.com/gobuffalo/x v0.0.0-20181025165825-f204f550da9d/go.mod h1:Qh2Pb/Ak1Ko2 github.com/gobuffalo/x v0.0.0-20181025192250-1ef645d63fe8/go.mod h1:AIlnMGlYXOCsoCntLPFLYtrJNS/pc2HD4IdSXH62TpU= github.com/gobuffalo/x v0.0.0-20190224155809-6bb134105960 h1:DoUD23uwnzKJ3t5HH2SeTIszWmc13AV9TAdMhtXQts8= github.com/gobuffalo/x v0.0.0-20190224155809-6bb134105960/go.mod h1:ig5vdn4+5IPtxgESlZWo1SSDyHKKef8EjVVKhY9kkIQ= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA= +github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/gofrs/uuid v3.1.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gofrs/uuid v4.3.1+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA= github.com/gofrs/uuid v4.4.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= -github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= -github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= +github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= @@ -266,7 +251,6 @@ github.com/gorilla/sessions v1.1.3/go.mod h1:8KCfur6+4Mqcc6S0FEfKuN15Vl5MgXW92AE github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI= github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= @@ -335,8 +319,6 @@ github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqx github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= -github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= -github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/karrick/godirwalk v1.7.5/go.mod h1:2c9FRhkDxdIbgkOnCEvnSWs71Bhugbl46shStcFDJ34= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= @@ -354,6 +336,19 @@ github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/lestrrat-go/backoff/v2 v2.0.8 h1:oNb5E5isby2kiro9AgdHLv5N5tint1AnDVVf2E2un5A= +github.com/lestrrat-go/backoff/v2 v2.0.8/go.mod h1:rHP/q/r9aT27n24JQLa7JhSQZCKBBOiM/uP402WwN8Y= +github.com/lestrrat-go/blackmagic v1.0.2 h1:Cg2gVSc9h7sz9NOByczrbUvLopQmXrfFx//N+AkAr5k= +github.com/lestrrat-go/blackmagic v1.0.2/go.mod h1:UrEqBzIR2U6CnzVyUtfM6oZNMt/7O7Vohk2J0OGSAtU= +github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE= +github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E= +github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI= +github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4= +github.com/lestrrat-go/jwx v1.2.29 h1:QT0utmUJ4/12rmsVQrJ3u55bycPkKqGYuGT4tyRhxSQ= +github.com/lestrrat-go/jwx v1.2.29/go.mod h1:hU8k2l6WF0ncx20uQdOmik/Gjg6E3/wIRtXSNFeZuB8= +github.com/lestrrat-go/option v1.0.0/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= +github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU= +github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= @@ -363,11 +358,6 @@ github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/luna-duclos/instrumentedsql v1.1.3 h1:t7mvC0z1jUt5A0UQ6I/0H31ryymuQRnJcWCiqV3lSAA= github.com/luna-duclos/instrumentedsql v1.1.3/go.mod h1:9J1njvFds+zN7y85EDhN9XNQLANWwZt2ULeIC8yMNYs= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= -github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= -github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= -github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/markbates/deplist v1.0.4/go.mod h1:gRRbPbbuA8TmMiRvaOzUlRfzfjeCCBqX2A6arxN01MM= github.com/markbates/deplist v1.0.5/go.mod h1:gRRbPbbuA8TmMiRvaOzUlRfzfjeCCBqX2A6arxN01MM= github.com/markbates/going v1.0.2/go.mod h1:UWCk3zm0UKefHZ7l8BNqi26UyiEMniznk8naLdTcy6c= @@ -419,20 +409,17 @@ github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.0.0/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= -github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/monoculum/formam v0.0.0-20180901015400-4e68be1d79ba/go.mod h1:RKgILGEJq24YyJ2ban8EO0RUVSJlF1pGsEvoLEACr/Q= github.com/monoculum/formam v3.5.5+incompatible h1:iPl5csfEN96G2N2mGu8V/ZB62XLf9ySTpC8KRH6qXec= github.com/monoculum/formam v3.5.5+incompatible/go.mod h1:RKgILGEJq24YyJ2ban8EO0RUVSJlF1pGsEvoLEACr/Q= github.com/nicksnyder/go-i18n v1.10.0/go.mod h1:HrK7VCrbOvQoUAQ7Vpy7i87N7JZZZ7R2xBGjv0j365Q= github.com/nicksnyder/go-i18n v1.10.1 h1:isfg77E/aCD7+0lD/D00ebR2MV5vgeQ276WYyDaCRQc= github.com/nicksnyder/go-i18n v1.10.1/go.mod h1:e4Di5xjP9oTVrC6y3C7C0HoSYXjSbhh/dU0eUV32nB4= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/onsi/ginkgo v1.6.0 h1:Ix8l273rp3QzYgXSR+c8d1fTG7UPgYkOSELPhiY/YGw= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= -github.com/onsi/gomega v1.4.2 h1:3mYCb7aPxS/RU7TI1y4rkEn1oKmPRjNJLNEXgw7MH2I= github.com/onsi/gomega v1.4.2/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= @@ -456,7 +443,6 @@ github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OK github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= -github.com/serenize/snaker v0.0.0-20171204205717-a683aaf2d516 h1:ofR1ZdrNSkiWcMsRrubK9tb2/SlZVWttAfqUjJi6QYc= github.com/serenize/snaker v0.0.0-20171204205717-a683aaf2d516/go.mod h1:Yow6lPLSAXx2ifx470yD/nUe22Dv5vBvxK/UK9UUTVs= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= @@ -503,6 +489,7 @@ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -512,10 +499,9 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= -github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/swaggo/swag v1.16.1 h1:fTNRhKstPKxcnoKsytm4sahr8FaYzUcT7i1/3nd/fBg= -github.com/swaggo/swag v1.16.1/go.mod h1:9/LMvHycG3NFHfR6LwvikHv5iFvmPADQ359cKikGxto= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/unrolled/secure v0.0.0-20180918153822-f340ee86eb8b/go.mod h1:mnPT77IAdsi/kV7+Es7y+pXALeV3h7G6dQF6mNYjcLA= github.com/unrolled/secure v0.0.0-20181005190816-ff9db2ff917f/go.mod h1:mnPT77IAdsi/kV7+Es7y+pXALeV3h7G6dQF6mNYjcLA= github.com/unrolled/secure v0.0.0-20181022170031-4b6b7cf51606/go.mod h1:mnPT77IAdsi/kV7+Es7y+pXALeV3h7G6dQF6mNYjcLA= @@ -556,14 +542,17 @@ golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= -golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= -golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= +golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI= +golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= -golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180816102801-aaf60122140d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -585,15 +574,17 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.0.0-20220826154423-83b083e8dc8b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.0.0-20221002022538-bcab6841153b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50= -golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ= +golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220929204114-8fcdb60fdcc0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= -golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180816055513-1c9583448a9c/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180906133057-8cf3aee42992/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -630,15 +621,21 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= -golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws= +golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20220722155259-a9ba230a4035/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.10.0 h1:3R7pNqamzBraeqj/Tj8qt1aQ2HpmlC+Cx/qL/7hn4/c= -golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= +golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58= +golang.org/x/term v0.21.0 h1:WVXCp+/EBEHOj53Rvu+7KiT/iElMrO8ACK16SMZ3jaA= +golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -647,8 +644,10 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= -golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= +golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181003024731-2f84ea8ef872/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181006002542-f60d9635b16a/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -669,8 +668,7 @@ golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.11.0 h1:EMCa6U9S2LtZXLAMoWiR/R8dAQFRqbAitmbJ2UKhoi8= -golang.org/x/tools v0.11.0/go.mod h1:anzJrxPjNtfgiYQYirP2CPGzGLxrH2u2QBhn6Bf3qY8= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -683,17 +681,14 @@ gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKWaSkCsqBpgog8nAV2xsGOxlo= gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw= gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s= gopkg.in/mail.v2 v2.0.0-20180731213649-a0242b2233b4/go.mod h1:htwXN1Qh09vZJ1NVKxQqHPBaCBbzKhp5GzuJEA4VJWw= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -701,7 +696,6 @@ gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= diff --git a/mc_web_console_api/handler/AdminHandler.go b/mc_web_console_api/handler/AdminHandler.go deleted file mode 100644 index a7440571..00000000 --- a/mc_web_console_api/handler/AdminHandler.go +++ /dev/null @@ -1,346 +0,0 @@ -package handler - -import ( - "log" - fwmodels "mc_web_console_api/fwmodels" - "mc_web_console_api/models" - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - //tbnetutil "mc_web_console_api/fwmodels/tumblebug/netutil" - - util "mc_web_console_api/util" - - "net/http" - "fmt" - "strings" - "encoding/json" - "io" - - "github.com/gobuffalo/buffalo" - "github.com/gobuffalo/pop/v6" - "github.com/gofrs/uuid" -) - -// 관리를 위한 handler -// 메뉴, 공통코드, region 등... -// TODO: commonHandler와 합쳐야 하나? - -func RegionGroupList(paramRegionGroup models.RegionGroup) (models.RegionGroups, fwmodels.WebStatus) { - regionGroupList := []models.RegionGroup{} - //err := models.DB.All(®ionGroupList) - //query := models.DB.Q() - - regionGroupList, err := models.RegionGroupList(paramRegionGroup) - if err != nil { - log.Println("RegionGroupList err ", err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - //query := models.DB.Q() - - // if providerId != "" { - // query = query.Where("provider_id = ?", providerId) - // } - // if regionGroupName != "" { - // query = query.Where("region_group_name = ?", regionGroupName) - // } - //err := query.All(®ionGroupList) - // //err := query.All(®ionGroupList) - //if err != nil { - // log.Println("regionGroupList err", err) - // //return errors.WithStack(err) - // return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - //} - log.Println("regionGroupList", regionGroupList) - return regionGroupList, fwmodels.WebStatus{StatusCode: 200} -} - -// regionList 조건에 ID를 넣으면 1개만 조회 됨. -func GetRegionGroup(paramRegionGroup models.RegionGroup) (models.RegionGroup, fwmodels.WebStatus) { - - returnRegionGroup := models.RegionGroup{} - - //regionGroupList, respStatus := RegionGroupList(paramRegionGroup) - regionGroupList, err := models.RegionGroupList(paramRegionGroup) - if err != nil { - log.Println("GetRegionGroup err ", err) - return returnRegionGroup, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - log.Println("GetRegionGroup 1 length = ", len(regionGroupList)) - if len(regionGroupList) > 1 { - return returnRegionGroup, fwmodels.WebStatus{StatusCode: 500, Message: "more than one result value"} - } - log.Println("GetRegionGroup 2") - if len(regionGroupList) < 1 { - return returnRegionGroup, fwmodels.WebStatus{StatusCode: 500, Message: "no results"} - } - log.Println("GetRegionGroup 3") - returnRegionGroup = regionGroupList[0] // 1개만 있어야 함. - return returnRegionGroup, fwmodels.WebStatus{StatusCode: 200} - - // regionGroup := models.RegionGroup{} - // valueCount := 0 - // query := models.DB.Q() - // if regionGroupId != "" { - // query = query.Where("id = ?", regionGroupId) - // valueCount++ - // } - // if providerId != "" { - // query = query.Where("provider_id = ? ", providerId) - // valueCount++ - // } - // if regionGroupName != "" { - // query = query.Where("region_group_name = ? ", regionGroupName) - // valueCount++ - // } - - // if valueCount == 0 { - // errMsg := "There are no search conditions" - // return regionGroup, fwmodels.WebStatus{StatusCode: 500, Message: errMsg} - // } - // err := query.First(®ionGroup) - - // if err != nil { - // return regionGroup, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - // } - // return regionGroup, fwmodels.WebStatus{StatusCode: 200} -} - -func SaveRegionGroup(regionGroup *models.RegionGroup, c buffalo.Context) (models.RegionGroup, fwmodels.WebStatus) { - //regionGroup := &models.RegionGroup{} - - tx := c.Value("tx").(*pop.Connection) - - vErrors, err := regionGroup.Create(tx) - if vErrors.HasAny() { - log.Println("Reg RegionGroup vErrors", vErrors.Error()) - return *regionGroup, fwmodels.WebStatus{StatusCode: 500, Message: vErrors.Error()} - } - if err != nil { - log.Println("Reg RegionGroup err", err) - return *regionGroup, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - return *regionGroup, fwmodels.WebStatus{StatusCode: 200} -} - -func DeleteRegionGroup(regionGroup *models.RegionGroup, c buffalo.Context) (models.RegionGroup, fwmodels.WebStatus) { - - tx := c.Value("tx").(*pop.Connection) - - err := regionGroup.Destroy(tx) - if err != nil { - log.Println("Del RegionGroup err", err) - return *regionGroup, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - return *regionGroup, fwmodels.WebStatus{StatusCode: 200} -} - -// 메뉴 Tree 조회 -// category, menu구조를 tree형태로 쿼리 -func MenuTree() (*models.MenuTree, fwmodels.WebStatus) { - menuTrees := &models.MenuTree{} - - db := models.DB - - sb := strings.Builder{} - - sb.WriteString(" with recursive category_tree (category_id, category_name, parent_category_id, level, lp, sort, use_yn) as ( ") - //-- 최상위 category - sb.WriteString(" select id as category_id, category_name, parent_category_id, 0 as level, cast(id as varchar) as lp, sort, use_yn ") - sb.WriteString(" from categories ") - sb.WriteString(" where parent_category_id = '-' ") - sb.WriteString(" union all ") - sb.WriteString(" select c.id as category_id, c.category_name, c.parent_category_id, ct.level +1 as level, ct.lp || ',' || ct.category_id, c.sort, c.use_yn ") - sb.WriteString(" from categories c ") - sb.WriteString(" inner join category_tree ct on c.parent_category_id = ct.category_id ") - sb.WriteString(" ) ") - sb.WriteString(" select ct.category_id, ct.category_name, ct.parent_category_id, ct.level, ct.lp ") - sb.WriteString(" , COALESCE(mn.id, '-') as id, COALESCE(mn.name, '-') as name, COALESCE(COALESCE(mn.alias, mn.name), '-') as alias, COALESCE(mn.visible, true) as visible ") - sb.WriteString(" , ct.sort as category_sort, COALESCE(mn.sort, -1) as menu_sort, ct.use_yn ") - sb.WriteString(" from category_tree ct ") - sb.WriteString(" left join menus mn ") - sb.WriteString(" on ct.category_id = mn.category_id ") - sb.WriteString(" where ct.use_yn = true ") - sb.WriteString(" order by category_sort, menu_sort ") - - q := db.RawQuery(sb.String()) - err := q.All(menuTrees) - if err != nil { - log.Println("menu err", err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - log.Println("menuTrees", menuTrees) - return menuTrees, fwmodels.WebStatus{StatusCode: 200} -} - -// 임시 User 조회 -func GetUserById(userId uuid.UUID) (*models.User, fwmodels.WebStatus) { - user := &models.User{} - //query := models.DB.Q() - //err := query.Find(user, userId) - err := models.DB.Find(user, userId) - if err != nil { - return user, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - log.Println("user", user) - return user, fwmodels.WebStatus{StatusCode: 200} -} - - -/////////// CB-TB Admin 기능 start ///// - -///requests Get all requests -func GetAllRequestsTB(status string, method string, callUrl string, time string, savefile string) (tbcommon.TbRequestDetails, fwmodels.WebStatus) { - var originalUrl = "/requests" - - var paramMapper = make(map[string]string) - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - urlParam += "?status=" - if status != ""{// Handling, Error, Success - urlParam += "" + status - } - if method != ""{// GET, POST, etc - urlParam += "&method=" + method - } - if callUrl != ""{// request URL - urlParam += "&url=" + callUrl - } - if time != ""{// GET, POST, etc - urlParam += "&time=" + time - } - if savefile != ""{// GET, POST, etc - urlParam += "&savefile=" + savefile - } - - url := util.TUMBLEBUG + urlParam - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - requestDetails := tbcommon.TbRequestDetails{} - if err != nil { - fmt.Println(err) - return requestDetails, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return requestDetails, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&requestDetails) - - fmt.Println(requestDetails) - - return requestDetails, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Get details of a specific request -func GetRequestByIdTB(reqId string) (tbcommon.TbRequestDetails, fwmodels.WebStatus) { - var originalUrl = "/request/{reqId}" - - var paramMapper = make(map[string]string) - paramMapper["{reqId}"] = reqId - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - requestDetail := tbcommon.TbRequestDetails{} - if reqId == "" { - return requestDetail, fwmodels.WebStatus{StatusCode: 500, Message: "req ID is required"} - } - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - - - if err != nil { - fmt.Println(err) - return requestDetail, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return requestDetail, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&requestDetail) - //spew.Dump(body) - fmt.Println(requestDetail) - - return requestDetail, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Delete all requests' details -func DeleteAllRequestsTB() (io.ReadCloser, fwmodels.WebStatus) { - var originalUrl = "/requests" - - var paramMapper = make(map[string]string) - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("DeleteAllRequestsTB ", failResultInfo) - return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Delete a specific request's details -func DeleteRequestByIdTB(reqId string) (io.ReadCloser, fwmodels.WebStatus) { - var originalUrl = "/request/{reqId}" - - var paramMapper = make(map[string]string) - paramMapper["{reqId}"] = reqId - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - if reqId == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "req ID is required"} - } - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("DelNLB ", failResultInfo) - return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -/////////// CB-TB Admin 기능 end ///// \ No newline at end of file diff --git a/mc_web_console_api/handler/CloudConnectionHandler.go b/mc_web_console_api/handler/CloudConnectionHandler.go deleted file mode 100644 index eca3743d..00000000 --- a/mc_web_console_api/handler/CloudConnectionHandler.go +++ /dev/null @@ -1,2655 +0,0 @@ -package handler - -import ( - "encoding/json" - "fmt" - "io" - "log" - "strings" - - // "strings" - "bytes" - - // "math" - "net/http" - // "strconv" - // "sync" - //"io/ioutil" - //"github.com/davecgh/go-spew/spew" - - // spider "mc_web_console_api/fwmodels/spider" - - fwmodels "mc_web_console_api/fwmodels" - "mc_web_console_api/fwmodels/spider" - "mc_web_console_api/models" - "mc_web_console_api/models/views" - - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - - util "mc_web_console_api/util" - - "github.com/davecgh/go-spew/spew" - "github.com/gobuffalo/buffalo" - "github.com/gobuffalo/pop/v6" - "github.com/gofrs/uuid" - "github.com/pkg/errors" -) - -// 목록 : ListData -// 1개 : Data -// 등록 : Reg -// 삭제 : Del - -// Cloud Provider 목록 -type GVC struct { - VC views.ViewCloudConnection -} - -// Get Framework Health : spider를 호출하여 결과가 있으면 OK -func GetSpiderHealthCheck() fwmodels.WebStatus { - _, respStatus := GetCloudOSList() - - return respStatus -} - -// Get Framework Health -func GetTumblebugHealthCheck() fwmodels.WebStatus { - var originalUrl = "/health" - urlParam := util.MappingUrlParameter(originalUrl, nil) - url := util.TUMBLEBUG + urlParam - - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - if err != nil { - fmt.Println(err) - return fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - log.Println(respBody) - - return fwmodels.WebStatus{StatusCode: respStatus} -} - -// Get Framework Health -func GetDragonflyHealthCheck() fwmodels.WebStatus { - var originalUrl = "/healthcheck" - urlParam := util.MappingUrlParameter(originalUrl, nil) - url := util.DRAGONFLY + urlParam - - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - if err != nil { - fmt.Println(err) - return fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - log.Println(respBody) - - return fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetCloudOSList() ([]string, fwmodels.WebStatus) { - - var originalUrl = "/cloudos" - urlParam := util.MappingUrlParameter(originalUrl, nil) - url := util.SPIDER + urlParam - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // defer resp.Close() - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - cloudOs := map[string][]string{} - json.NewDecoder(respBody).Decode(&cloudOs) - fmt.Println(cloudOs["cloudos"]) - - return cloudOs["cloudos"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// provider 별 connection count, connection 있는 provider 수 -func GetCloudConnectionCountMap(cloudConnectionConfigInfoList []spider.CloudConnectionConfigInfo) (map[string]int, int) { - connectionConfigCountMap := make(map[string]int) - for _, connectionInfo := range cloudConnectionConfigInfoList { - count := 0 - val, exists := connectionConfigCountMap[util.GetProviderName(connectionInfo.ProviderName)] - if !exists { - count = 1 - } else { - count = val + 1 - } - connectionConfigCountMap[util.GetProviderName(connectionInfo.ProviderName)] = count - } - - providerCount := 0 - for i, _ := range connectionConfigCountMap { - if i == "" { - } - providerCount++ - } - return connectionConfigCountMap, providerCount -} - -// 현재 설정된 connection 목록 GetConnectionConfigListData -> GetCloudConnectionConfigList로 변경 -func GetCloudConnectionConfigList() ([]spider.CloudConnectionConfigInfo, fwmodels.WebStatus) { - var originalUrl = "/connectionconfig" - urlParam := util.MappingUrlParameter(originalUrl, nil) - url := util.SPIDER + urlParam - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // defer body.Close() - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - cloudConnectionConfigInfo := map[string][]spider.CloudConnectionConfigInfo{} - json.NewDecoder(respBody).Decode(&cloudConnectionConfigInfo) - fmt.Println(cloudConnectionConfigInfo["connectionconfig"]) - - return cloudConnectionConfigInfo["connectionconfig"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// Connection 상세 -func GetCloudConnectionConfigData(configName string) (spider.CloudConnectionConfigInfo, fwmodels.WebStatus) { - var originalUrl = "/connectionconfig/{{config_name}}" - - var paramMapper = make(map[string]string) - paramMapper["{{config_name}}"] = configName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.SPIDER + urlParam - - // url := util.SPIDER + "/connectionconfig/" + configName - fmt.Println("=========== GetCloudConnectionConfigData : ", configName) - cloudConnectionConfigInfo := spider.CloudConnectionConfigInfo{} - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // defer body.Close() - - if err != nil { - fmt.Println(err) - return cloudConnectionConfigInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&cloudConnectionConfigInfo) - fmt.Println(cloudConnectionConfigInfo) - return cloudConnectionConfigInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// CloudConnectionConfigInfo 등록 -// func RegCloudConnectionConfig(cloudConnectionConfigInfo *fwmodels.CloudConnectionConfigInfo) (io.ReadCloser, fwmodels.WebStatus) { -func RegCloudConnectionConfig(cloudConnectionConfigInfo *spider.CloudConnectionConfigInfo) (*spider.CloudConnectionConfigInfo, fwmodels.WebStatus) { - var originalUrl = "/connectionconfig" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.SPIDER + urlParam - // buff := bytes.NewBuffer(pbytes) - // url := util.SPIDER + "/connectionconfig" - - fmt.Println("cloudConnectionConfigInfo : ", cloudConnectionConfigInfo) - - // body, err := util.CommonHttpPost(url, regionInfo) - pbytes, _ := json.Marshal(cloudConnectionConfigInfo) - // body, err := util.CommonHttpPost(url, pbytes) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - // if err != nil { - // fmt.Println(err) - // return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - // } - - // respBody := resp.Body - // respStatus := resp.StatusCode - //cloudConnectionConfigInfo - // return respBody, fwmodels.WebStatus{StatusCode: respStatus} - - returnCloudConnectionConfigInfo := spider.CloudConnectionConfigInfo{} - if err != nil { - fmt.Println(err) - return &returnCloudConnectionConfigInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - returnStatus := fwmodels.WebStatus{} - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnCloudConnectionConfigInfo) - fmt.Println(returnCloudConnectionConfigInfo) - } - returnStatus.StatusCode = respStatus - - return &returnCloudConnectionConfigInfo, returnStatus -} - -// CloudConnectionConfigInfo 삭제 -func DelCloudConnectionConfig(configName string) (io.ReadCloser, fwmodels.WebStatus) { - var originalUrl = "/connectionconfig/{{config_name}}" - - var paramMapper = make(map[string]string) - paramMapper["{{config_name}}"] = configName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.SPIDER + urlParam - - // buff := bytes.NewBuffer(pbytes) - // url := util.SPIDER + "/connectionconfig/" + configName - - fmt.Println("DelCloudConnectionConfig : ", configName) - - // body, err := util.CommonHttpPost(url, regionInfo) - - pbytes, _ := json.Marshal(configName) - // body, err := util.CommonHttpDelete(url, pbytes) - resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - - if err != nil { - log.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - - return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 현재 설정된 region 목록 -func GetRegionList() ([]spider.RegionInfo, fwmodels.WebStatus) { - var originalUrl = "/region" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.SPIDER + urlParam - - // url := util.SPIDER + "/region" - // fmt.Println("=========== GetRegionListData : ", url) - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // defer body.Close() - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - regionList := map[string][]spider.RegionInfo{} - json.NewDecoder(respBody).Decode(®ionList) - //fmt.Println(regionList["region"]) - - return regionList["region"], fwmodels.WebStatus{StatusCode: respStatus} -} - -func MconRegionList(region *models.Region, c buffalo.Context) ([]models.Region, error) { - regions := []models.Region{} - - // query := models.DB.Q() - // // if region.ID.String() != "" { - // // query = query.Where("id = ", region.ID) - // // } - // if region.ProviderID != "" { - // query = query.Where("provider_id = ? ", region.ProviderID) - // } - // err := query.All(®ions) - // // err := query.All(®ions) - - tx := c.Value("tx").(*pop.Connection) - // err := tx.Eager().All(®ions) - query := tx.Eager().Q() - - query.Where("provider_id = ? ", region.ProviderID) - - err := query.All(®ions) - if err != nil { - log.Println("mconRegionList err ", err) - return regions, err - } - - return regions, nil -} - -func GetRegionData(regionName string) (*tbcommon.TbRegion, fwmodels.WebStatus) { - var originalUrl = "/region/{regionName}" - - var paramMapper = make(map[string]string) - paramMapper["{regionName}"] = regionName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.SPIDER + urlParam - - // url := util.SPIDER + "/region/" + regionName - fmt.Println("=========== GetRegionData : ", regionName) - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // defer body.Close() - // regionInfo := spider.RegionInfo{} - regionInfo := tbcommon.TbRegion{} - if err != nil { - fmt.Println(err) - return ®ionInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - // regionList := map[string][]string{} - // // regionList := map[string][]spider.RegionInfo{} - // json.NewDecoder(body).Decode(®ionList) - // fmt.Println(regionList) // map[KeyValueInfoList:[] ProviderName:[] RegionName:[]] - // // fmt.Println(regionList["connectionconfig"]) - - json.NewDecoder(respBody).Decode(®ionInfo) - // fmt.Println(regionInfo) - // fmt.Println(regionInfo.KeyValueInfoList) - return ®ionInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// region 단건 조회 -func MconRegionGet(region *models.Region) (models.Region, error) { - resultRegion := models.Region{} - - // paramRegion := &models.Region{} - // if err := c.Bind(paramRegion); err != nil { - // return resultRegion, err - // } - - //err := models.DB.Find(&resultRegion, region.ID) - //if err != nil { - // return resultRegion, err - //} - - query := models.DB.Q() - if region.ID.String() != "00000000-0000-0000-0000-000000000000" { - query = query.Where(" id = ? ", region.ID) - } - if region.ProviderID != "" { - query = query.Where(" provider_id = ? ", region.ProviderID) - } - if region.RegionName != "" { - query = query.Where(" region_name = ? ", region.RegionName) - } - err := query.First(&resultRegion) - - return resultRegion, err -} - -// Region 등록 -// func RegRegion(regionInfo *spider.RegionInfo) (io.ReadCloser, fwmodels.WebStatus) { -func RegRegion(regionInfo *spider.RegionInfo) (*spider.RegionInfo, fwmodels.WebStatus) { - var originalUrl = "/region" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.SPIDER + urlParam - - // buff := bytes.NewBuffer(pbytes) - // url := util.SPIDER + "/region" - - fmt.Println("RegRegion : ", regionInfo) - - // body, err := util.CommonHttpPost(url, regionInfo) - pbytes, _ := json.Marshal(regionInfo) - // body, err := util.CommonHttpPost(url, pbytes) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - // if err != nil { - // fmt.Println(err) - // return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - // } - - // respBody := resp.Body - // respStatus := resp.StatusCode - - // return respBody, fwmodels.WebStatus{StatusCode: respStatus} - respBody := resp.Body - respStatus := resp.StatusCode - - returnRegionInfo := spider.RegionInfo{} - returnStatus := fwmodels.WebStatus{} - - if err != nil { - fmt.Println(err) - return &returnRegionInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnRegionInfo) - fmt.Println(returnRegionInfo) - } - returnStatus.StatusCode = respStatus - - return &returnRegionInfo, returnStatus -} - -// region 추가 -func MconRegionCreate(region *models.Region, c buffalo.Context) error { - // paramRegion := &models.Region{} - // if err := c.Bind(paramRegion); err != nil { - // return errors.WithStack(err) - // } - - tx := c.Value("tx").(*pop.Connection) - - // validateErr , otherErr - verrs, err := region.Create(tx) - if verrs != nil { - return errors.WithStack(verrs) - } - if err != nil { - return errors.WithStack(err) - } - - return nil -} - -// Region 삭제 -func DelRegion(regionName string) (io.ReadCloser, fwmodels.WebStatus) { - var originalUrl = "/region/{{region_name}}" - - var paramMapper = make(map[string]string) - paramMapper["{{region_name}}"] = regionName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.SPIDER + urlParam - - // buff := bytes.NewBuffer(pbytes) - // url := util.SPIDER + "/region/" + regionName - - fmt.Println("DelRegion : ", regionName) - - // body, err := util.CommonHttpPost(url, regionInfo) - - pbytes, _ := json.Marshal(regionName) - // body, err := util.CommonHttpDelete(url, pbytes) - resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - - return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 현재 설정된 credential 목록 : 목록에서는 key의 value는 ...으로 표시 -func GetCredentialList() ([]spider.CredentialInfo, fwmodels.WebStatus) { - var originalUrl = "/credential" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.SPIDER + urlParam - - // SPIDER == SPIDER - // url := util.SPIDER + "/credential" - // fmt.Println("=========== GetRegionListData : ", url) - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // defer body.Close() - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - credentialList := map[string][]spider.CredentialInfo{} - json.NewDecoder(respBody).Decode(&credentialList) - fmt.Println(credentialList["credential"]) - // TODO : key의 value를 "..."로 대체함. 사용자에게 노출시킬 필요가 있을지... - for _, credentialInfo := range credentialList["credential"] { - fmt.Println("credentialInfo : ", credentialInfo) - keyValueInfoList := credentialInfo.KeyValueInfoList - fmt.Println("before keyValueInfoList : ", keyValueInfoList) - for _, keyValueInfo := range keyValueInfoList { - keyValueInfo.Value = "..." - } - // fmt.Println("after keyValueInfoList : ", keyValueInfoList) - } - - return credentialList["credential"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// credential 목록 조회 -func MconCredentialList(credential *models.Credential, c buffalo.Context) ([]models.Credential, error) { - crendentials := []models.Credential{} - - // paramCredential := &models.Credential{} - // if err := c.Bind(paramCredential); err != nil { - // return errors.WithStack(err) - // } - - // tx := c.Value("tx").(*pop.Connection) - // query := tx.Eager() - // if credential.ID.String() != "" { - // query.Where("id = ", credential.ID) - // } - // if credential.CredentialName != "" { - // query.Where("driver_name = ", credential.CredentialName) - // } - query := models.DB.Q() - if credential.ID.String() != "" { - query = query.Where("id = ", credential.ID) - } - if credential.CredentialName != "" { - query = query.Where("credential_name = ", credential.CredentialName) - } - err := query.All(&crendentials) - if err != nil { - return crendentials, errors.WithStack(err) - } - - return crendentials, nil -} - -// Credential 상세조회 -func GetCredentialData(credentialName string) (*spider.CredentialInfo, fwmodels.WebStatus) { - var originalUrl = "/credential/{{credential_name}}" - - var paramMapper = make(map[string]string) - paramMapper["{{credential_name}}"] = credentialName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.SPIDER + urlParam - - // url := util.SPIDER + "/credential/" + credentialName - fmt.Println("=========== GetCredentialData : ", credentialName) - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // defer body.Close() - credentialInfo := spider.CredentialInfo{} - if err != nil { - fmt.Println(err) - return &credentialInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&credentialInfo) - // fmt.Println(credentialInfo) - // fmt.Println(credentialInfo.KeyValueInfoList) - return &credentialInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// credential 단건 조회 -func MconCredentialGet(credential *models.Credential) (models.Credential, error) { - resultCredential := models.Credential{} - - //err := models.DB.Find(&resultCredential, credential.ID) - //if err != nil { - // return resultCredential, errors.WithStack(err) - //} - - query := models.DB.Q() - if credential.ID.String() != "00000000-0000-0000-0000-000000000000" { - query = query.Where(" id = ? ", credential.ID) - } - if credential.ProviderID != "" { - query = query.Where(" provider_id = ? ", credential.ProviderID) - } - if credential.CredentialName != "" { - query = query.Where(" credential_name = ? ", credential.CredentialName) - } - err := query.First(&resultCredential) - - return resultCredential, err -} - -// Credential 등록 -func RegCredential(credentialInfo *spider.CredentialInfo) (*spider.CredentialInfo, fwmodels.WebStatus) { - var originalUrl = "/credential" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.SPIDER + urlParam - - fmt.Println("RegCredential : ", credentialInfo) - returnCredentialInfo := spider.CredentialInfo{} - returnStatus := fwmodels.WebStatus{} - - // GCP의 경우 value에 \n 이 포함되어 있기 때문에 이것이 넘어올 때는 \\n 형태로 넘어온다. 이것을 \으로 replace 해야 - // - var credentialBuffer bytes.Buffer - if credentialInfo.ProviderName == "GCP" { - - credentialBuffer.WriteString(`{`) - credentialBuffer.WriteString(`"CredentialName":"` + credentialInfo.CredentialName + `"`) - credentialBuffer.WriteString(`,"ProviderName":"` + credentialInfo.ProviderName + `"`) - credentialBuffer.WriteString(`,"KeyValueInfoList":[`) - - for mapIndex, keyValueInfo := range credentialInfo.KeyValueInfoList { - // for mapIndex, _ := range credentialInfo.KeyValueInfoList { - gcpKey := keyValueInfo.Key - gcpValue := keyValueInfo.Value - // replacedValue := gcpValue - if mapIndex > 0 { - credentialBuffer.WriteString(`,`) - } - credentialBuffer.WriteString(`{"Key":"` + gcpKey + `","Value":"` + gcpValue + `"}`) - // if gcpKey == "private_key" { - // // fmt.Println(gcpValue) - // // // fmt.Println(keyValueInfo) - // // fmt.Println("--------- before / after -----------------") - // replacedValue = strings.Replace(gcpValue, "\\n", "\n", -1) - // // replacedValue = strings.Replace(gcpValue, "\n", "\\n", -1) - // // replacedValue = "`" + gcpValue + "`" - // keyValueInfo.Value = replacedValue - // fmt.Println(replacedValue) - // // fmt.Println(keyValueInfo) - - // } - } - // fmt.Println("GCP RegCredential : ", credentialInfo) - - credentialBuffer.WriteString(`]`) - credentialBuffer.WriteString(`}`) - // fmt.Println("******* ") - - // fmt.Println(credentialBuffer.String()) - resp, err := util.CommonHttpBytes(url, &credentialBuffer, http.MethodPost) - - // pbytes, marshalErr := json.Marshal(credentialInfo) - // if marshalErr != nil { - // fmt.Println(" ------------------ ") - // fmt.Println(marshalErr) - // } - // fmt.Println(string(pbytes)) - - // resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - if err != nil { - fmt.Println(err) - return &returnCredentialInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnCredentialInfo) - fmt.Println(returnCredentialInfo) - } - returnStatus.StatusCode = respStatus - } else if credentialInfo.ProviderName == "OPENSTACK" { - - credentialBuffer.WriteString(`{`) - credentialBuffer.WriteString(`"CredentialName":"` + credentialInfo.CredentialName + `"`) - credentialBuffer.WriteString(`,"ProviderName":"` + credentialInfo.ProviderName + `"`) - credentialBuffer.WriteString(`,"KeyValueInfoList":[`) - - for mapIndex, keyValueInfo := range credentialInfo.KeyValueInfoList { - // for mapIndex, _ := range credentialInfo.KeyValueInfoList { - openstackKey := keyValueInfo.Key - openstackValue := keyValueInfo.Value - // replacedValue := gcpValue - if mapIndex > 0 { - credentialBuffer.WriteString(`,`) - } - credentialBuffer.WriteString(`{"Key":"` + openstackKey + `","Value":"` + openstackValue + `"}`) - // if gcpKey == "private_key" { - // // fmt.Println(gcpValue) - // // // fmt.Println(keyValueInfo) - // // fmt.Println("--------- before / after -----------------") - // replacedValue = strings.Replace(gcpValue, "\\n", "\n", -1) - // // replacedValue = strings.Replace(gcpValue, "\n", "\\n", -1) - // // replacedValue = "`" + gcpValue + "`" - // keyValueInfo.Value = replacedValue - // fmt.Println(replacedValue) - // // fmt.Println(keyValueInfo) - - // } - } - // fmt.Println("GCP RegCredential : ", credentialInfo) - - credentialBuffer.WriteString(`]`) - credentialBuffer.WriteString(`}`) - // fmt.Println("******* ") - - // fmt.Println(credentialBuffer.String()) - resp, err := util.CommonHttpBytes(url, &credentialBuffer, http.MethodPost) - - // pbytes, marshalErr := json.Marshal(credentialInfo) - // if marshalErr != nil { - // fmt.Println(" ------------------ ") - // fmt.Println(marshalErr) - // } - // fmt.Println(string(pbytes)) - - // resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - if err != nil { - fmt.Println(err) - return &returnCredentialInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnCredentialInfo) - fmt.Println(returnCredentialInfo) - } - returnStatus.StatusCode = respStatus - } else { - // body, err := util.CommonHttpPost(url, regionInfo) - - pbytes, marshalErr := json.Marshal(credentialInfo) - // pbytes, marshalErr := json.Marshal(credentialInfo) - if marshalErr != nil { - fmt.Println(" ------------------ ") - fmt.Println(marshalErr) - } - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - if err != nil { - fmt.Println(err) - return &returnCredentialInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnCredentialInfo) - fmt.Println(returnCredentialInfo) - } - returnStatus.StatusCode = respStatus - } - - // if err != nil { - // fmt.Println(err) - // return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - // } - - // respBody := resp.Body - // respStatus := resp.StatusCode - - // // util.DisplayResponse(resp) - // return respBody, fwmodels.WebStatus{StatusCode: respStatus} - - // respBody := resp.Body - // respStatus := resp.StatusCode - - // if err != nil { - // fmt.Println(err) - // return &returnCredentialInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - // } - - // if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - // errorInfo := fwmodels.ErrorInfo{} - // json.NewDecoder(respBody).Decode(&errorInfo) - // fmt.Println("respStatus != 200 reason ", errorInfo) - // returnStatus.Message = errorInfo.Message - // } else { - // json.NewDecoder(respBody).Decode(&returnCredentialInfo) - // fmt.Println(returnCredentialInfo) - // } - // returnStatus.StatusCode = respStatus - - return &returnCredentialInfo, returnStatus -} - -// credential 추가 -func MconCredentialCreate(credential *models.Credential, c buffalo.Context) error { - - tx := c.Value("tx").(*pop.Connection) - - // validateErr , otherErr - verrs, err := credential.Create(tx) - if verrs != nil { - return errors.WithStack(verrs) - } - if err != nil { - return errors.WithStack(err) - } - - return nil -} - -// Credential 삭제 -func DelCredential(credentialName string) (fwmodels.WebStatus, fwmodels.WebStatus) { - webStatus := fwmodels.WebStatus{} - - var originalUrl = "/credential/{{credential_name}}" - - var paramMapper = make(map[string]string) - paramMapper["{{credential_name}}"] = credentialName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.SPIDER + urlParam - // buff := bytes.NewBuffer(pbytes) - // url := util.SPIDER + "/credential/" + credentialName - - fmt.Println("DelCredential : ", credentialName) - - pbytes, _ := json.Marshal(credentialName) - // body, err := util.CommonHttpDelete(url, pbytes) - resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - - if err != nil { - fmt.Println(err) - return webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return webStatus, fwmodels.WebStatus{StatusCode: respStatus} - //return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 현재 설정된 Driver 목록 -func GetDriverList() ([]spider.DriverInfo, fwmodels.WebStatus) { - var originalUrl = "/driver" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.SPIDER + urlParam - - // url := util.SPIDER + "/driver" - fmt.Println("=========== GetDriverListData : ", url) - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // defer body.Close() - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - driverList := map[string][]spider.DriverInfo{} - json.NewDecoder(respBody).Decode(&driverList) - fmt.Println(driverList["driver"]) - - return driverList["driver"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// Driver 상세조회 -func SpiderDriverGet(driverlName string) (*spider.DriverInfo, fwmodels.WebStatus) { - var originalUrl = "/driver/{{driver_name}}" - - var paramMapper = make(map[string]string) - paramMapper["{{driver_name}}"] = driverlName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.SPIDER + urlParam - - //url := util.SPIDER + "/driver/" + driverlName - fmt.Println("=========== GetDriverData : ", url) - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // defer body.Close() - driverInfo := spider.DriverInfo{} - if err != nil { - fmt.Println(err) - return &driverInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&driverInfo) - fmt.Println(driverInfo) - return &driverInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// driver 단건 조회 -func MconDriverGet(c buffalo.Context) (models.Driver, error) { - driver := models.Driver{} - - paramDriver := &models.Driver{} - if err := c.Bind(paramDriver); err != nil { - return driver, errors.WithStack(err) - } - - err := models.DB.Find(&driver, paramDriver.ID) - if err != nil { - return driver, errors.WithStack(err) - } - - return driver, nil -} - -// Driver 등록 -func RegDriver(driverInfo *spider.DriverInfo) (*spider.DriverInfo, fwmodels.WebStatus) { - var originalUrl = "/driver" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.SPIDER + urlParam - // buff := bytes.NewBuffer(pbytes) - // url := util.SPIDER + "/driver" - - fmt.Println("driverInfo : ", driverInfo) - - // body, err := util.CommonHttpPost(url, regionInfo) - pbytes, _ := json.Marshal(driverInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - // if err != nil { - // fmt.Println(err) - // return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - // } - - // respBody := resp.Body - // respStatus := resp.StatusCode - // return respBody, fwmodels.WebStatus{StatusCode: respStatus} - - respBody := resp.Body - respStatus := resp.StatusCode - - returnDriverInfo := spider.DriverInfo{} - returnStatus := fwmodels.WebStatus{} - - if err != nil { - fmt.Println(err) - return &returnDriverInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnDriverInfo) - fmt.Println(returnDriverInfo) - } - returnStatus.StatusCode = respStatus - - return &returnDriverInfo, returnStatus -} - -// driver 추가 -func MconDriverCreate(driver *models.Driver, c buffalo.Context) error { - - tx := c.Value("tx").(*pop.Connection) - - // validateErr , otherErr - verrs, err := driver.Create(tx) - if verrs != nil { - return errors.WithStack(verrs) - } - if err != nil { - return errors.WithStack(err) - } - - return nil -} - -// Driver 삭제 -func DelDriver(driverName string) (io.ReadCloser, fwmodels.WebStatus) { - var originalUrl = "/driver/{{driver_name}}" - - var paramMapper = make(map[string]string) - paramMapper["{{driver_name}}"] = driverName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.SPIDER + urlParam - // buff := bytes.NewBuffer(pbytes) - // url := util.SPIDER + "/driver/" + driverName - - fmt.Println("driverName : ", driverName) - - pbytes, _ := json.Marshal(driverName) - // body, err := util.CommonHttpDelete(url, pbytes) - resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// /////////// Config -// 현재 설정된 Config 목록 TODO :Spider에서 /config 가 없는 것 같은데.... 나중에 확인해서 안쓰면 제거할 것 -func GetConfigList() ([]spider.ConfigInfo, fwmodels.WebStatus) { - url := util.SPIDER + "/config" - fmt.Println("=========== GetConfigListData : ", url) - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // defer body.Close() - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - configList := map[string][]spider.ConfigInfo{} - json.NewDecoder(respBody).Decode(&configList) - fmt.Println(configList["config"]) - - return configList["config"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// Config 상세조회 -func GetConfigData(configID string) (*spider.ConfigInfo, fwmodels.WebStatus) { - url := util.SPIDER + "/config/" + configID - fmt.Println("=========== GetConfigData : ", url) - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // defer body.Close() - configInfo := spider.ConfigInfo{} - if err != nil { - fmt.Println(err) - return &configInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&configInfo) - fmt.Println(configInfo) - return &configInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Driver 등록 -func RegConfig(configInfo *spider.ConfigInfo) (*spider.ConfigInfo, fwmodels.WebStatus) { - // buff := bytes.NewBuffer(pbytes) - url := util.SPIDER + "/config" - - fmt.Println("configInfo : ", configInfo) - - // body, err := util.CommonHttpPost(url, regionInfo) - pbytes, _ := json.Marshal(configInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - // if err != nil { - // fmt.Println(err) - // return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - // } - - // respBody := resp.Body - // respStatus := resp.StatusCode - // return respBody, fwmodels.WebStatus{StatusCode: respStatus} - respBody := resp.Body - respStatus := resp.StatusCode - - returnConfigInfo := spider.ConfigInfo{} - returnStatus := fwmodels.WebStatus{} - - if err != nil { - fmt.Println(err) - return &returnConfigInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnConfigInfo) - fmt.Println(returnConfigInfo) - } - returnStatus.StatusCode = respStatus - - return &returnConfigInfo, returnStatus -} - -// Driver 삭제 -func DelConfig(configID string) (io.ReadCloser, fwmodels.WebStatus) { - - // buff := bytes.NewBuffer(pbytes) - url := util.SPIDER + "/config/" + configID - - fmt.Println("configID : ", configID) - - pbytes, _ := json.Marshal(configID) - // body, err := util.CommonHttpDelete(url, pbytes) - resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -////// DB 사용 - -// Connection이 존재하는지 check -func CheckExistsCloudProvider(providerName string, tx *pop.Connection) bool { - dr := &models.CloudProvider{} - q := tx.Where("id = ?", providerName) - b, err := q.Exists(dr) - if err != nil { - errors.WithStack(err) - } - return b -} - -// Credential이 존재하는지 check -func CheckExistsCredential(providerName string, credentialName string) bool { - cr := &models.Credential{} - //q := tx.Where("providerName = ?", providerName).Where("credential_name = ?", credentialName) - q := models.DB.Where("provider_id = ?", providerName).Where("credential_name = ?", credentialName) - b, err := q.Exists(cr) - if err != nil { - errors.WithStack(err) - } - return b -} - -// Region이 존재하는지 check -func CheckExistsRegion(providerName string, regionName string) bool { - rg := &models.Region{} - //q := tx.Where("providerName = ?", providerName).Where("region_name = ?", regionName) - q := models.DB.Where("provider_id = ?", providerName).Where("region_name = ?", regionName) - b, err := q.Exists(rg) - if err != nil { - errors.WithStack(err) - } - return b -} - -// RegionKeyValue가 존재하는지 check -func CheckExistsRegionKeyValue(regionKeyVal models.RegionKeyvalue) bool { - q := models.DB.Where("region_id = ?", regionKeyVal.RegionID).Where("key = ?", regionKeyVal.Key).Where("value = ?", regionKeyVal.Value) - b, err := q.Exists(regionKeyVal) - if err != nil { - errors.WithStack(err) - } - return b -} - -// Driver가 존재하는지 check -func CheckExistsDriver(providerName string, driverName string, driverLibFilename string) bool { - dr := &models.Driver{} - q := models.DB.Where("driver_name = ?", driverName).Where("lib_file_name = ?", driverLibFilename) - b, err := q.Exists(dr) - if err != nil { - errors.WithStack(err) - } - return b -} - -// Connection이 존재하는지 check -func CheckExistsCloudConnection(connectionView views.ViewCloudConnection) bool { - cloudConnection := &views.ViewCloudConnections{} - - query := models.DB.Q() - //if connectionView.ID.String() != "" { - // query = query.Where("id = ?", connectionView.ID.String()) - //} - if connectionView.ConnectionName != "" { - query = query.Where("connection_name = ?", connectionView.ConnectionName) - } - if connectionView.ProviderID != "" { - query = query.Where("provider_id = ?", connectionView.ProviderID) - } - if connectionView.RegionName != "" { - query = query.Where("region_name = ?", connectionView.RegionName) - } - if connectionView.ZoneName != "" { - query = query.Where("zone_name = ?", connectionView.ZoneName) - } - if connectionView.CredentialName != "" { - query = query.Where("credential_name = ?", connectionView.CredentialName) - } - if connectionView.DriverName != "" { - query = query.Where("driver_name = ?", connectionView.DriverName) - } - - //q := models.DB.Where("connection_name = ?", connectionView.) - b, err := query.Exists(cloudConnection) - if err != nil { - log.Println("connection exists", err) - errors.WithStack(err) - } - return b -} - -// 해당 user의 provider에서 사용할 credential이 지정되어 있는지 -func CheckExistsUserCredential(userId string, providerId string) bool { - userCredential := &models.UserCredential{} - query := models.DB.Q() - query = query.Where("user_id = ?", userId).Where("provider_id = ?", providerId) - b, err := query.Exists(userCredential) - if err != nil { - errors.WithStack(err) - } - return b - - // uc := &models.UserCredential{} - // q := tx.Where("id = ?", providerName) - // b, err := q.Exists(dr) - // if err != nil { - // errors.WithStack(err) - // } -} - -// connection정보 -func GetUsedConnection(paramConnectionMapping *models.CloudConnectionMapping) (*models.CloudConnectionMapping, error) { - connectionMapping := &models.CloudConnectionMapping{} - - query := models.DB.Q() - query = query.Where("namespace_id = ?", paramConnectionMapping.NamespaceID) - query = query.Where("resource_id = ?", paramConnectionMapping.ResourceID) - query = query.Where("resource_type = ?", paramConnectionMapping.ResourceType) - err := query.First(&connectionMapping) - - if err != nil { - return connectionMapping, err - } - return connectionMapping, err -} - -// connection정보 등 하위내용이 필요하므로 tx로 호출 -func GetUsedConnectionTx(paramConnectionMapping *models.CloudConnectionMapping, c buffalo.Context) (*models.CloudConnectionMapping, error) { - connectionMapping := &models.CloudConnectionMapping{} - - tx := c.Value("tx").(*pop.Connection) - err := tx.Eager().Where("resource_id = ?", paramConnectionMapping.ResourceID).Where("resource_type = ?", paramConnectionMapping.ResourceType).First(connectionMapping) - - //err := models.DB.Where("resource_id = ?", paramConnectionMapping.ResourceID).Where("resource_type = ?", paramConnectionMapping.ResourceType).First(connectionMapping) - if err != nil { - return connectionMapping, err - } - return connectionMapping, err -} - -// connection Mapping -// 요 리소스는 이 connection을 사용하며 이 credential을 사용한다. -func SaveConnectionMapping(connectionMapping *models.CloudConnectionMapping, c buffalo.Context) error { - - tx := c.Value("tx").(*pop.Connection) - - vErrors, err := connectionMapping.Create(tx) - if vErrors.HasAny() { - log.Println("CloudConnectionMapping vErrors", vErrors.Error()) - return errors.WithStack(vErrors) - } - if err != nil { - log.Println("CloudConnectionMapping err", err) - return errors.WithStack(err) - } - - return nil - - // ID uuid.UUID `json:"id" db:"id"` - // CreatedAt time.Time `json:"created_at" db:"created_at"` - // UpdatedAt time.Time `json:"updated_at" db:"updated_at"` - - // // vpc, securitygroup, sshkey, vmimage, vmspec, nlb, vm, mckscontrolplane, mcksworkernode, pmks - // ResourceType string `json:"resource_type" db:"resource_type"` - // ResourceID string `json:"resource_id" db:"resource_id"` // 해당 resource의 ID를 string으로 - - // ConnectionID uuid.UUID `json:"connection_id" db:"connection_id"` - // CloudConnection *CloudConnection `belongs_to:"cloud_connection"` - - // CredentialID uuid.UUID `json:"credential_id" db:"credential_id"` - // Credential *Credential `belongs_to:"credential"` -} - -// provider와 region, zone 으로 해당 유저가 사용가능한 connection 목록 return -// tx로 호출해야 Credential, Driver 등 정보가 채워짐. -func GetConnectionList(providerId string, regionName string, zoneName string, c buffalo.Context) ([]models.CloudConnection, error) { - - connectionList := []models.CloudConnection{} - - // tx := c.Value("tx").(*pop.Connection) - // query := tx.Eager() - // if paramConnection.ConnectionName != "" { - // query.Where("connection_name = ", paramConnection.ConnectionName) - // } - // err := query.All(&cloudConnections) - // if err != nil { - // return errors.WithStack(err) - // } - - tx := c.Value("tx").(*pop.Connection) - query := tx.Q() - if providerId != "" { - query = query.Where("provider_id = ?", providerId) - } - err := query.All(&connectionList) - if err != nil { - return connectionList, errors.WithStack(err) - } - - // query := models.DB.Q() - // if providerId != "" { - // query = query.Where("provider_id = ?", providerId) - // } - // err := query.All(&connectionList) - // if err != nil { - // log.Println("CloudConnectionMapping err", err) - // return connectionList, errors.WithStack(err) - // } - return connectionList, nil -} - -// 사용자가 등록한 credential 조회 -// isDefaultOnly=true 면 default로 설정한 것만 조회 -func ListUserCredential(providerId string, userId string, isDefaultOnly bool) ([]models.UserCredential, error) { - credentials := []models.UserCredential{} - query := models.DB.Q() - query = query.Where("user_id = ?", userId) - if providerId != "" { - query = query.Where("provider_id = ? ", providerId) - } - if isDefaultOnly { - query = query.Where("is_default = ? ", true) - } - - err := query.All(&credentials) - - if err != nil { - return credentials, errors.WithStack(err) - } - return credentials, nil -} - -// User가 CSP에 default로 설정한 credential : user가 등록한 credential 에서 default 설정은 csp별로 1개만 가능. -func GetDefaultUserCredential(providerId string, userId string) (models.UserCredential, error) { - credential := models.UserCredential{} - - query := models.DB.Q() - query = query.Where("user_id = ?", userId) - query = query.Where("provider_id = ? ", providerId) - query = query.Where("is_default = ? ", true) - err := query.First(&credential) - - if err != nil { - return credential, errors.WithStack(err) - } - return credential, nil -} - -// 새로 UserCredential 저장 -func SaveDefaultUserCredential(userCredential *models.UserCredential, c buffalo.Context) (*models.UserCredential, error) { - credential := &models.UserCredential{} - - if userCredential.IsDefault { - // 기존에 isDefault가 있으면 update - existsCredential := userCredential - existsCredential.IsDefault = false - _, err := UpdateDefaultUserCredential(existsCredential, c) - if err != nil { - return userCredential, err - } - } - - tx := c.Value("tx").(*pop.Connection) - - vErrors, err := userCredential.Create(tx) - if vErrors.HasAny() { - log.Println("CloudConnectionMapping vErrors", vErrors.Error()) - return credential, errors.WithStack(vErrors) - } - if err != nil { - log.Println("CloudConnectionMapping err", err) - return credential, errors.WithStack(err) - } - - return credential, nil -} - -// user credential 수정 -// update는 user_id, provider_id 단위로 한다. -func UpdateDefaultUserCredential(userCredential *models.UserCredential, c buffalo.Context) (models.UserCredential, error) { - credential := models.UserCredential{} - - // userID가 있어야 함 - if userCredential.UserID.IsNil() { - return credential, errors.New("Known User") - } - if userCredential.ProviderID == "" { - return credential, errors.New("Provider is empty") - } - - tx := c.Value("tx").(*pop.Connection) - - vErrors, err := userCredential.Update(tx) - if vErrors.HasAny() { - log.Println("CloudConnectionMapping vErrors", vErrors.Error()) - return credential, errors.WithStack(vErrors) - } - if err != nil { - log.Println("CloudConnectionMapping err", err) - return credential, errors.WithStack(err) - } - - return credential, nil -} - -// Credential 목록 조회 : provider와 credential 이름으로 조회. 가능하면 provider는 오면 좋겠는데. 관리자가 생성한것들 -func ListPublicCredentialByName(providerId string, credentialName string, c buffalo.Context) ([]models.Credential, error) { - - credentials := []models.Credential{} - query := models.DB.Q() - if providerId != "" { - query = query.Where("provider_id = ? ", providerId) - } - if credentialName != "" { - query = query.Where("credential_name = ?", credentialName) - } - query = query.Where("user_level = ? ", "admin") - err := query.All(&credentials) - - if err != nil { - return credentials, errors.WithStack(err) - } - return credentials, nil -} - -// Credentian 조회 : provider와 credential 이름으로 1건조회 -func GetCredentialByName(providerId string, credentialName string, c buffalo.Context) (models.Credential, error) { - - credential := models.Credential{} - /* - tx := c.Value("tx").(*pop.Connection) - // if providerName != "" { - // tx.Where("provider_id = ?", providerName) - // } - query := tx.Eager() - //if credentialName != "" { - query.Where("credential_name = ", credentialName) - //} - err := query.All(&credential) - - // q := tx.Q() - // q.Join("cloud_providers", "cloud_connections.provider_id = cloud_providers.id") - // q.Join("drivers", "cloud_connections.driver_id = drivers.id") - // q.Join("credentials", "cloud_connections.credential_id = credentials.id") - // q.Join("regions", "cloud_connections.region_id = regions.id") - // if providerName != "" { - // q.Where(`cloud_providers.provider_name like ?`, name) - // } - // if regionName != "" { - // q.Where(`regions.region_name like ?`, regionName) - // } - // q.Paginate(page, perPage) - - // err := q.All(&roles) - - //err := models.DB.Where("provider_id = ?", providerName).All(connectionList) - */ - //err := models.DB.Where("credential_name = ?", credentialName).Last(&credential) - //query := models.DB - log.Println("asdfasdfasdfasdfasdfasdfasdfasdfasdf&&&&&&&&&&&&&&") - tx := c.Value("tx").(*pop.Connection) - query := tx.Eager() - if credentialName != "" { - query.Where("provider_id = ", providerId) - log.Println("provider_id = ", providerId) - } - if credentialName != "" { - query.Where("credential_name = ", credentialName) - log.Println("credential_name = ", credentialName) - } - - resultCredentials := &models.Credentials{} - err := query.All(resultCredentials) - //err := models.DB.Where("provider_id = ?", providerName) - - // TODO : 이부분을 그냥 사용하는쪽에서 처리하게 할까? method를 단건, 여러건으로 나눌까 - if len(*resultCredentials) == 0 { - // not found - return credential, errors.New("Not found connection") - } else if len(*resultCredentials) > 1 { - // too many - return credential, errors.New("Too many connections ") - } else { - credential = (*resultCredentials)[0] - } - - if err != nil { - log.Println("credential err", err) - return credential, errors.WithStack(err) - } - return credential, nil -} - -func GetDriverByName(driverName string, c buffalo.Context) (models.Driver, error) { - - driver := models.Driver{} - /* - tx := c.Value("tx").(*pop.Connection) - - query := tx.Eager() - //if driverName != "" { - query.Where("driver_name = ", driverName) - //} - err := query.All(&driver) - */ - err := models.DB.Where("driver_name = ?", driverName).Last(&driver) - if err != nil { - log.Println("driver err", err) - return driver, errors.WithStack(err) - } - return driver, nil -} -func GetDriverByProvider(providerId string, c buffalo.Context) (models.Driver, error) { - - driver := models.Driver{} - err := models.DB.Where("provider_id = ?", providerId).Last(&driver) - if err != nil { - log.Println("driver err", err) - return driver, errors.WithStack(err) - } - return driver, nil -} - -func GetRegionByName(regionName string, c buffalo.Context) (models.Region, error) { - - region := models.Region{} - /* - tx := c.Value("tx").(*pop.Connection) - - query := tx.Eager() - //if regionName != "" { - query.Where("region_name = ", regionName) - //} - err := query.All(®ion) - */ - err := models.DB.Where("region_name = ?", regionName).Last(®ion) - if err != nil { - log.Println("region err", err) - return region, errors.WithStack(err) - } - return region, nil -} - -// 해당 connection과 연결된 resource들 확인 -// 해당 resource로 사용된 connectionId 가져올 때, -// 해당 credential이 사용된 connectionId 가져올 때, -// 해당 connection이 사용된 resource 가져올 때 -func ListConnectionMapping(connectionId string, credentialId string, resourceType string, resourceId string, resourceName string) ([]models.CloudConnectionMapping, error) { - cm := []models.CloudConnectionMapping{} - - query := models.DB.Q() - if connectionId != "" { - query = query.Where("connection_id = ?", connectionId) - } - if credentialId != "" { - query = query.Where("credential_id = ?", credentialId) - } - if resourceType != "" { - query = query.Where("resource_type = ?", resourceType) - } - if resourceId != "" { - query = query.Where("resource_id = ?", resourceId) - } - - err := query.All(&cm) - if err != nil { - log.Println("ListConnectionMapping err", err) - return cm, errors.WithStack(err) - } - - return cm, nil -} - -// 해당 connection과 연결된 resource들 확인 -// 해당 resource로 사용된 connectionId 가져올 때, -// 해당 credential이 사용된 connectionId 가져올 때, -// 해당 connection이 사용된 resource 가져올 때 -func GetConnectionMapping(connectionId string, credentialId string, resourceType string, resourceId string, resourceName string) (models.CloudConnectionMapping, error) { - cm := models.CloudConnectionMapping{} - - query := models.DB.Q() - if connectionId != "" { - query = query.Where("connection_id = ?", connectionId) - } - if credentialId != "" { - query = query.Where("credential_id = ?", credentialId) - } - if resourceType != "" { - query = query.Where("resource_type = ?", resourceType) - } - if resourceId != "" { - query = query.Where("resource_id = ?", resourceId) - } - - err := query.First(&cm) - if err != nil { - log.Println("GetConnectionMapping err", err) - return cm, errors.WithStack(err) - } - - return cm, nil -} - -// provider와 region, zone 으로 해당 유저가 사용가능한 connection 단건 return -// user가 사용할 credential (여러개면 random하게 택1) + provider + region + zone(optional) 로 사용할 connection 조회 ---> 여러개면 random하게 택1 -// region 별 connection은 1개만 사용. 여러개중 1개만 -func GetAvailableConnection(viewCloudConnection views.ViewCloudConnection, c buffalo.Context) (views.ViewCloudConnection, error) { - connection := views.ViewCloudConnection{} - /////////// - // user 정보 가져오기 - //log.Println(c.Session().Get("current_user")) - //log.Println(c.Session().Get("current_user_id")) - //user := c.Session().Get("current_user").(*models.User) - //user := c.Value("current_user").(*models.User) - userId := c.Session().Get("current_user_id").(uuid.UUID) - if userId == uuid.Nil { - return connection, errors.New("failed to get User") - } - - //userCredentialID := c.Session().Get("current_credential") // user가 수시로 바꿀 수 있으면 session에 set하도록 변경 필요 - // credential 조회 : 해당 provider의 credential에 defautl 설정이 되어 있으면 해당 값 사용. - //userCredentialID := user.DefaultCredential - userCredentialID := "" - credentialExist := CheckExistsUserCredential(userId.String(), viewCloudConnection.ProviderID) - // - if credentialExist { - userDefaultCredential, err := GetDefaultUserCredential(viewCloudConnection.ProviderID, userId.String()) - if err != nil { - return connection, err - } - // default set이 되어있으면 set. - if userDefaultCredential.IsDefault { - userCredentialID = userDefaultCredential.CredentialID.String() - } - } - - if userCredentialID == "" { // 없으면 가용 user credential 조회 - publicCredentials, err := ListPublicCredentialByName(viewCloudConnection.ProviderID, "", c) // credential이름은 없이, user_level == 'admin' 인것만 조회 - if err != nil { - return connection, err - } - - if len(publicCredentials) == 0 { - return connection, errors.New("failed to get Credential") - } - userCredentialID = publicCredentials[0].ID.String() - } - - // user가 사용가능한 credentialId 1개 조회. 여러개 중 1개 - /* - if credentialID == "" { - credential := &models.Credential{} - credentialQuery := models.DB.Q() - credentialQuery = credentialQuery.Where("provider_id = ?", providerID).Where("user_level = ?", "admin") - err := credentialQuery.First(credential) - if err != nil { - log.Println("credentialQuery err", err) - return *connection, errors.WithStack(err) - } - credentialID = credential.ID.String() - } - */ - - query := models.DB.Q() - query = query.Where("credential_id = ?", userCredentialID) - if viewCloudConnection.ProviderID != "" { - query = query.Where("provider_id = ?", viewCloudConnection.ProviderID) - } - if viewCloudConnection.RegionName != "" { - query = query.Where("region_name = ?", viewCloudConnection.RegionName) - } - if viewCloudConnection.ZoneName != "" { - query = query.Where("zone_name = ?", viewCloudConnection.ZoneName) - } - err := query.First(&connection) - if err != nil { - log.Println("region err", err) - return connection, errors.WithStack(err) - } - - // region/zone ID 조회. 여러 zone이 있으면 여러개 중 1개 - // region := &models.Region{} - // regionQuery := models.DB - // if( providerName != "" ){ - // regionQuery.Where("provider_id = ?", providerName) - // } - // if( regionName != "" ){ - // regionQuery.Where("region_name = ?", regionName) - // } - // if( zoneName != "" ){ - // regionQuery.Where("zone_name = ?", zoneName) - // } - - /* - select cc.provider_id, cc.connection_name, kv.region_id - , max(case when kv.key='Region' then kv.value end) as region_name - , max(case when kv.key='Zone' then kv.value end) as zone_id - from cloud_connections cc - join regions rg - on cc.region_id = rg.id - join region_keyvalues kv - on rg.id = kv.region_id - where cc.region_id = '1bb8a5e4-daaa-43ae-a7ed-68b49e97f737' - --where rg.region_name like '%ap-hongkong%' - group by cc.provider_id, cc.connection_name, kv.region_id - --order by rg.provider_id, kv.region_id - */ - - //err = regionQuery.First(region) - //if err != nil { - // log.Println("region err", err) - // return *cc, errors.WithStack(err) - //} - - // 사용할 connection 중 1개 return. zone 이 조건에 없으면 여러개 중 1개 - - /* - connectionQuery := models.DB.Q() - connectionQuery = connectionQuery.Where("provider_id = ?", providerID) - connectionQuery = connectionQuery.Where("credential_id = ?", userCredentialID) - if regionName != "" { - connectionQuery.Where(`region_id like ?`, regionName) - } - if zoneName != "" { - connectionQuery.Where(`zone_id like ?`, zoneName) - } - err := connectionQuery.First(&connection) - if err != nil { - log.Println("connection err", err) - return connection, errors.WithStack(err) - } - */ - /* - -- view로 생성함. - queryStr := "" - queryStr += " select * " - queryStr += " from ( " - queryStr += " select cc.provider_id, cc.connection_name " - queryStr += " , dr.id as driver_id " - queryStr += " , max(dr.driver_name) as driver_name " - queryStr += " , cd.id as credential_id " - queryStr += " , max(cd.credential_name) as credential_name " - queryStr += " , max(rg.region_name) as region_alias " - queryStr += " , kv.region_id " - queryStr += " , max(case when kv.key='Region' then kv.value end) as region_name " - queryStr += " , max(case when kv.key='Zone' then kv.value end) as zone_name " - queryStr += " from cloud_connections cc " - queryStr += " join cloud_providers cp " - queryStr += " on cc.provider_id = cp.id " - queryStr += " join drivers dr " - queryStr += " on cc.driver_id = dr.id " - queryStr += " join credentials cd " - queryStr += " on cc.credential_id = cd.id " - queryStr += " join regions rg " - queryStr += " on cc.region_id = rg.id " - queryStr += " join region_keyvalues kv " - queryStr += " on rg.id = kv.region_id " - queryStr += " where 1 = 1 " - queryStr += " group by cc.provider_id, cc.connection_name " - queryStr += " , dr.id, cd.id, rg.id, kv.region_id " - queryStr += " ) cloud_connection_mapping " - queryStr += " where 1 = 1 " - - q := models.DB.RawQuery(queryStr) - err := q.First(&connection) - if err != nil { - log.Println("connection err", err) - return connection, errors.WithStack(err) - } - - */ - - return connection, nil -} - -func (gvc GVC) GetAvailableConnection(viewCloudConnection *views.ViewCloudConnection, c buffalo.Context) (views.ViewCloudConnection, error) { - connection := views.ViewCloudConnection{} - /////////// - // user 정보 가져오기 - user := c.Value("current_user").(*models.User) - if user.ID == uuid.Nil { - return connection, errors.New("failed to get User") - } - - //userCredentialID := c.Session().Get("current_credential") // user가 수시로 바꿀 수 있으면 session에 set하도록 변경 필요 - // credential 조회 : 해당 provider의 credential에 defautl 설정이 되어 있으면 해당 값 사용. - //userCredentialID := user.DefaultCredential - userCredentialID := "" - credentialExist := CheckExistsUserCredential(user.ID.String(), viewCloudConnection.ProviderID) - // - if credentialExist { - userDefaultCredential, err := GetDefaultUserCredential(viewCloudConnection.ProviderID, user.ID.String()) - if err != nil { - return connection, err - } - // default set이 되어있으면 set. - if userDefaultCredential.IsDefault { - userCredentialID = userDefaultCredential.CredentialID.String() - } - } - - if userCredentialID == "" { // 없으면 가용 user credential 조회 - publicCredentials, err := ListPublicCredentialByName(viewCloudConnection.ProviderID, "", c) // credential이름은 없이, user_level == 'admin' 인것만 조회 - if err != nil { - return connection, err - } - - if len(publicCredentials) == 0 { - return connection, errors.New("failed to get Credential") - } - userCredentialID = publicCredentials[0].ID.String() - } - - // user가 사용가능한 credentialId 1개 조회. 여러개 중 1개 - /* - if credentialID == "" { - credential := &models.Credential{} - credentialQuery := models.DB.Q() - credentialQuery = credentialQuery.Where("provider_id = ?", providerID).Where("user_level = ?", "admin") - err := credentialQuery.First(credential) - if err != nil { - log.Println("credentialQuery err", err) - return *connection, errors.WithStack(err) - } - credentialID = credential.ID.String() - } - */ - - query := models.DB.Q() - query = query.Where("credential_id = ?", userCredentialID) - if viewCloudConnection.ProviderID != "" { - query = query.Where("provider_id = ?", viewCloudConnection.ProviderID) - } - if viewCloudConnection.RegionName != "" { - query = query.Where("region_name = ?", viewCloudConnection.RegionName) - } - if viewCloudConnection.ZoneName != "" { - query = query.Where("zone_name = ?", viewCloudConnection.ZoneName) - } - err := query.First(&connection) - if err != nil { - log.Println("region err", err) - return connection, errors.WithStack(err) - } - - // region/zone ID 조회. 여러 zone이 있으면 여러개 중 1개 - // region := &models.Region{} - // regionQuery := models.DB - // if( providerName != "" ){ - // regionQuery.Where("provider_id = ?", providerName) - // } - // if( regionName != "" ){ - // regionQuery.Where("region_name = ?", regionName) - // } - // if( zoneName != "" ){ - // regionQuery.Where("zone_name = ?", zoneName) - // } - - /* - select cc.provider_id, cc.connection_name, kv.region_id - , max(case when kv.key='Region' then kv.value end) as region_name - , max(case when kv.key='Zone' then kv.value end) as zone_id - from cloud_connections cc - join regions rg - on cc.region_id = rg.id - join region_keyvalues kv - on rg.id = kv.region_id - where cc.region_id = '1bb8a5e4-daaa-43ae-a7ed-68b49e97f737' - --where rg.region_name like '%ap-hongkong%' - group by cc.provider_id, cc.connection_name, kv.region_id - --order by rg.provider_id, kv.region_id - */ - - //err = regionQuery.First(region) - //if err != nil { - // log.Println("region err", err) - // return *cc, errors.WithStack(err) - //} - - // 사용할 connection 중 1개 return. zone 이 조건에 없으면 여러개 중 1개 - - /* - connectionQuery := models.DB.Q() - connectionQuery = connectionQuery.Where("provider_id = ?", providerID) - connectionQuery = connectionQuery.Where("credential_id = ?", userCredentialID) - if regionName != "" { - connectionQuery.Where(`region_id like ?`, regionName) - } - if zoneName != "" { - connectionQuery.Where(`zone_id like ?`, zoneName) - } - err := connectionQuery.First(&connection) - if err != nil { - log.Println("connection err", err) - return connection, errors.WithStack(err) - } - */ - /* - -- view로 생성함. - queryStr := "" - queryStr += " select * " - queryStr += " from ( " - queryStr += " select cc.provider_id, cc.connection_name " - queryStr += " , dr.id as driver_id " - queryStr += " , max(dr.driver_name) as driver_name " - queryStr += " , cd.id as credential_id " - queryStr += " , max(cd.credential_name) as credential_name " - queryStr += " , max(rg.region_name) as region_alias " - queryStr += " , kv.region_id " - queryStr += " , max(case when kv.key='Region' then kv.value end) as region_name " - queryStr += " , max(case when kv.key='Zone' then kv.value end) as zone_name " - queryStr += " from cloud_connections cc " - queryStr += " join cloud_providers cp " - queryStr += " on cc.provider_id = cp.id " - queryStr += " join drivers dr " - queryStr += " on cc.driver_id = dr.id " - queryStr += " join credentials cd " - queryStr += " on cc.credential_id = cd.id " - queryStr += " join regions rg " - queryStr += " on cc.region_id = rg.id " - queryStr += " join region_keyvalues kv " - queryStr += " on rg.id = kv.region_id " - queryStr += " where 1 = 1 " - queryStr += " group by cc.provider_id, cc.connection_name " - queryStr += " , dr.id, cd.id, rg.id, kv.region_id " - queryStr += " ) cloud_connection_mapping " - queryStr += " where 1 = 1 " - - q := models.DB.RawQuery(queryStr) - err := q.First(&connection) - if err != nil { - log.Println("connection err", err) - return connection, errors.WithStack(err) - } - - */ - - return connection, nil -} - -// provider와 region, zone 으로 해당 유저가 사용가능한 connection 단건 return -// user가 사용할 credential (여러개면 random하게 택1) + provider + region + zone(optional) 로 사용할 connection 조회 ---> 여러개면 random하게 택1 -func ListViewConnection(namespace string, viewCloudConnection views.ViewCloudConnection, c buffalo.Context) ([]views.ViewCloudConnection, error) { - connectionList := []views.ViewCloudConnection{} - /////////// - // user 정보 가져오기 - user := c.Value("current_user").(*models.User) - if user.ID == uuid.Nil { - return connectionList, errors.New("failed to get User") - } - - //userCredentialID := c.Session().Get("current_credential") // user가 수시로 바꿀 수 있으면 session에 set하도록 변경 필요 - userCredentialID := user.DefaultCredential - if userCredentialID == "" { // 없으면 가용 user credential 조회 - publicCredentials, err := ListPublicCredentialByName(viewCloudConnection.ProviderID, "", c) // credential이름은 없이, user_level == 'admin' 인것만 조회 - if err != nil { - return connectionList, err - } - userCredentialID = publicCredentials[0].ID.String() - } - - query := models.DB.Q() - query = query.Where("credential_id = ?", userCredentialID) - if viewCloudConnection.ProviderID != "" { - query = query.Where("provider_id = ?", viewCloudConnection.ProviderID) - } - if viewCloudConnection.RegionName != "" { - query = query.Where("region_name = ?", viewCloudConnection.RegionName) - } - if viewCloudConnection.ZoneName != "" { - query = query.Where("zone_name = ?", viewCloudConnection.ZoneName) - } - err := query.All(&connectionList) - if err != nil { - log.Println("region err", err) - return connectionList, errors.WithStack(err) - } - - return connectionList, nil -} - -// 단건조회 -func GetViewConnection(viewCloudConnection views.ViewCloudConnection) (views.ViewCloudConnection, error) { - connection := views.ViewCloudConnection{} - query := models.DB.Q() - - if viewCloudConnection.ConnectionName != "" { - query = query.Where("connection_name = ?", viewCloudConnection.ConnectionName) - } - if viewCloudConnection.ProviderID != "" { - query = query.Where("provider_id = ?", viewCloudConnection.ProviderID) - } - if viewCloudConnection.RegionName != "" { - query = query.Where("region_name = ?", viewCloudConnection.RegionName) - } - if viewCloudConnection.ZoneName != "" { - query = query.Where("zone_name = ?", viewCloudConnection.ZoneName) - } - err := query.First(&connection) - if err != nil { - log.Println("region err", err) - return connection, errors.New("has not found") - //return connection, errors.WithStack(err) - } - return connection, nil -} - -func CheckExistsResourceMapping(resourceType string, resourceId string, tx *pop.Connection) bool { - - cm := &models.CloudConnectionMapping{} - //q := tx.Where("resource_type = ?", resourceType) - //q.Where("resource_id = ?", resourceId) - //b, err := q.Exists(cm) - b, err := tx.Where("resource_type = ?", resourceType).Where("resource_id = ?", resourceId).Exists(cm) - if err != nil { - errors.WithStack(err) - } - return b -} - -func ListResourceByType(namespace string, connectionParamMap map[string]string, provider string, regionName string, zoneName string, resourceType string) ([]views.ViewCloudResource, error) { - log.Println("ListResourceByType ") - - ccm := []views.ViewCloudResource{} - //ccm := []models.CloudConnectionMapping{} - //addParam := []string{} - addParam := []interface{}{} - - queryString := "" - queryString += " select vc.id, vc.connection_name, cc.namespace_name, cc.namespace_id, vc.provider_id, vc.region_id, vc.region_name" - queryString += " , cc.resource_type, cc.resource_id, cc.resource_name" - queryString += " from view_cloud_connections vc" - queryString += " join cloud_connection_mappings cc" - queryString += " on vc.id = cc.connection_id" - queryString += " and vc.credential_id = cc.credential_id" - queryString += " where 1 = 1" - queryString += " and cc.namespace_name = ?" // resource는 namespace를 가진다. - queryString += " and cc.resource_type = ?" // 조회하고자 하는 resource type - addParam = append(addParam, namespace) - addParam = append(addParam, resourceType) - - if provider != "" { - queryString += " and vc.provider_id = ?" - addParam = append(addParam, provider) - } - if regionName != "" { - queryString += " and vc.region_name = ?" - addParam = append(addParam, regionName) - } - if zoneName != "" { - queryString += " and vc.zone_name = ?" - addParam = append(addParam, zoneName) - } - - queryString += " and cc.updated_at = ( select max(ccm.updated_at) updated_at " - queryString += " from cloud_connection_mappings ccm" - queryString += " where ccm.namespace_name = ?" - queryString += " and ccm.resource_type = ?" - queryString += " and ccm.resource_id = cc.resource_id" - queryString += " group by namespace_id, resource_type, resource_id" - queryString += " )" - addParam = append(addParam, namespace) - addParam = append(addParam, resourceType) - - // 특정 resource를 사용하는 connection만 거르기 - if len(connectionParamMap) > 0 { - for connectionParamKey, connectionParamVal := range connectionParamMap { - // connection 이 직접 주어지면 바로 사용 - if connectionParamKey == "connectionName" { - queryString += " and vc.connection_name = ?" - addParam = append(addParam, connectionParamVal) - break - } else { - // resource id가 따로 주어지면 subquery 추가 - queryString += " and vc.id = (" - queryString += " select connection_id " - queryString += " from cloud_connection_mappings ccm" - queryString += " where ccm.namespace_name = ? " - queryString += " and ccm.resource_type = ? " - queryString += " and ccm.resource_id = ? " - queryString += " ) " - addParam = append(addParam, namespace) - addParam = append(addParam, connectionParamKey) - addParam = append(addParam, connectionParamVal) - } - } - } - - log.Println("queryString ", queryString) - log.Println("addParam ", addParam) - query := models.DB.RawQuery(queryString, addParam...) - err := query.All(&ccm) - if err != nil { - return ccm, err - } - - return ccm, nil -} - -func SyncCloudProvider(c buffalo.Context) error { - cspList, status := GetCloudOSList() - if status.StatusCode == 500 { - return errors.New(status.Message) - } - // 조회 내역 db에 저장 - tx := c.Value("tx").(*pop.Connection) - for _, csp := range cspList { - cspId := strings.ToUpper(csp) - b := CheckExistsCloudProvider(cspId, tx) - cp := &models.CloudProvider{} - cp.ProviderID = cspId - cp.ProviderName = csp - if !b { // 없으면 create - verr, err := cp.Create(tx) - if verr.HasAny() { - spew.Dump("csp creation succeed ", *cp) - return errors.WithStack(verr) - } - - if err != nil { - spew.Dump("csp creation failed ", cp) - return errors.WithStack(err) - } - } else { // 있으면 update - verr, err := cp.Update(tx) - if verr.HasAny() { - spew.Dump("csp update succeed ", *cp) - return errors.WithStack(verr) - } - if err != nil { - spew.Dump("csp update failed ", cp) - return errors.WithStack(err) - } - } - } - - return nil -} - -// Driver 동기화 -func SyncDriver(c buffalo.Context) error { - driverList, status := GetDriverList() - - if status.StatusCode == 500 { - return errors.New(status.Message) - } - - tx := c.Value("tx").(*pop.Connection) - for _, driver := range driverList { - log.Println("checkExistsDriver before ") - b := CheckExistsDriver(driver.ProviderName, driver.DriverName, driver.DriverLibFileName) - dr := &models.Driver{} - //dr.ProviderID = driver.ProviderName - dr.DriverName = driver.DriverName - dr.LibFileName = driver.DriverLibFileName - log.Println("checkExistsDriver result ", b) - if !b { // 없으면 create - verr, err := dr.Create(tx) - if verr.HasAny() { - spew.Dump("driver creation succeed ", *dr) - return errors.WithStack(verr) - } - if err != nil { - spew.Dump("driver creation failed ", dr) - return errors.WithStack(err) - } - } else { // 있으면 update - verr, err := dr.Update(tx) - if verr.HasAny() { - spew.Dump("driver update succeed ", *dr) - return errors.WithStack(verr) - } - if err != nil { - spew.Dump("driver update failed ", dr) - return errors.WithStack(err) - } - } - } - - log.Println("checkExistsDriver after ") - return nil - -} - -// Region 동기화 -func SyncRegion(c buffalo.Context) error { - cbRegionList, status := GetRegionList() - if status.StatusCode == 500 { - return errors.New(status.Message) - } - // 조회 내역 db에 저장 - tx := c.Value("tx").(*pop.Connection) - for _, cbRegion := range cbRegionList { - b := CheckExistsRegion(cbRegion.ProviderName, cbRegion.RegionName) - rg := &models.Region{} - rg.ProviderID = cbRegion.ProviderName - rg.RegionName = cbRegion.RegionName - log.Println(" result ", b) - if !b { // 없으면 create - verr, err := rg.Create(tx) - log.Println(" Create result ") - if verr.HasAny() { - log.Println("verr ", verr) - spew.Dump("region creation failed ", *rg) - return errors.WithStack(verr) - } - if err != nil { - log.Println("err ", err) - spew.Dump("region creation failed ", *rg) - return errors.WithStack(err) - } - } else { // 있으면 skip - // verr, err := rg.Update(tx) - // if verr.HasAny() { - // spew.Dump("region update succeed ", *rg) - // return errors.WithStack(verr) - // } - // if err != nil { - // spew.Dump("region update failed ", *rg) - // return errors.WithStack(err) - // } - } - // region keyvalue - // region 조회 - log.Println(" region keyvalue start ", rg) - regionVals := &models.Region{} - //err := tx.Find(regionVals, rg.ID) - err := tx.Where("region_name = ? ", rg.RegionName).Where("provider_id = ?", cbRegion.ProviderName).First(regionVals) - //err := models.DB.Where("region_name = ? ", rg.RegionName).Where("provider_id = ?", rg.ProviderID).First(regionVals) - // query := tx.Where("region_name = ? ", rg.RegionName).Where("provider_id = ?", region.ProviderName).First(regionVals) - // err := query.All(®ionVals) - if err != nil { - errors.WithStack(err) - } - log.Println("regionKeyVal ", regionVals) - regionID := regionVals.ID - for _, regionKeyVal := range cbRegion.KeyValueInfoList { - log.Println("cbRegion KeyValueInfoList ", regionKeyVal) - spew.Dump(regionKeyVal) - rgKeyVal := &models.RegionKeyvalue{} - rgKeyVal.RegionID = regionID - rgKeyVal.Key = regionKeyVal.Key - rgKeyVal.Value = regionKeyVal.Value - - // 존재여부 check. 있으면 continue - exist := CheckExistsRegionKeyValue(*rgKeyVal) - if exist { - log.Println("exist KeyValueInfo ", rgKeyVal) - continue - } - - vErrors, err := rgKeyVal.Create(tx) - if vErrors.HasAny() { - log.Println("cbRegion KeyValueInfoList vErrors", vErrors.Error()) - return errors.WithStack(vErrors) - } - if err != nil { - log.Println("cbRegion KeyValueInfoList err", err) - return errors.WithStack(err) - } - } - } - return nil -} - -// Credential 동기화 -func SyncCredential(c buffalo.Context) error { - cbCredentialList, status := GetCredentialList() - if status.StatusCode == 500 { - return errors.New(status.Message) - } - // 조회 내역 db에 저장 - tx := c.Value("tx").(*pop.Connection) - for _, cbCredential := range cbCredentialList { - b := CheckExistsCredential(cbCredential.ProviderName, cbCredential.CredentialName) - cr := &models.Credential{} - //cr.ProviderID = cbCredential.ProviderName - cr.CredentialName = cbCredential.CredentialName - cr.UserLevel = "admin" // sync는 public으로. 향후 Role 조정하도록 - credentialID := uuid.UUID{} - log.Println(" result ", b) - if !b { // 없으면 create - verr, err := cr.Create(tx) - log.Println(" Create result ") - if verr.HasAny() { - log.Println("verr ", verr) - spew.Dump("Credential creation failed ", *cr) - return errors.WithStack(verr) - } - if err != nil { - log.Println("err ", err) - spew.Dump("Credential creation failed ", *cr) - return errors.WithStack(err) - } - credentialID = cr.ID - } else { // 있으면 update - verr, err := cr.Update(tx) - if verr.HasAny() { - spew.Dump("Credential update succeed ", *cr) - return errors.WithStack(verr) - } - if err != nil { - spew.Dump("Credential update failed ", *cr) - return errors.WithStack(err) - } - // Credential 조회 - log.Println(" Credential keyvalue start ", cr) - credentialVals := &models.Credential{} - err = tx.Where("credential_name = ? ", cbCredential.CredentialName).Where("provider_id = ?", cbCredential.ProviderName).First(credentialVals) - //err := tx.Find(credentialVals, cr.ID)// 이미 있는경우 ID는 비어있으므로 사용할 수 없음 - if err != nil { - errors.WithStack(err) - } - log.Println("credentialKeyVal ", credentialVals) - credentialID = credentialVals.ID - } - // Credential keyvalue - - for _, credentialKeyVal := range cbCredential.KeyValueInfoList { - log.Println("cbCredential KeyValueInfoList ", credentialKeyVal) - spew.Dump(credentialKeyVal) - crKeyVal := &models.CredentialKeyvalue{} - crKeyVal.CredentialID = credentialID - crKeyVal.Key = credentialKeyVal.Key - crKeyVal.Value = credentialKeyVal.Value - vErrors, err := crKeyVal.Create(tx) - if vErrors.HasAny() { - log.Println("cbCredential KeyValueInfoList vErrors", vErrors.Error()) - return errors.WithStack(vErrors) - } - if err != nil { - log.Println("cbCredential KeyValueInfoList err", err) - return errors.WithStack(err) - } - } - } - return nil -} - -// Connection 동기화 -func SyncConnection(c buffalo.Context) error { - // connection 조회 - connectionList, status := GetCloudConnectionConfigList() - if status.StatusCode == 500 { - return errors.New(status.Message) - } - // 조회 내역 db에 저장 - tx := c.Value("tx").(*pop.Connection) - for _, connection := range connectionList { - - connectionView := views.ViewCloudConnection{} - connectionView.ProviderID = connection.ProviderID - connectionView.ConnectionName = connection.ConfigName - connectionView.DriverName = connection.DriverName - b := CheckExistsCloudConnection(connectionView) - - // credentialUUID, err := uuid.FromString(connection.CredentialName) - log.Println("BEFORE INSERT ===================") - spew.Dump(connection) - credential, err := GetCredentialByName(connection.ProviderName, connection.CredentialName, c) - if err != nil { - log.Println("credential uuid parsing failed : ", err) - continue - } - - driver, err := GetDriverByName(connection.DriverName, c) - if err != nil { - log.Println("driver uuid parsing failed : ", driver, err) - continue - } - - region, err := GetRegionByName(connection.RegionName, c) - if err != nil { - log.Println("region uuid parsing failed : ", err) - continue - } - - conn := &models.CloudConnection{} - conn.ProviderID = connection.ProviderName - conn.ConnectionName = connection.ConfigName - //conn.CredentialID = credential.ID// credential uuid parsing failed : unable to fetch records: expected slice but got struct - //conn.DriverID = driver.ID - //conn.RegionID = region.ID - conn.Credential = &credential - conn.Driver = &driver - conn.Region = ®ion - //log.Println("region : ", region) - //log.Println("credential : ", credential) - //log.Println("driver : ", driver) - // conn.CloudProvider.ID = connection.ProviderName - // conn.Credential.ID = credentialUUID// 직접 ID에 할당하면 되는가? - // conn.Driver.ID = connection.Driver - // conn.Region = conn.Region - if !b { // 없으면 create - verr, err := conn.Create(tx) - if verr.HasAny() { - spew.Dump("conn creation succeed ", *conn) - return errors.WithStack(verr) - } - if err != nil { - spew.Dump("conn creation failed ", conn) - return errors.WithStack(err) - } - } else { // 있으면 update - verr, err := conn.Update(tx) - if verr.HasAny() { - spew.Dump("conn update succeed ", *conn) - return errors.WithStack(verr) - } - if err != nil { - spew.Dump("conn update failed ", conn) - return errors.WithStack(err) - } - } - } - return nil -} - -// credential 추가시 호출 -// 모든 region에 대해 해당 credential로 connection 생성 -func GenerateConnectionsByCredential(paramProviderID string, paramCredentialName string, c buffalo.Context) error { - // 해당 provider의 driver 조회 - driverInfo, err := GetDriverByProvider(paramProviderID, c) - if err != nil { - return err - } - - // spider의 모든 connection 조회 - connectionList, respStatus := GetCloudConnectionConfigList() - if respStatus.StatusCode == 500 { - return errors.New(respStatus.Message) - } - - // spider의 모든 region 조회 - regionList, respStatus := GetRegionList() - if respStatus.StatusCode == 500 { - return errors.New(respStatus.Message) - } - - // 해당 region에 connection이 있으면 skip 없으면 생성 - for idx, spiderRegion := range regionList { - if paramProviderID != spiderRegion.ProviderName { - continue - } - - keyValueList := spiderRegion.KeyValueInfoList - - regionValue := "" - zoneValue := "" - for _, keyValue := range keyValueList { - if keyValue.Key == "Region" { - regionValue = keyValue.Value - } - if keyValue.Key == "Zone" { - zoneValue = keyValue.Value - } - } - - if regionValue == "" || zoneValue == "" { - continue - } - - connectionView := views.ViewCloudConnection{} - connectionView.ProviderID = paramProviderID - connectionView.DriverName = driverInfo.DriverName - connectionView.RegionName = regionValue - connectionView.ZoneName = zoneValue - connectionView.CredentialName = paramCredentialName - - log.Println("CheckExistsCloudConnection") - b := CheckExistsCloudConnection(connectionView) //db에 connection이 있는지 check - log.Println("CheckExistsCloudConnection result ", b) - if !b { // 없으면 생성 - // credential 조회 => credentialId - b := CheckExistsCredential(paramProviderID, paramCredentialName) - if !b { - // create Credential - log.Println("need to reg credential to db ", paramCredentialName) - cr := &models.Credential{} - cr.ProviderID = paramProviderID - cr.CredentialName = paramCredentialName - cr.UserLevel = "admin" // sync는 public으로. 향후 Role 조정하도록 - - tx := c.Value("tx").(*pop.Connection) - verr, err := cr.Create(tx) - if err != nil { - log.Println("cr create err", err) - } - if verr != nil { - log.Println("cr create verr", verr) - } - return nil - } - credentialInfo, err := MconCredentialGet(&models.Credential{ProviderID: paramProviderID, CredentialName: paramCredentialName}) - if err != nil { - log.Println("credential err ", err) - return err - } - log.Println("spiderRegion ", spiderRegion) - // region 조회 => regionId - regionInfo, err := MconRegionGet(&models.Region{ProviderID: paramProviderID, RegionName: spiderRegion.RegionName}) - if err != nil { - log.Println("region err ", err) - return err - } - - // spider에 connection이 있으면 db에만 저장. - // var connectionName = paramProviderID + "-" + regionInfo.RegionName - // spiderConnection, respStatus := GetCloudConnectionConfigData(connectionName) - // if respStatus.StatusCode == 500 { - // log.Println("GetCloudConnectionConfigData err", respStatus) - // return nil - // } - - // credential & region으로 connection 찾기 - spiderExistsConnection := false - spiderConnectionName := "" - for _, spiderConn := range connectionList { - spiderProviderId := spiderConn.ProviderID - spiderProviderName := spiderConn.ProviderName - spiderRegionName := spiderConn.RegionName - spiderCredentialName := spiderConn.CredentialName - - log.Println("paramProviderID ", paramProviderID) - log.Println("spiderProviderId ", spiderProviderId) - log.Println("spiderProviderName ", spiderProviderName) - log.Println("regionInfo.RegionName ", regionInfo.RegionName) - log.Println("spiderRegionName ", spiderRegionName) - log.Println("paramCredentialName ", paramCredentialName) - log.Println("spiderCredentialName ", spiderCredentialName) - // 비교 : - if strings.EqualFold(paramProviderID, spiderProviderName) && strings.EqualFold(regionInfo.RegionName, spiderRegionName) && strings.EqualFold(paramCredentialName, spiderCredentialName) { - spiderExistsConnection = true - spiderConnectionName = spiderConn.ConfigName - break - } - } - log.Println("spiderConnectionName ", spiderConnectionName) - log.Println("spiderExistsConnection ", spiderExistsConnection) - if !spiderExistsConnection { - spiderConnectionName = regionInfo.RegionName + "-conn" // region명에 -conn을 붙인다(region명에 provider가 포함되어 있음) - - paramConnectionInfo := new(spider.CloudConnectionConfigInfo) - paramConnectionInfo.ConfigName = spiderConnectionName - paramConnectionInfo.ProviderID = strings.ToUpper(paramProviderID) - paramConnectionInfo.ProviderName = strings.ToUpper(paramProviderID) - paramConnectionInfo.CredentialName = credentialInfo.CredentialName - paramConnectionInfo.DriverName = driverInfo.DriverName - paramConnectionInfo.RegionName = regionInfo.RegionName - - _, respStatus := RegCloudConnectionConfig(paramConnectionInfo) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - log.Println("spider connection reg failed ", respStatus.Message) - return nil - } - } - //spiderConnection.ConfigName - - conn := &models.CloudConnection{} - conn.ProviderID = paramProviderID - conn.ConnectionName = strings.ToLower(spiderConnectionName) - conn.Credential = &credentialInfo - conn.Driver = &driverInfo - conn.Region = ®ionInfo - - tx := c.Value("tx").(*pop.Connection) - verr, err := conn.Create(tx) - if verr.HasAny() { - spew.Dump("conn creation succeed ", *conn) - return errors.WithStack(verr) - } - if err != nil { - spew.Dump("conn creation failed ", conn) - return errors.WithStack(err) - } - } else { - log.Println("CheckExistsCloudConnection exist ", b) - } - log.Println("CheckExistsCloudConnection end ", idx) - } - return nil -} diff --git a/mc_web_console_api/handler/ClusterHandler.go b/mc_web_console_api/handler/ClusterHandler.go deleted file mode 100644 index 4dab9e3d..00000000 --- a/mc_web_console_api/handler/ClusterHandler.go +++ /dev/null @@ -1,459 +0,0 @@ -package handler - -import ( - "encoding/json" - "fmt" - "log" - "mc_web_console_api/fwmodels" - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - "mc_web_console_api/fwmodels/tumblebug/mcis" - - util "mc_web_console_api/util" - "net/http" -) - -// Delete all Clusters -func DelAllCluster(nameSpaceID string, matchParam string) (mcis.TbClusterStatus, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/cluster" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - matchParamVal := "" - - if matchParam != "" { - matchParamVal = "?option=" + matchParam - } - - // url := util.TUMBLEBUG + urlParam - url := util.TUMBLEBUG + urlParam + matchParamVal - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttpWithoutParam(url, http.MethodDelete) - - resultInfo := mcis.TbClusterStatus(mcis.ClusterDeleting) - - if err != nil { - fmt.Println(err) - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("DelAllMcis ", failResultInfo) - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// List all Clusters or Clusters' ID -func ClusterList(nameSpaceID string, optionParam string) ([]mcis.TbClusterInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/cluster" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - optionParamVal := "" - - if optionParam == "" { - optionParam = "status" - } - // install, init, cpus, cpum, memR, memW, fioR, fioW, dbR, dbW, rtt, mrtt, clean - //if optionParam != "" { - // optionParamVal = "?option=" + optionParam - //} - if optionParam == "all" { - optionParamVal = "" // all 은 optionParam값이 없는 경우임. - } else { - optionParamVal = "?option=" + optionParam - } - - url := util.TUMBLEBUG + urlParam + optionParamVal - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - clusterList := map[string][]mcis.TbClusterInfo{} - returnStatus := fwmodels.WebStatus{} - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - //errorInfo := fwmodels.ErrorInfo{} - //json.NewDecoder(respBody).Decode(&errorInfo) - //fmt.Println("respStatus != 200 reason ", errorInfo) - //returnStatus.Message = errorInfo.Message - - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&clusterList) - fmt.Println(clusterList["items"]) - - returnStatus.StatusCode = respStatus - log.Println(respBody) - // util.DisplayResponse(resp) // 수신내용 확인 - - return clusterList["items"], returnStatus - -} - -func ClusterIDList(nameSpaceID string) ([]string, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/cluster" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam + "?option=id" - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - clusterIdList := []string{} - returnStatus := fwmodels.WebStatus{} - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - //errorInfo := fwmodels.ErrorInfo{} - //json.NewDecoder(respBody).Decode(&errorInfo) - //fmt.Println("respStatus != 200 reason ", errorInfo) - //returnStatus.Message = errorInfo.Message - - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&clusterIdList) - - returnStatus.StatusCode = respStatus - log.Println(respBody) - // util.DisplayResponse(resp) // 수신내용 확인 - - return clusterIdList, returnStatus -} - -// Create Cluster - -func CreateCluster(nameSpaceID string, optionParam string, clusterReq *mcis.TbClusterReq) (*mcis.TbClusterInfo, fwmodels.WebStatus) { - - var originalUrl = "/ns/{nsId}/cluster" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - if optionParam != "" { - urlParam += "?option=" + optionParam - } - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(clusterReq) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnClusterInfo := mcis.TbClusterInfo{} - returnStatus := fwmodels.WebStatus{} - - if err != nil { - fmt.Println(err) - return &returnClusterInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnClusterInfo) - fmt.Println(returnClusterInfo) - } - returnStatus.StatusCode = respStatus - - return &returnClusterInfo, returnStatus -} - -// Delete Cluster - -func DelCluster(nameSpaceID string, clusterName string) (*mcis.StatusInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/cluster/{clusterId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{clusterId}"] = clusterName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - - if clusterName == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "cluster is required"} - } - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - statusInfo := mcis.StatusInfo{} - if err != nil { - fmt.Println("delCluster ", err) - return &statusInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&statusInfo) - fmt.Println(statusInfo) - - if respStatus != 200 && respStatus != 201 { - fmt.Println(respBody) - return &statusInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: statusInfo.Message} - } - return &statusInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Add a Node Group - -func AddNodeGroup(nameSpaceID string, clusterName string, nodeGroupReq *mcis.TbNodeGroupReq) (*mcis.TbClusterInfo, fwmodels.WebStatus) { - - var originalUrl = "/ns/{nsId}/cluster/{clusterId}/nodegroup" - var paramMapper = make(map[string]string) - - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{clusterId}"] = clusterName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - if clusterName == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "cluster is required"} - } - - pbytes, _ := json.Marshal(nodeGroupReq) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnClusterInfo := mcis.TbClusterInfo{} - returnStatus := fwmodels.WebStatus{} - - if err != nil { - fmt.Println(err) - return &returnClusterInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnClusterInfo) - fmt.Println(returnClusterInfo) - } - returnStatus.StatusCode = respStatus - - return &returnClusterInfo, returnStatus -} - -// Remove a NodeGroup -func DelNodeGroup(nameSpaceID string, clusterName string, nodeGroupName string) (*mcis.StatusInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/cluster/{clusterId}/nodegroup/{nodeGroupName}" - var paramMapper = make(map[string]string) - - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{clusterId}"] = clusterName - paramMapper["{nodeGroupName}"] = nodeGroupName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - if clusterName == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "cluster is required"} - } - if nodeGroupName == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "nodeGroup is required"} - } - - // 경로안에 parameter가 있어 추가 param없이 호출 함 - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - statusInfo := mcis.StatusInfo{} - if err != nil { - fmt.Println(err) - return &statusInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&statusInfo) - fmt.Println(statusInfo) - - return &statusInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Change a NodeGroup's Autoscale size -func EditNodeGroupAutoscalesize(nameSpaceID string, clusterName string, nodeGroupName string) (*mcis.TbClusterInfo, fwmodels.WebStatus) { - - var originalUrl = "/ns/{nsId}/cluster/{clusterId}/nodeGroup/{nodeGroupName}/autoscalesize" - - var paramMapper = make(map[string]string) - - paramMapper["{nsid}"] = nameSpaceID - paramMapper["{clusterId}"] = clusterName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - - if clusterName == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "cluster is required"} - } - if nodeGroupName == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "nodeGroup is required"} - } - - pbytes, _ := json.Marshal(nodeGroupName) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - - returnClusterInfo := mcis.TbClusterInfo{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return &returnClusterInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnClusterInfo) - fmt.Println(returnClusterInfo) - } - returnStatus.StatusCode = respStatus - - return &returnClusterInfo, returnStatus - -} - -// Set a NodeGroup's Autoscaling on/off -func EditAutoscaling(nameSpaceID string, clusterName string, nodeGroupName string) (*mcis.TbClusterInfo, fwmodels.WebStatus) { - - var originalUrl = "/ns/{nsId}/cluster/{clusterId}/nodegroup/{nodeGroupName}/onautoscaling" - - var paramMapper = make(map[string]string) - - paramMapper["{nsid}"] = nameSpaceID - paramMapper["{clusterId}"] = clusterName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - - if clusterName == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "cluster is required"} - } - if nodeGroupName == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "nodeGroup is required"} - } - - pbytes, _ := json.Marshal(nodeGroupName) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - - returnClusterInfo := mcis.TbClusterInfo{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return &returnClusterInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnClusterInfo) - fmt.Println(returnClusterInfo) - } - returnStatus.StatusCode = respStatus - - return &returnClusterInfo, returnStatus -} - -// Upgrade a Cluster's version -func UpgradeClusterVersion(nameSpaceID string, clusterName string) (*mcis.TbClusterInfo, fwmodels.WebStatus) { - - var originalUrl = "/ns/{nsId}/cluster/{clusterId}/upgrade" - - var paramMapper = make(map[string]string) - - paramMapper["{nsid}"] = nameSpaceID - paramMapper["{clusterId}"] = clusterName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - - if clusterName == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "cluster is required"} - } - - resp, err := util.CommonHttp(url, nil, http.MethodPut) - - returnClusterInfo := mcis.TbClusterInfo{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return &returnClusterInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnClusterInfo) - fmt.Println(returnClusterInfo) - } - returnStatus.StatusCode = respStatus - - return &returnClusterInfo, returnStatus - -} diff --git a/mc_web_console_api/handler/CommonHandler.go b/mc_web_console_api/handler/CommonHandler.go deleted file mode 100644 index 0023e813..00000000 --- a/mc_web_console_api/handler/CommonHandler.go +++ /dev/null @@ -1,57 +0,0 @@ -package handler - -import ( - // "encoding/base64" - "fmt" - // "log" - // "io" - // "net/http" - "os" - "strconv" - "time" - - "github.com/gobuffalo/buffalo" -) - -var SpiderURL = os.Getenv("SPIDER_URL") -var TumbleBugURL = os.Getenv("TUMBLE_URL") -var DragonFlyURL = os.Getenv("DRAGONFLY_URL") -var LadyBugURL = os.Getenv("LADYBUG_URL") - -// type CredentialInfo struct { -// Username string -// Password string -// } -type CommonURL struct { - SpiderURL string - TumbleBugURL string - DragonFlyURL string - LadyBugURL string -} - -func GetCommonURL() CommonURL { - common_url := CommonURL{ - SpiderURL: os.Getenv("SPIDER_URL"), - TumbleBugURL: os.Getenv("TUMBLE_URL"), - DragonFlyURL: os.Getenv("DRAGONFLY_URL"), - LadyBugURL: os.Getenv("LADYBUG_URL"), - } - return common_url -} - -func GetNameSpaceToString(c buffalo.Context) string { - fmt.Println("====== GET NAME SPACE ========") - - nsId := c.Session().Get("namespace") - - return nsId.(string) -} - -func MakeNameSpace(name string) string { - now := time.Now() - nanos := strconv.FormatInt(now.UnixNano(), 10) - - result := name + "-" + nanos - fmt.Println("makeNameSpace : ", result) - return result -} diff --git a/mc_web_console_api/handler/DataDiskHandler.go b/mc_web_console_api/handler/DataDiskHandler.go deleted file mode 100644 index 52b5ecb6..00000000 --- a/mc_web_console_api/handler/DataDiskHandler.go +++ /dev/null @@ -1,482 +0,0 @@ -package handler - -import ( - "encoding/json" - "fmt" - "log" - "strings" - - // "math" - "net/http" - // "strconv" - // "sync" - - //"github.com/davecgh/go-spew/spew" - - // "mc_web_console_api/fwmodels/spider" - // "mc_web_console_api/fwmodels/tumblebug" - "mc_web_console_api/fwmodels" - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - "mc_web_console_api/fwmodels/webconsole" - - util "mc_web_console_api/util" - - "github.com/gobuffalo/buffalo" -) - -// DataDisk 목록 조회 -func GetDataDiskList(nameSpaceID string, optionParam string, filterKeyParam string, filterValParam string) ([]tbmcir.TbDataDiskInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/dataDisk" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - if optionParam != "" { - urlParam += "?option=" + optionParam - } else { - urlParam += "?option=" - } - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - - url := util.TUMBLEBUG + urlParam - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - log.Println(respBody) - dataDiskInfoList := map[string][]tbmcir.TbDataDiskInfo{} - json.NewDecoder(respBody).Decode(&dataDiskInfoList) - //spew.Dump(body) - fmt.Println(dataDiskInfoList["dataDisk"]) - - return dataDiskInfoList["dataDisk"], fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetDataDiskListByID(nameSpaceID string, filterKeyParam string, filterValParam string) ([]string, fwmodels.WebStatus) { - fmt.Println("GetDataDiskListByID ************ : ") - var originalUrl = "/ns/{nsId}/resources/dataDisk" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - urlParam += "?option=id" - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - url := util.TUMBLEBUG + urlParam - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - log.Println(respBody) - //vNetInfoList := map[string][]string{} - dataDiskInfoList := tbcommon.TbIdList{} - json.NewDecoder(respBody).Decode(&dataDiskInfoList) - - return dataDiskInfoList.IDList, fwmodels.WebStatus{StatusCode: respStatus} -} - -// List 조회시 optionParam 추가 -func GetDataDiskListByOption(nameSpaceID string, optionParam string, filterKeyParam string, filterValParam string) ([]tbmcir.TbDataDiskInfo, fwmodels.WebStatus) { - fmt.Println("GetDataDiskListByOption ************ : ") - var originalUrl = "/ns/{nsId}/resources/dataDisk" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - if optionParam != "" { - urlParam += "?option=" + optionParam - } else { - urlParam += "?option=" - } - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - url := util.TUMBLEBUG + urlParam - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - log.Println(respBody) - dataDiskInfoList := map[string][]tbmcir.TbDataDiskInfo{} - json.NewDecoder(respBody).Decode(&dataDiskInfoList) - //spew.Dump(body) - fmt.Println(dataDiskInfoList["dataDisk"]) - - return dataDiskInfoList["dataDisk"], fwmodels.WebStatus{StatusCode: respStatus} -} - -func RegDataDisk(nameSpaceID string, dataDiskReqInfo *tbmcir.TbDataDiskReq) (*tbmcir.TbDataDiskInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/dataDisk" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - fmt.Println("dataDiskReqInfo : ", dataDiskReqInfo) - - pbytes, _ := json.Marshal(dataDiskReqInfo) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - resultDataDiskInfo := tbmcir.TbDataDiskInfo{} - if err != nil { - fmt.Println(err) - return &resultDataDiskInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - fmt.Println("respStatus ", respStatus) - - if respStatus == 500 { - webStatus := fwmodels.WebStatus{} - json.NewDecoder(respBody).Decode(&webStatus) - fmt.Println(webStatus) - webStatus.StatusCode = respStatus - return &resultDataDiskInfo, webStatus - } - // 응답에 생성한 객체값이 옴 - json.NewDecoder(respBody).Decode(&resultDataDiskInfo) - fmt.Println(resultDataDiskInfo) - - return &resultDataDiskInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Async로 Disk 생성 : 항목 안에 attached Vm 정보가 있으면 생성 후 attach까지 한다. -func AsyncRegDataDisk(nameSpaceID string, dataDiskReqInfo *webconsole.DataDiskCreateReq, c buffalo.Context) { - taskKey := nameSpaceID + "||" + "disk" + "||" + dataDiskReqInfo.Name - - // DataDiskCreateReq -> tbmcir.TbDataDiskReq - tbDataDiskReq := tbmcir.TbDataDiskReq{} - tbDataDiskReq.Name = dataDiskReqInfo.Name - tbDataDiskReq.ConnectionName = dataDiskReqInfo.ConnectionName - tbDataDiskReq.CspDataDiskId = dataDiskReqInfo.CspDataDiskId - tbDataDiskReq.Description = dataDiskReqInfo.Description - tbDataDiskReq.DiskSize = dataDiskReqInfo.DiskSize - tbDataDiskReq.DiskType = dataDiskReqInfo.DiskType - - resultDataDiskInfo, respStatus := RegDataDisk(nameSpaceID, &tbDataDiskReq) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - StoreWebsocketMessage(util.TASK_TYPE_DISK, taskKey, util.DISK_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, c) - } else { - StoreWebsocketMessage(util.TASK_TYPE_DISK, taskKey, util.DISK_LIFECYCLE_CREATE, util.TASK_STATUS_COMPLETE, c) - - // create 성공이고 vm에 attach - if dataDiskReqInfo.AttachVmID != "" { - // disk 조회해서 available 상태일 때 attach한다. - // 1. disk 상태조회 : available까지 1초씩 1분 기다릴까? - - // 2. vm에 attach - mcisID := dataDiskReqInfo.McisID - vmID := dataDiskReqInfo.AttachVmID - optionParam := "attach" - attachDetachDataDiskReq := new(tbmcir.TbAttachDetachDataDiskReq) - attachDetachDataDiskReq.DataDiskId = resultDataDiskInfo.ID - - AsyncAttachDetachDataDiskToVM(nameSpaceID, mcisID, vmID, optionParam, attachDetachDataDiskReq, c) - // _, respStatus := AttachDetachDataDiskToVM(nameSpaceID, mcisID, vmID, optionParam, attachDetachDataDiskReq) - // if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - // StoreWebsocketMessage(util.TASK_TYPE_DISK, taskKey, util.DISK_LIFECYCLE_ATTACHED, util.TASK_STATUS_FAIL, c) - // } else { - // StoreWebsocketMessage(util.TASK_TYPE_DISK, taskKey, util.DISK_LIFECYCLE_ATTACHED, util.TASK_STATUS_COMPLETE, c) - // } - } - } -} - -// Namespace내 모든 DataDisk 삭제 -func DelAllDataDisk(nameSpaceID string) (fwmodels.WebStatus, fwmodels.WebStatus) { - webStatus := fwmodels.WebStatus{} - - var originalUrl = "/ns/{nsId}/resources/dataDisk" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam + "?match=match" - - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - - if err != nil { - fmt.Println(err) - return webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return webStatus, fwmodels.WebStatus{StatusCode: respStatus} -} - -// DataDisk 삭제 -func DelDataDisk(nameSpaceID string, dataDiskID string) (fwmodels.WebStatus, fwmodels.WebStatus) { - webStatus := fwmodels.WebStatus{} - - var originalUrl = "/ns/{nsId}/resources/dataDisk/{dataDiskId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{dataDiskId}"] = dataDiskID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - - if err != nil { - fmt.Println(err) - return webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return webStatus, fwmodels.WebStatus{StatusCode: respStatus} -} - -func AsyncDelDataDisk(nameSpaceID string, dataDiskID string, c buffalo.Context) { - taskKey := nameSpaceID + "||" + "disk" + "||" + dataDiskID - - _, respStatus := DelDataDisk(nameSpaceID, dataDiskID) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - StoreWebsocketMessage(util.TASK_TYPE_DISK, taskKey, util.DISK_LIFECYCLE_DELETE, util.TASK_STATUS_FAIL, c) - } else { - StoreWebsocketMessage(util.TASK_TYPE_DISK, taskKey, util.DISK_LIFECYCLE_DELETE, util.TASK_STATUS_COMPLETE, c) - } -} - -// DataDisk 상세 조회 -func DataDiskGet(nameSpaceID string, dataDiskID string) (*tbmcir.TbDataDiskInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/dataDisk/{dataDiskId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{dataDiskId}"] = dataDiskID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - - fmt.Println("nameSpaceID : ", nameSpaceID) - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - dataDiskInfo := tbmcir.TbDataDiskInfo{} - if err != nil { - fmt.Println(err) - return &dataDiskInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&dataDiskInfo) - fmt.Println(dataDiskInfo) - - return &dataDiskInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func DataDiskPut(nameSpaceID string, dataDiskID string, dataDiskUpsizeReq *tbmcir.TbDataDiskUpsizeReq) (*tbmcir.TbDataDiskInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/dataDisk/{dataDiskId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{dataDiskId}"] = dataDiskID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(dataDiskUpsizeReq) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - dataDiskInfoResponse := tbmcir.TbDataDiskInfo{} - if err != nil { - fmt.Println(err) - return &dataDiskInfoResponse, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - log.Println("resp = ", resp) - respBody := resp.Body - respStatus := resp.StatusCode - log.Println("respBody = ", respBody) - - json.NewDecoder(respBody).Decode(&dataDiskInfoResponse) - fmt.Println(dataDiskInfoResponse) - - return &dataDiskInfoResponse, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Disk 정보 조회 -// Provider, connection 에서 사용가능한 DiskType 조회 -// 현재 : spider의 cloudos_meta.yaml 값 사용 -func DiskLookup(providerId string, connectionName string) ([]webconsole.LookupDiskInfo, error) { - - //defaultNameSpaceID := loginInfo.DefaultNameSpaceID - diskInfoMap := map[string]webconsole.LookupDiskInfo{} - - // 변환 : 구분자만 빼서 공백 빼고 array로 - awsRootdiskType := "standard / gp2 / gp3" - awsDiskType := "standard / gp2 / gp3 / io1 / io2 / st1 / sc1" - awsDiskSize := "standard|1|1024|GB / gp2|1|16384|GB / gp3|1|16384|GB / io1|4|16384|GB / io2|4|16384|GB / st1|125|16384|GB / sc1|125|16384|GB" - - awsDiskInfo := webconsole.LookupDiskInfo{} - awsDiskInfo.ProviderID = "AWS" - awsDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(awsRootdiskType, " ", ""), "/") - awsDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(awsDiskType, " ", ""), "/") - awsDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(awsDiskSize, " ", ""), "/") - diskInfoMap["AWS"] = awsDiskInfo - - gcpRootdiskType := "pd-standard / pd-balanced / pd-ssd / pd-extreme" - gcpDiskType := "pd-standard / pd-balanced / pd-ssd / pd-extreme" - gcpDiskSize := "pd-standard|10|65536|GB / pd-balanced|10|65536|GB / pd-ssd|10|65536|GB / pd-extreme|500|65536|GB" - - gcpDiskInfo := webconsole.LookupDiskInfo{} - gcpDiskInfo.ProviderID = "GCP" - gcpDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(gcpRootdiskType, " ", ""), "/") - gcpDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(gcpDiskType, " ", ""), "/") - gcpDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(gcpDiskSize, " ", ""), "/") - diskInfoMap["GCP"] = gcpDiskInfo - - aliRootdiskType := "cloud_essd / cloud_efficiency / cloud / cloud_ssd" - aliDiskType := "cloud / cloud_efficiency / cloud_ssd / cloud_essd" - aliDiskSize := "cloud|5|2000|GB / cloud_efficiency|20|32768|GB / cloud_ssd|20|32768|GB / cloud_essd_PL0|40|32768|GB / cloud_essd_PL1|20|32768|GB / cloud_essd_PL2|461|32768|GB / cloud_essd_PL3|1261|32768|GB" - - aliDiskInfo := webconsole.LookupDiskInfo{} - aliDiskInfo.ProviderID = "ALIBABA" - aliDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(aliRootdiskType, " ", ""), "/") - aliDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(aliDiskType, " ", ""), "/") - aliDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(aliDiskSize, " ", ""), "/") - diskInfoMap["ALIBABA"] = aliDiskInfo - - tencentRootdiskType := "CLOUD_PREMIUM / CLOUD_SSD" - tencentDiskType := "CLOUD_PREMIUM / CLOUD_SSD / CLOUD_HSSD / CLOUD_BASIC / CLOUD_TSSD" - tencentDiskSize := "CLOUD_PREMIUM|10|32000|GB / CLOUD_SSD|20|32000|GB / CLOUD_HSSD|20|32000|GB / CLOUD_BASIC|10|32000|GB / CLOUD_TSSD|10|32000|GB" - - tencentDiskInfo := webconsole.LookupDiskInfo{} - tencentDiskInfo.ProviderID = "TENCENT" - tencentDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(tencentRootdiskType, " ", ""), "/") - tencentDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(tencentDiskType, " ", ""), "/") - tencentDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(tencentDiskSize, " ", ""), "/") - diskInfoMap["TENCENT"] = tencentDiskInfo - - dataDiskInfoList := []webconsole.LookupDiskInfo{} - if providerId != "" { - // TODO : 해당 connection으로 사용가능한 DISK 정보 조회 - if connectionName != "" { // 현재는 connection으로 filter 하지 않음 - - } - //providerDisk := webconsole.LookupDiskInfo{} - providerDisk := diskInfoMap[providerId] - dataDiskInfoList = append(dataDiskInfoList, providerDisk) - } else if connectionName != "" { - // 모든 provider의 datadisk 정보 조회... - // getConnection 에서 Provider 가져옴 - - } - - return dataDiskInfoList, nil -} - -// Provider, Region 에서 사용가능한 DiskType 조회 -// 현재 : spider의 cloudos_meta.yaml 값 사용 -// Region 값에 따라 달라지는게 있으면 추가할 것. -func AvailableDiskTypeByProviderRegion(providerId string, regionName string) ([]webconsole.AvailableDiskType, error) { - - diskInfoMap := map[string]webconsole.AvailableDiskType{} - - // 변환 : 구분자만 빼서 공백 빼고 array로 - awsRootdiskType := "standard / gp2 / gp3" - awsDiskType := "standard / gp2 / gp3 / io1 / io2 / st1 / sc1" - awsDiskSize := "standard|1|1024|GB / gp2|1|16384|GB / gp3|1|16384|GB / io1|4|16384|GB / io2|4|16384|GB / st1|125|16384|GB / sc1|125|16384|GB" - - awsDiskInfo := webconsole.AvailableDiskType{} - awsDiskInfo.ProviderID = "AWS" - awsDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(awsRootdiskType, " ", ""), "/") - awsDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(awsDiskType, " ", ""), "/") - awsDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(awsDiskSize, " ", ""), "/") - diskInfoMap["AWS"] = awsDiskInfo - - gcpRootdiskType := "pd-standard / pd-balanced / pd-ssd / pd-extreme" - gcpDiskType := "pd-standard / pd-balanced / pd-ssd / pd-extreme" - gcpDiskSize := "pd-standard|10|65536|GB / pd-balanced|10|65536|GB / pd-ssd|10|65536|GB / pd-extreme|500|65536|GB" - - gcpDiskInfo := webconsole.AvailableDiskType{} - gcpDiskInfo.ProviderID = "GCP" - gcpDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(gcpRootdiskType, " ", ""), "/") - gcpDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(gcpDiskType, " ", ""), "/") - gcpDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(gcpDiskSize, " ", ""), "/") - diskInfoMap["GCP"] = gcpDiskInfo - - aliRootdiskType := "cloud_essd / cloud_efficiency / cloud / cloud_ssd" - aliDiskType := "cloud / cloud_efficiency / cloud_ssd / cloud_essd" - aliDiskSize := "cloud|5|2000|GB / cloud_efficiency|20|32768|GB / cloud_ssd|20|32768|GB / cloud_essd_PL0|40|32768|GB / cloud_essd_PL1|20|32768|GB / cloud_essd_PL2|461|32768|GB / cloud_essd_PL3|1261|32768|GB" - - aliDiskInfo := webconsole.AvailableDiskType{} - aliDiskInfo.ProviderID = "ALIBABA" - aliDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(aliRootdiskType, " ", ""), "/") - aliDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(aliDiskType, " ", ""), "/") - aliDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(aliDiskSize, " ", ""), "/") - diskInfoMap["ALIBABA"] = aliDiskInfo - - tencentRootdiskType := "CLOUD_PREMIUM / CLOUD_SSD" - tencentDiskType := "CLOUD_PREMIUM / CLOUD_SSD / CLOUD_HSSD / CLOUD_BASIC / CLOUD_TSSD" - tencentDiskSize := "CLOUD_PREMIUM|10|32000|GB / CLOUD_SSD|20|32000|GB / CLOUD_HSSD|20|32000|GB / CLOUD_BASIC|10|32000|GB / CLOUD_TSSD|10|32000|GB" - - tencentDiskInfo := webconsole.AvailableDiskType{} - tencentDiskInfo.ProviderID = "TENCENT" - tencentDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(tencentRootdiskType, " ", ""), "/") - tencentDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(tencentDiskType, " ", ""), "/") - tencentDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(tencentDiskSize, " ", ""), "/") - diskInfoMap["TENCENT"] = tencentDiskInfo - - dataDiskInfoList := []webconsole.AvailableDiskType{} - if providerId != "" { - if regionName != "" { // TODO : Region에 따라 달라지면 보완할 것 - - } - providerDisk := diskInfoMap[strings.ToUpper(providerId)] - dataDiskInfoList = append(dataDiskInfoList, providerDisk) - } - - return dataDiskInfoList, nil -} diff --git a/mc_web_console_api/handler/McisHandler.go b/mc_web_console_api/handler/McisHandler.go deleted file mode 100644 index e96a9286..00000000 --- a/mc_web_console_api/handler/McisHandler.go +++ /dev/null @@ -1,2229 +0,0 @@ -package handler - -import ( - "encoding/json" - "fmt" - - fwmodels "mc_web_console_api/fwmodels" - "mc_web_console_api/fwmodels/tumblebug/mcir" - tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - "mc_web_console_api/fwmodels/tumblebug/mcis" - - //tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - "io" - "log" - "net/http" - - // "github.com/davecgh/go-spew/spew" - - // "os" - // fwmodels."mc_web_console_api/fwmodels. - - // spider "mc_web_console_api/fwmodels/spider" - // "mc_web_console_api/fwmodels/tumblebug" - - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - // tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - tbmcis "mc_web_console_api/fwmodels/tumblebug/mcis" - - webconsole "mc_web_console_api/fwmodels/webconsole" - - // "github.com/go-session/echo-session" - - // echosession "github.com/go-session/echo-session" - - util "mc_web_console_api/util" - - "github.com/gobuffalo/buffalo" -) - -//var MCISUrl = "http://15.165.16.67:1323" -//var SPiderUrl = "http://15.165.16.67:1024" - -// var SpiderUrl = os.Getenv("SPIDER_URL")// util.SPIDER -// var MCISUrl = os.Getenv("TUMBLE_URL")// util.TUMBLEBUG - -// MCIS 목록 조회 : option (id, simple, status) 추가할 것. -func GetMcisList(nameSpaceID string, optionParam string) ([]tbmcis.TbMcisInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - optionParamVal := "" - - if optionParam == "" { - optionParam = "status" - } - // install, init, cpus, cpum, memR, memW, fioR, fioW, dbR, dbW, rtt, mrtt, clean - //if optionParam != "" { - // optionParamVal = "?option=" + optionParam - //} - if optionParam == "all" { - optionParamVal = "" // all 은 optionParam값이 없는 경우임. - } else { - optionParamVal = "?option=" + optionParam - } - - // url := util.TUMBLEBUG + urlParam - url := util.TUMBLEBUG + urlParam + optionParamVal - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/mcis" - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - mcisList := map[string][]tbmcis.TbMcisInfo{} - returnStatus := fwmodels.WebStatus{} - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - //errorInfo := fwmodels.ErrorInfo{} - //json.NewDecoder(respBody).Decode(&errorInfo) - //fmt.Println("respStatus != 200 reason ", errorInfo) - //returnStatus.Message = errorInfo.Message - - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - json.NewDecoder(respBody).Decode(&mcisList) - fmt.Println(mcisList["mcis"]) - - returnStatus.StatusCode = respStatus - log.Println(respBody) - // util.DisplayResponse(resp) // 수신내용 확인 - - return mcisList["mcis"], returnStatus -} - -func GetMcisListByID(nameSpaceID string, filterKeyParam string, filterValParam string) ([]string, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - urlParam += "?option=id" - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - url := util.TUMBLEBUG + urlParam - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - mcisList := tbcommon.TbIdList{} - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&mcisList) - //spew.Dump(body) - fmt.Println(mcisList.IDList) - - return mcisList.IDList, fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetMcisListByOption(nameSpaceID string, optionParam string, filterKeyParam string, filterValParam string) ([]tbmcis.TbMcisInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - urlParam += "?option=" + optionParam - - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - url := util.TUMBLEBUG + urlParam - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - mcisList := map[string][]tbmcis.TbMcisInfo{} - returnStatus := fwmodels.WebStatus{} - - if respStatus != 200 && respStatus != 201 { - //spew.Dump(respBody) - log.Println(respBody) - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - json.NewDecoder(respBody).Decode(&mcisList) - fmt.Println(mcisList["mcis"]) - - returnStatus.StatusCode = respStatus - log.Println(respBody) - // util.DisplayResponse(resp) // 수신내용 확인 - - return mcisList["mcis"], returnStatus -} - -// 특정 MCIS 조회 -// action : status, suspend, resume, reboot, terminate, refine -// option : id, - -// [CONTROL] : common.SimpleMsg -// [DEFAULT] : mcis.TbMcisInfo -// [ID] : common.IdList -// [STATUS] : mcis.McisStatusInfo : status는 swagger에 정의되어 있지 않음. slack에 물어봐야 하나 -func GetMcisData(nameSpaceID string, mcisID string) (*tbmcis.TbMcisInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - - optionParamVal := "?option=default" - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam + optionParamVal - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - // defer body.Close() - mcisInfo := tbmcis.TbMcisInfo{} - if err != nil { - fmt.Println(err) - return &mcisInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return &mcisInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&mcisInfo) - fmt.Println(mcisInfo) - - // resultBody, err := ioutil.ReadAll(respBody) - // if err == nil { - // str := string(resultBody) - // println(str) - // } - // pbytes, _ := json.Marshal(respBody) - // fmt.Println(string(pbytes)) - - return &mcisInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetMcisDataByStatus(nameSpaceID string, mcisID string, optionParam string) (tbmcis.McisStatusInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - - optionParamVal := "?option=default" - // install, init, cpus, cpum, memR, memW, fioR, fioW, dbR, dbW, rtt, mrtt, clean - if optionParam != "" { - optionParamVal = "?option=" + optionParam - } - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam + optionParamVal - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - // defer body.Close() - //mcisStatusInfo := tbmcis.McisStatusInfo{} - //mcisStatusInfo := tbmcis.McisStatusInfo{} - mcisStatusInfo := map[string]tbmcis.McisStatusInfo{} - if err != nil { - fmt.Println(err) - failStatusInfo := tbmcis.McisStatusInfo{} - return failStatusInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - failStatusInfo := tbmcis.McisStatusInfo{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return failStatusInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&mcisStatusInfo) - fmt.Println(mcisStatusInfo) - - // resultBody, err := ioutil.ReadAll(respBody) - // if err == nil { - // str := string(resultBody) - // println(str) - // } - // pbytes, _ := json.Marshal(respBody) - // fmt.Println(string(pbytes)) - - return mcisStatusInfo["status"], fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetMcisDataByID(nameSpaceID string, mcisID string) (*tbcommon.TbIdList, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - - optionParamVal := "?option=id" - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam + optionParamVal - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - // defer body.Close() - vmIDList := tbcommon.TbIdList{} - if err != nil { - fmt.Println(err) - return &vmIDList, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return &vmIDList, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - //json.NewDecoder(respBody).Decode(&mcisStatusInfo) - //fmt.Println(mcisStatusInfo) - - return &vmIDList, fwmodels.WebStatus{StatusCode: respStatus} -} - -// MCIS 등록. VM도 함께 등록 -func RegMcis(nameSpaceID string, mcisInfo *tbmcis.TbMcisReq) (*tbmcis.TbMcisInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/mcis" - - pbytes, _ := json.Marshal(mcisInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnMcisInfo := tbmcis.TbMcisInfo{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return &returnMcisInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - //errorInfo := fwmodels.ErrorInfo{} - //json.NewDecoder(respBody).Decode(&errorInfo) - //fmt.Println("respStatus != 200 reason ", errorInfo) - //returnStatus.Message = errorInfo.Message - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return &returnMcisInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&returnMcisInfo) - fmt.Println(returnMcisInfo) - - returnStatus.StatusCode = respStatus - - // return respBody, respStatusCode - return &returnMcisInfo, returnStatus -} - -// MCIS 등록, channel 이용 : thread이긴 하나 ch를 통해 결과를 받은 후 처리되므로 다를 바가 없음. -// go routine으로 호출하므로 호출결과를 echo-session에 저장 -> web socket으로 front-end 에 전달 -func RegMcisByAsync(nameSpaceID string, mcisInfo *tbmcis.TbMcisReq, c buffalo.Context) { - var originalUrl = "/ns/{nsId}/mcis" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/mcis" - - //dataDisk empty처리 - // vms := mcisInfo.Vm - // for _, vm := range vms { - // dataDisks := vm.DataDiskIds - // var diskIds []string - // for _, dataDisk := range dataDisks { - // if dataDisk != "" { - // log.Println("dataDisk ", dataDisk) - // diskIds = append(diskIds, dataDisk) - // } - // } - // log.Println("diskIds ", diskIds) - // vm.DataDiskIds = diskIds - // } - // log.Println("vms ", vms) - // log.Println("mcisInfo ", mcisInfo) - - pbytes, _ := json.Marshal(mcisInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - //returnMcisInfo := tbmcis.TbMcisInfo{} - //returnStatus := fwmodels.WebStatus{} - - taskKey := nameSpaceID + "||" + "mcis" + "||" + mcisInfo.Name // TODO : 공통 function으로 뺄 것. - - if err != nil { - fmt.Println(err) - log.Println("RegMcisByAsync ", err) - // websocketMessage := websocket.WebSocketMessage{} - // websocketMessage.Status = "fail" - // websocketMessage.ProcessTime = time.Now() - // return &returnMcisInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - - // websocket으로 전달할 data set - StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, util.MCIS_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - - // socketDataStore, storedOk := store.Get("socketdata") // 만들고 들어오기 때문에 저장된 게 없을 수 없음.. - // if !storedOk { // 저장된 거 가져올 때 오류면 - // log.Println("get stored socketData error ") - // } else { - // socketDataMap := socketDataStore.(map[int64]websocket.WebSocketMessage) - // // socketDataMap := map[string]websocket.WebSocketMessage{} // 신규로 만들 필요 없음. 이미 있음(by taskKey) - - // // socketDataMap[taskKey] = websocketMessage// 해당 객체 갱신. - // // websocketMessage := socketDataMap[taskKey] - // websocketMessage := websocket.WebSocketMessage{} - // websocketMessage.TaskType = "mcis" - // websocketMessage.TaskKey = taskKey - // websocketMessage.Status = "fail" - // websocketMessage.ProcessTime = time.Now() - - // socketDataMap[time.Now().UnixNano()] = websocketMessage - // store.Set("socketdata", socketDataMap) - - // store.Save() - // log.Println("get stored socketData fail ") - // } - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - //util.DisplayResponse(resp) // 결과 확인용 - - //errorInfo := fwmodels.ErrorInfo{} - //json.NewDecoder(respBody).Decode(&errorInfo) - //fmt.Println("respStatus != 200 reason ", errorInfo) - //returnStatus.Message = errorInfo.Message - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("RegMcisByAsync ", failResultInfo) - StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, util.MCIS_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - } else { - - //if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - // errorInfo := fwmodels.ErrorInfo{} - // json.NewDecoder(respBody).Decode(&errorInfo) - // fmt.Println("respStatus != 200 reason ", errorInfo) - // returnStatus.Message = errorInfo.Message - //} else { - // json.NewDecoder(respBody).Decode(&returnMcisInfo) - // fmt.Println(returnMcisInfo) - //} - //returnStatus.StatusCode = respStatus - - // // TODO : 결과값 설정 확인할 것. - // socketDataStore, storedOk := store.Get("socketdata") - // if !storedOk { // 저장된 거 가져올 때 오류면 - // log.Println("get stored socketData error 2 ") - // } - // socketDataMap := socketDataStore.(map[int64]websocket.WebSocketMessage) - // websocketMessage := websocket.WebSocketMessage{} - // // websocketMessage := socketDataMap[time.Now().UnixNano()] - // // websocketMessage := socketDataMap[taskKey] - // websocketMessage.TaskType = "mcis" - // websocketMessage.TaskKey = taskKey - // websocketMessage.Status = "complete" - // websocketMessage.ProcessTime = time.Now() - // store.Set("socketdata", socketDataMap) - // store.Save() - // log.Println("set stored socketData complete ", respStatus) - // websocket으로 전달할 data set - - StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, util.MCIS_LIFECYCLE_CREATE, util.TASK_STATUS_COMPLETE, c) // session에 작업내용 저장 - } -} - -// MCIS에 VM 추가 등록 -func RegVm(nameSpaceID string, mcisID string, vmInfo *tbmcis.TbVmReq) (*tbmcis.TbVmInfo, fwmodels.WebStatus) { - // var mcisInfoID = mcisInfo.ID // path의 mcisID와 전송되는 parameter의 mcisID 비교용 - // var vmList = mcisInfo.Vms - - // 전송은 vm -> 수신 vm - returnVmInfo := tbmcis.TbVmInfo{} - returnStatus := fwmodels.WebStatus{} - - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/vm" // 1개만 추가할 때 - // if len(vmList) == 0 { - // return nil, fwmodels.WebStatus{StatusCode: 500, Message: "There no Vm info"} - // } - // fmt.Println("222") - // // mcisID 변조 체크 - // if mcisID != mcisInfoID { - // return nil, fwmodels.WebStatus{StatusCode: 500, Message: "MCIS Info not valid"} - // } - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - fmt.Println(originalUrl) - url := util.TUMBLEBUG + urlParam - // fmt.Println(vmList) - // pbytes, _ := json.Marshal(vmList) - fmt.Println(vmInfo) - pbytes, _ := json.Marshal(vmInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - fmt.Println("result ", err) - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - log.Println("RegVm ", err) - return &returnVmInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - //util.DisplayResponse(resp) // 결과 확인용 - - //errorInfo := fwmodels.ErrorInfo{} - //json.NewDecoder(respBody).Decode(&errorInfo) - //fmt.Println("respStatus != 200 reason ", errorInfo) - //returnStatus.Message = errorInfo.Message - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("RegVm ", failResultInfo) - return &returnVmInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&returnVmInfo) - //fmt.Println(returnVmInfo) - - returnStatus.StatusCode = respStatus - //fmt.Println(respBody) - //fmt.Println(respStatus) - - return &returnVmInfo, returnStatus -} - -// VM 등록 -func AsyncRegVm(nameSpaceID string, mcisID string, vmInfo *tbmcis.TbVmReq, c buffalo.Context) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/vm" // 1개만 추가할 때 - - //subGroupSize, err := strconv.ParseInt(vmInfo.SubGroupSize, 10, 64) - //if subGroupSize > 1 { // subGroupSize가 2개 이상일 때 - // originalUrl = "/ns/{nsId}/mcis/{mcisId}/subgroup" - //} - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - fmt.Println(originalUrl) - url := util.TUMBLEBUG + urlParam - // fmt.Println(vmList) - // pbytes, _ := json.Marshal(vmList) - fmt.Println(vmInfo) - pbytes, _ := json.Marshal(vmInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - //respBody := resp.Body - //respStatus := resp.StatusCode - fmt.Println("AsyncRegVm result ", err) - log.Println(resp) - - // // TODO : 결과값 설정 확인할 것. - // store := echosession.FromContext(c) - // socketDataStore, storedOk := store.Get("socketdata") - // if !storedOk { // 저장된 거 가져올 때 오류면 - // log.Println("get stored socketData error 2 ") - // } - // socketDataMap := socketDataStore.(map[string]websocket.WebSocketMessage) - // websocketMessage := socketDataMap[taskKey] - // // websocketMessage := socketDataMap[taskKey] - // websocketMessage.Status = "complete" - // websocketMessage.ProcessTime = time.Now() - // store.Set("socketdata", socketDataMap) - // store.Save() - // log.Println("set stored socketData complete ", respStatus) - - // returnVmInfo := tbmcis.TbVmInfo{} - // taskKey := nameSpaceID + "||" + "vm" + "||" + mcisID + "||" + vmInfo.Name - // if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - // //errorInfo := fwmodels.ErrorInfo{} - // //json.NewDecoder(respBody).Decode(&errorInfo) - // //fmt.Println("respStatus != 200 reason ", errorInfo) - - // failResultInfo := tbcommon.TbSimpleMsg{} - // json.NewDecoder(respBody).Decode(&failResultInfo) - // log.Println("RegVm ", failResultInfo) - // StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, util.VM_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - // } else { // return이 없으므로 else에서 처리 - // json.NewDecoder(respBody).Decode(&returnVmInfo) - // fmt.Println(returnVmInfo) - // StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, util.VM_LIFECYCLE_CREATE, util.TASK_STATUS_COMPLETE, c) // session에 작업내용 저장 - // } -} - -// MCIS에 VM 추가 등록 -func RegSubGroup(nameSpaceID string, mcisID string, subGroupInfo *tbmcis.TbVmReq) (*tbmcis.TbMcisInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/subgroup" // 여러개 추가할 때 - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(subGroupInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - // 전송은 vm이나 수신은 mcisInfo (mcis안에 vm목록이 있음.) - returnMcisInfo := tbmcis.TbMcisInfo{} - returnStatus := fwmodels.WebStatus{} - - if err != nil { - fmt.Println(err) - return &returnMcisInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - returnStatus.StatusCode = respStatus - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("RegSubGroup ", failResultInfo) - return &returnMcisInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&returnMcisInfo) - fmt.Println(returnMcisInfo) - - // return respBody, respStatusCode - return &returnMcisInfo, returnStatus -} - -// Create MCIS Dynamically from common spec and image -// async 로 만들 지 -func RegMcisDynamic(nameSpaceID string, mcisDynamicReq *tbmcis.TbMcisDynamicReq) (*tbmcis.TbMcisInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcisDynamic" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(mcisDynamicReq) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnMcisInfo := tbmcis.TbMcisInfo{} - returnStatus := fwmodels.WebStatus{} - - if err != nil { - fmt.Println(err) - return &returnMcisInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - returnStatus.StatusCode = respStatus - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("RegMcisDynamic ", failResultInfo) - return &returnMcisInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&returnMcisInfo) - fmt.Println(returnMcisInfo) - - return &returnMcisInfo, returnStatus -} - -func RegMcisDynamicByAsync(nameSpaceID string, mcisInfo *tbmcis.TbMcisDynamicReq, c buffalo.Context) { - var originalUrl = "/ns/{nsId}/mcisDynamic" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(mcisInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - respBody := resp.Body - respStatus := resp.StatusCode - - taskKey := nameSpaceID + "||" + "mcis" + "||" + mcisInfo.Name // TODO : 공통 function으로 뺄 것. - - if err != nil { - fmt.Println(err) - log.Println("RegMcisDynamicByAsync ", err) - - StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, util.MCIS_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("RegMcisDynamicByAsync ", failResultInfo) - StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, util.MCIS_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - } else { - - StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, util.MCIS_LIFECYCLE_CREATE, util.TASK_STATUS_COMPLETE, c) // session에 작업내용 저장 - } -} - -// Add VM dynamically from common spec and image -func RegVmDynamicByAsync(nameSpaceID string, mcisID string, vmReqInfo *tbmcis.TbVmDynamicReq, c buffalo.Context) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/vmDynamic" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(vmReqInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - respBody := resp.Body - respStatus := resp.StatusCode - - taskKey := nameSpaceID + "||" + "vm" + "||" + vmReqInfo.Name // TODO : 공통 function으로 뺄 것. - - if err != nil { - fmt.Println(err) - log.Println("RegVmDynamicByAsync ", err) - - StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, util.MCIS_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("RegVmDynamicByAsync ", failResultInfo) - StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, util.MCIS_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - } else { - - StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, util.MCIS_LIFECYCLE_CREATE, util.TASK_STATUS_COMPLETE, c) // session에 작업내용 저장 - } -} - -// Recommend MCIS plan (filter and priority) -// 실제로는 추천 image 목록 -// move to GetRecommendVmSpecList in resourceHandler - -/* -// Checkavaiable ConnectionConfig list for creating MCIS Dynamically - - 사용 가능한 connectionConfig 목록 조회 : 동적생성에서 사용 - 해당 spec들을 사용할 수 있는 conection 정보 목록 - ex) "commonSpec": ["aws-ap-northeast-2-t2-small","gcp-us-west1-g1-small"] - -> spec : "aws-ap-northeast-2-t2-small", connectionName : "conn-abc", region : "ap-northeast-2" ... -*/ -func GetMcisDynamicCheckList(mcisReq *tbmcis.McisConnectionConfigCandidatesReq) (*tbmcis.CheckMcisDynamicReqInfo, fwmodels.WebStatus) { - var originalUrl = "/mcisDynamicCheckRequest" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(mcisReq) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnVmSpecs := tbmcis.CheckMcisDynamicReqInfo{} - returnStatus := fwmodels.WebStatus{} - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - returnStatus.StatusCode = respStatus - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("RegMcisDynamic ", failResultInfo) - return &returnVmSpecs, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&returnVmSpecs) - fmt.Println(returnVmSpecs) - - return &returnVmSpecs, returnStatus -} - -//////////////// -// func GetVMStatus(vm_name string, connectionConfig string) string { -// url := SpiderUrl + "/vmstatus/" + vm_name + "?connection_name=" + connectionConfig -// // resp, err := http.Get(url) -// // if err != nil { -// // fmt.Println("request URL : ", url) -// // } - -// // defer resp.Body.Close() -// body := HttpGetHandler(url) -// defer body.Close() -// info := map[string]McisInfo{} -// json.NewDecoder(body).Decode(&info) -// fmt.Println("VM Status : ", info["status"].Status) -// return info["status"].Status - -// } - -// MCIS 목록에서 mcis 상태별 count map반환 -func GetMcisStatusCountMap(mcisInfo tbmcis.TbMcisInfo) map[string]int { - mcisStatusRunning := 0 - mcisStatusStopped := 0 - mcisStatusTerminated := 0 - - // log.Println(" mcisInfo ", index, mcisInfo) - mcisStatus := util.GetMcisStatus(mcisInfo.Status) - if mcisStatus == util.MCIS_STATUS_RUNNING { - mcisStatusRunning++ - } else if mcisStatus == util.MCIS_STATUS_TERMINATED { - mcisStatusTerminated++ - } else { - mcisStatusStopped++ - } - mcisStatusMap := make(map[string]int) - mcisStatusMap["RUNNING"] = mcisStatusRunning - mcisStatusMap["STOPPED"] = mcisStatusStopped - mcisStatusMap["TERMINATED"] = mcisStatusTerminated - mcisStatusMap["TOTAL"] = mcisStatusRunning + mcisStatusStopped + mcisStatusTerminated - // mcisStatusTotalMap[mcisInfo.ID] = mcisStatusMap - - return mcisStatusMap -} - -// MCIS의 vm별 statun와 vm 상태별 count -// key는 vmID + vmName, value는 vmStatus -func GetSimpleVmWithStatusCountMap(mcisInfo tbmcis.TbMcisInfo) ([]webconsole.VmSimpleInfo, map[string]int) { - // log.Println(" mcisInfo ", index, mcisInfo) - // vmStatusMap := make(map[string]int) - // vmStatusMap := map[string]string{} // vmName : vmStatus - - vmStatusCountMap := map[string]int{} - totalVmStatusCount := 0 - vmList := mcisInfo.Vm - var vmSimpleList []webconsole.VmSimpleInfo - for vmIndex, vmInfo := range vmList { - // log.Println(" vmInfo ", vmIndex, vmInfo) - vmStatus := util.GetVmStatus(vmInfo.Status) // lowercase로 변환 - - locationInfo := vmInfo.Location - vmLatitude := locationInfo.Latitude - vmLongitude := locationInfo.Longitude - - log.Println(locationInfo) - // - vmSimpleObj := webconsole.VmSimpleInfo{ - VmIndex: vmIndex + 1, - VmID: vmInfo.ID, - VmName: vmInfo.Name, - VmStatus: vmStatus, - Latitude: vmLatitude, - Longitude: vmLongitude, - - // export용 추가 - VmConnectionName: vmInfo.ConnectionName, - VmDescription: vmInfo.Description, - VmImageId: vmInfo.ImageID, - VmLabel: vmInfo.Label, - // TODO : securityGroupId는 []string 이므로 변환작업 필요 - VmSecurityGroupIds: vmInfo.SecurityGroupIDs, //"securityGroupIIds": [ { "nameId": "string", "systemId": "string" } ], - VmSpecId: vmInfo.SpecID, - VmSshKeyId: vmInfo.SshKeyID, - VmSubnetId: vmInfo.SubnetID, - VmVnetId: vmInfo.VNetID, - SubGroupSize: 1, //? 는 없는데.. subGroupId만 있는데... 1로 기본 setting - VmUserAccount: vmInfo.VmUserAccount, - VmUserPassword: vmInfo.VmUserPassword, - } - - vmSimpleList = append(vmSimpleList, vmSimpleObj) - - log.Println("vmStatus " + vmStatus + ", Status " + vmInfo.Status) - log.Println(vmInfo.SecurityGroupIDs) - vmStatusCount := 0 - val, exists := vmStatusCountMap[vmStatus] - if exists { - vmStatusCount = val + 1 - totalVmStatusCount += 1 - } else { - vmStatusCount = 1 - totalVmStatusCount += 1 - } - vmStatusCountMap[vmStatus] = vmStatusCount - } - - vmStatusCountMap["TOTAL"] = totalVmStatusCount - log.Println(vmStatusCountMap) - // vmStatusCountMap := make(map[string]int) - // UI에서 사칙연산이 되지 않아 controller에서 계산한 뒤 넘겨 줌. 아나면 function을 정의해서 넘겨야 함 - // vmStatusCountMap[util.VM_STATUS_RUNNING] = vmStatusRunning - // vmStatusCountMap[util.VM_STATUS_RESUMING] = vmStatusResuming - // vmStatusCountMap[util.VM_STATUS_INCLUDE] = vmStatusInclude - // vmStatusCountMap[util.VM_STATUS_SUSPENDED] = vmStatusSuspended - // vmStatusCountMap[util.VM_STATUS_TERMINATED] = vmStatusTerminated - // vmStatusCountMap[util.VM_STATUS_UNDEFINED] = vmStatusUndefined - // vmStatusCountMap[util.VM_STATUS_PARTIAL] = vmStatusPartial - // vmStatusCountMap[util.VM_STATUS_ETC] = vmStatusEtc - // log.Println("mcisInfo.ID ", mcisInfo.ID) - // mcisIdArr[mcisIndex] = mcisInfo.ID // 바로 넣으면 Runtime Error구만.. - // vmStatusArr[mcisIndex] = vmStatusCountMap - - // UI에서는 3가지로 통합하여 봄 - // vmStatusCountMap["RUNNING"] = vmStatusRunning - // vmStatusCountMap["STOPPED"] = vmStatusInclude + vmStatusSuspended + vmStatusUndefined + vmStatusPartial + vmStatusEtc - // vmStatusCountMap["TERMINATED"] = vmStatusTerminated - // vmStatusTotalMap[mcisInfo.ID] = vmStatusCountMap - // vmIdArr = append(vmIdArr, vmInfo.ID) - // vmStatusArr = append(vmStatusArr, vmStatusCountMap) - - // log.Println("mcisIndex ", mcisIndex) - - // vmStatusCountMap["RUNNING"] = vmStatusRunning - // vmStatusCountMap["STOPPED"] = vmStatusInclude + vmStatusSuspended + vmStatusUndefined + vmStatusPartial + vmStatusEtc - // vmStatusCountMap["TERMINATED"] = vmStatusTerminated - // vmStatusCountMap["TOTAL"] = vmStatusCountMap["RUNNING"] + vmStatusCountMap["STOPPED"] + vmStatusCountMap["TERMINATED"] - - return vmSimpleList, vmStatusCountMap - -} - -// MCIS별 connection count -func GetVmConnectionCountMap(mcisInfo tbmcis.TbMcisInfo) map[string]int { - // connectionCountTotal := 0 - // connectionCountByMcis := 0 - // vmCountTotal := 0 - // vmRunningCountByMcis := 0 - // vmStoppedCountByMcis := 0 - // vmTerminatedCountByMcis := 0 - // vmStatusUndefined := 0 - // vmStatusPartial := 0 - // vmStatusEtc := 0 - // vmStatusTerminated := 0 - - // log.Println(" mcisInfo ", index, mcisInfo) - // vmList := mcisInfo.VMs - // for vmIndex, vmInfo := range vmList { - // // log.Println(" vmInfo ", vmIndex, vmInfo) - // vmConnection := util.GetVmConnectionName(vmInfo.ConnectionName) - - // } - vmStatusMap := make(map[string]int) - // UI에서 사칙연산이 되지 않아 controller에서 계산한 뒤 넘겨 줌. - // vmStatusMap[util.VM_STATUS_RUNNING] = vmStatusRunning - // vmStatusMap[util.VM_STATUS_RESUMING] = vmStatusResuming - // vmStatusMap[util.VM_STATUS_INCLUDE] = vmStatusInclude - // vmStatusMap[util.VM_STATUS_SUSPENDED] = vmStatusSuspended - // vmStatusMap[util.VM_STATUS_TERMINATED] = vmStatusTerminated - // vmStatusMap[util.VM_STATUS_UNDEFINED] = vmStatusUndefined - // vmStatusMap[util.VM_STATUS_PARTIAL] = vmStatusPartial - // vmStatusMap[util.VM_STATUS_ETC] = vmStatusEtc - // log.Println("mcisInfo.ID ", mcisInfo.ID) - // mcisIdArr[mcisIndex] = mcisInfo.ID // 바로 넣으면 Runtime Error구만.. - // vmStatusArr[mcisIndex] = vmStatusMap - - // UI에서는 3가지로 통합하여 봄 - // vmStatusMap["RUNNING"] = vmStatusRunning - // vmStatusMap["STOPPED"] = vmStatusInclude + vmStatusSuspended + vmStatusUndefined + vmStatusPartial + vmStatusEtc - // vmStatusMap["TERMINATED"] = vmStatusTerminated - // vmStatusTotalMap[mcisInfo.ID] = vmStatusMap - // vmIdArr = append(vmIdArr, vmInfo.ID) - // vmStatusArr = append(vmStatusArr, vmStatusMap) - - // log.Println("mcisIndex ", mcisIndex) - - // vmStatusMap := make(map[string]int) - // vmStatusMap["RUNNING"] = vmStatusRunning - // vmStatusMap["STOPPED"] = vmStatusInclude + vmStatusSuspended + vmStatusUndefined + vmStatusPartial + vmStatusEtc - // vmStatusMap["TERMINATED"] = vmStatusTerminated - - return vmStatusMap - -} - -// 해당 MCIS의 VM 연결 수 -func GetVmConnectionCountByMcis(mcisInfo tbmcis.TbMcisInfo) map[string]int { - // log.Println(" mcisInfo ", index, mcisInfo) - vmList := mcisInfo.Vm - // mcisConnectionCountMap := make(map[string]int) - mcisConnectionCountMap := map[string]int{} - - totalConnectionCount := 0 - log.Println("GetVMConnectionCountByMcis map length ", len(mcisConnectionCountMap)) - for _, vmInfo := range vmList { - // log.Println(" vmInfo ", vmIndex, vmInfo) - locationInfo := vmInfo.Location - // cloudType := locationInfo.CloudType // CloudConnection - providerCount := 0 - val, exists := mcisConnectionCountMap[util.GetProviderName(locationInfo.CloudType)] - if exists { - providerCount = val + 1 - // totalConnectionCount += 1 // 이미 있는 경우에는 count추가필요없음 - } else { - providerCount = 1 - totalConnectionCount += 1 - } - // log.Println("GetProviderName ", locationInfo.CloudType) - mcisConnectionCountMap[util.GetProviderName(locationInfo.CloudType)] = providerCount - } - // log.Println("GetVMConnectionCountByMcis map length ", len(mcisConnectionCountMap)) - // log.Println("GetVMConnectionCountByMcis map ", mcisConnectionCountMap) - return mcisConnectionCountMap -} - -// MCIS의 특정 VM 조회 -// action : status, suspend, resume, reboot, terminate -func GetVMofMcisData(nameSpaceID string, mcisID string, vmID string) (*tbmcis.TbVmInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/vm/{vmId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{vmId}"] = vmID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/mcis/" + mcisID + "/vm/" + vmID - - // resp, err := util.CommonHttp(url, nil, http.MethodGet) - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - // defer body.Close() - vmInfo := tbmcis.TbVmInfo{} - if err != nil { - fmt.Println(err) - return &vmInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("GetVMofMcisData ", failResultInfo) - return &vmInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&vmInfo) - fmt.Println("respStatus = ", respStatus) - fmt.Println(vmInfo) - - return &vmInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// MCIS의 Status변경 -// LifeCycle 의 경우 요청에 대한 응답이 바로 오므로 asyncMethod를 따로 만들지 않음. 응답시간이 오래걸리는 경우 syncXXX 를 만들고 echo 를 같이 넘겨 결과 처리하도록 해야 함. -func McisLifeCycle(mcisLifeCycle *webconsole.McisLifeCycle) (*webconsole.McisLifeCycle, fwmodels.WebStatus) { - nameSpaceID := mcisLifeCycle.NameSpaceID - mcisID := mcisLifeCycle.McisID - action := mcisLifeCycle.Action - force := mcisLifeCycle.Force - - var originalUrl = "/ns/{nsId}/control/mcis/{mcisId}?action={action}&force={force}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{action}"] = action - paramMapper["{force}"] = force - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + mcisLifeCycle.NameSpaceID + "/mcis/" + mcisLifeCycle.McisID + "?action=" + mcisLifeCycle.LifeCycleType - //// var url = CommonURL+"/ns/"+nameSpace+"/mcis/"+mcis_id+"?action="+type - //pbytes, _ := json.Marshal(mcisLifeCycle) - //resp, err := util.CommonHttp(url, pbytes, http.MethodGet) // POST로 받기는 했으나 실제로는 Get으로 날아감. - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - resultMcisLifeCycle := webconsole.McisLifeCycle{} - if err != nil { - fmt.Println("McisLifeCycle err") - fmt.Println(err) - return &resultMcisLifeCycle, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - // respStatus := resp.Status - // log.Println("respStatusCode = ", respStatusCode) - // log.Println("respStatus = ", respStatus) - - // 응답에 생성한 객체값이 옴 - - if respStatus != 200 && respStatus != 201 { - // statusInfo := fwmodels.WebStatus{} - // fmt.Println("McisLifeCycle respStatus ", respStatus) - // fmt.Println(respBody) - // json.NewDecoder(respBody).Decode(statusInfo) - // fmt.Println(statusInfo) - // fmt.Println(statusInfo.Message) - - //errorInfo := fwmodels.ErrorInfo{} - //json.NewDecoder(respBody).Decode(&errorInfo) - //fmt.Println("respStatus != 200 reason ", errorInfo) - - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("McisLifeCycle ", failResultInfo) - return &resultMcisLifeCycle, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - - //return &resultMcisLifeCycle, fwmodels.WebStatus{StatusCode: respStatus, Message: errorInfo.Message} - } - // return body, err - // respBody := resp.Body - // respStatus := resp.StatusCode - // return respBody, respStatus - - json.NewDecoder(respBody).Decode(resultMcisLifeCycle) - fmt.Println(resultMcisLifeCycle) - - return &resultMcisLifeCycle, fwmodels.WebStatus{StatusCode: respStatus} - -} -func McisLifeCycleByAsync(mcisLifeCycle *webconsole.McisLifeCycle, c buffalo.Context) { - nameSpaceID := mcisLifeCycle.NameSpaceID - mcisID := mcisLifeCycle.McisID - action := mcisLifeCycle.Action - force := mcisLifeCycle.Force - - var originalUrl = "/ns/{nsId}/control/mcis/{mcisId}?action={action}&force={force}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{action}"] = action - paramMapper["{force}"] = force - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - log.Println("111") - taskKey := nameSpaceID + "||" + "mcis" + "||" + mcisLifeCycle.McisID - //////////// - if err != nil { - fmt.Println("McisLifeCycle err") - fmt.Println(err) - - // websocket으로 전달할 data set - StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, action, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - } - log.Println("222") - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("McisLifeCycle ", failResultInfo) - StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, action, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - } else { - resultMcisLifeCycle := webconsole.McisLifeCycle{} - json.NewDecoder(respBody).Decode(&resultMcisLifeCycle) - fmt.Println(resultMcisLifeCycle) - StoreWebsocketMessage(util.TASK_TYPE_MCIS, taskKey, action, util.TASK_STATUS_COMPLETE, c) // session에 작업내용 저장 - } - log.Println("333") -} - -// MCIS의 VM Status변경 : 요청에 대한 응답이 바로 오므로 async 만들지 않음 -func McisVmLifeCycle(vmLifeCycle *webconsole.VmLifeCycle) (*webconsole.VmLifeCycle, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/control/mcis/{mcisId}/vm/{vmId}?action={action}&force={force}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = vmLifeCycle.NameSpaceID - paramMapper["{mcisId}"] = vmLifeCycle.McisID - paramMapper["{vmId}"] = vmLifeCycle.VmID - paramMapper["{action}"] = vmLifeCycle.Action - paramMapper["{force}"] = vmLifeCycle.Force - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + vmLifeCycle.NameSpaceID + "/mcis/" + vmLifeCycle.McisID + "/vm/" + vmLifeCycle.VmID + "?action=" + vmLifeCycle.LifeCycleType - ///url = CommonURL+"/ns/"+nameSpace+"/mcis/"+mcis_id+"/vm/"+vm_id+"?action="+type - //pbytes, _ := json.Marshal(vmLifeCycle) - //resp, err := util.CommonHttp(url, pbytes, http.MethodGet) // POST로 받기는 했으나 실제로는 Get으로 날아감. - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - resultVmLifeCycle := webconsole.VmLifeCycle{} - if err != nil { - fmt.Println("McisVmLifeCycle err") - fmt.Println(err) - return &resultVmLifeCycle, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("McisVmLifeCycle ", failResultInfo) - return &resultVmLifeCycle, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - // 응답에 생성한 객체값이 옴 - json.NewDecoder(respBody).Decode(resultVmLifeCycle) - fmt.Println(resultVmLifeCycle) - - return &resultVmLifeCycle, fwmodels.WebStatus{StatusCode: respStatus} -} - -func McisVmLifeCycleByAsync(vmLifeCycle *webconsole.VmLifeCycle, c buffalo.Context) { - var originalUrl = "/ns/{nsId}/control/mcis/{mcisId}/vm/{vmId}?action={action}&force={force}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = vmLifeCycle.NameSpaceID - paramMapper["{mcisId}"] = vmLifeCycle.McisID - paramMapper["{vmId}"] = vmLifeCycle.VmID - paramMapper["{action}"] = vmLifeCycle.Action - paramMapper["{force}"] = vmLifeCycle.Force - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - resultVmLifeCycle := webconsole.VmLifeCycle{} - - taskKey := vmLifeCycle.NameSpaceID + "||" + "vm" + "||" + vmLifeCycle.McisID + "||" + vmLifeCycle.VmID - - if err != nil { - fmt.Println("McisVmLifeCycleByAsync err") - fmt.Println(err) - StoreWebsocketMessage(util.TASK_TYPE_VM, taskKey, vmLifeCycle.Action, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("McisVmLifeCycleByAsync ", failResultInfo) - StoreWebsocketMessage(util.TASK_TYPE_VM, taskKey, vmLifeCycle.Action, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - } - log.Println("McisVmLifeCycleByAsync 111") - // 응답에 생성한 객체값이 옴 - json.NewDecoder(respBody).Decode(resultVmLifeCycle) - log.Println("McisVmLifeCycleByAsync 222") - fmt.Println(resultVmLifeCycle) - StoreWebsocketMessage(util.TASK_TYPE_VM, taskKey, vmLifeCycle.Action, util.TASK_STATUS_COMPLETE, c) // session에 작업내용 저장 - //return &resultVmLifeCycle, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 벤치마크?? MCIS 조회. 근데 왜 결과는 resultarray지? -// TODO : 여러개 return되면 method이름을 xxxData -> xxxList 로 바꿀 것 -func GetBenchmarkMcisData(nameSpaceID string, mcisID string, hostIp string, optionParam string) ([]tbmcis.BenchmarkInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/benchmark/mcis/{mcisId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - optionParamVal := "" - // install, init, cpus, cpum, memR, memW, fioR, fioW, dbR, dbW, rtt, mrtt, clean - if optionParam != "" { - optionParamVal = "?option=" + optionParam - } - - // url := util.TUMBLEBUG + urlParam + "?option=" + optionParam - url := util.TUMBLEBUG + urlParam + optionParamVal - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/benchmark/mcis/" + mcisID - // /ns/{nsId}/benchmark/mcis/{mcisId} - pbytes, _ := json.Marshal(hostIp) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) // 조회이나 POST로 호출 - - respBody := resp.Body - respStatus := resp.StatusCode - // defer body.Close() - //resultBenchmarkInfos := []tbmcis.BenchmarkInfo{} - resultBenchmarkInfos := map[string][]tbmcis.BenchmarkInfo{} - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("GetBenchmarkMcisData ", failResultInfo) - return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&resultBenchmarkInfos) - fmt.Println(resultBenchmarkInfos) - //resultarray - return resultBenchmarkInfos["resultarray"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// List all MCISs -func GetBenchmarkAllMcisList(nameSpaceID string, mcisID string, hostIp string) ([]tbmcis.BenchmarkInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/benchmarkAll/mcis/{mcisId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/benchmark/mcis/" + mcisID - - pbytes, _ := json.Marshal(hostIp) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) // 조회이나 POST로 호출 - - respBody := resp.Body - respStatus := resp.StatusCode - - // defer body.Close() - //resultBenchmarkInfos := []tbmcis.BenchmarkInfo{} - //if err != nil { - // fmt.Println(err) - // return &resultBenchmarkInfos, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - //} - resultBenchmarkInfos := map[string][]tbmcis.BenchmarkInfo{} - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("GetBenchmarkAllMcisList ", failResultInfo) - return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&resultBenchmarkInfos) - fmt.Println(resultBenchmarkInfos) - - return resultBenchmarkInfos["resultarray"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// MCIS에 명령 내리기 -func CommandMcis(nameSpaceID string, mcisID string, mcisCommandInfo *tbmcis.McisCmdReq) (tbmcis.RestPostCmdMcisResponseWrapper, fwmodels.WebStatus) { - // webStatus := fwmodels.WebStatus{} - resultInfo := tbmcis.RestPostCmdMcisResponseWrapper{} - - var originalUrl = "/ns/{nsId}/cmd/mcis/{mcisId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(mcisCommandInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - if err != nil { - fmt.Println(err) - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - fmt.Println("resp : ", resp) - - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - //resultInfo := fwmodels.ResultInfo{} - log.Println("ResultStatusCode : ", respStatus) - - // 실패시 Message에 성공시 Result에 string으로 담겨 온다. - if respStatus != 200 && respStatus != 201 { - failResult := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResult) - log.Println("ResultMessage : " + failResult.Message) - - // return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: failResult.Message} - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResult.Message} - } - - log.Println(respBody) - // spew.Dump(respBody) - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - - // webStatus.StatusCode = respStatus - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 특정 VM에 명령내리기 -func CommandVmOfMcis(nameSpaceID string, mcisID string, vmID string, mcisCommandInfo *tbmcis.McisCmdReq) (tbmcis.RestPostCmdMcisVmResponse, fwmodels.WebStatus) { - // webStatus := fwmodels.WebStatus{} - resultInfo := tbmcis.RestPostCmdMcisVmResponse{} - - var originalUrl = "/ns/{nsId}/cmd/mcis/{mcisId}/vm/{vmId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{vmId}"] = vmID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/mcis/" + mcisID + "/vm/" + vmID - - pbytes, _ := json.Marshal(mcisCommandInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - if err != nil { - fmt.Println(err) - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - fmt.Println("resp : ", resp) - - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - // resultInfo := fwmodels.ResultInfo{} - - log.Println(respBody) - // spew.Dump(respBody) - - log.Println("ResultStatusCode : ", respStatus) - - // 실패시 Message에 성공시 Result에 string으로 담겨 온다. - if respStatus != 200 && respStatus != 201 { - // log.Println("ResultMessage : " + resultInfo.Message) - // return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - failResult := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResult) - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResult.Message} - - } - log.Println("ResultMessage : " + resultInfo.Result) - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - - // webStatus.StatusCode = respStatus - // webStatus.Message = resultInfo.Result - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Install the benchmark agent to specified MCIS -func InstallBenchmarkAgentToMcis(nameSpaceID string, mcisID string, mcisCommandInfo *tbmcis.McisCmdReq) (*tbmcis.RestPostCmdMcisResponseWrapper, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/installBenchmarkAgent/mcis/{mcisId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/mcis/" + mcisID - // /ns/{nsId}/install/mcis/{mcisId} - pbytes, _ := json.Marshal(mcisCommandInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnMcisCommandResult := tbmcis.RestPostCmdMcisResponseWrapper{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - returnStatus.StatusCode = respStatus - - if err != nil { - fmt.Println(err) - return &returnMcisCommandResult, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("InstallBenchmarkAgentToMcis ", failResultInfo) - return &returnMcisCommandResult, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&returnMcisCommandResult) - fmt.Println(returnMcisCommandResult) - - // return respBody, respStatusCode - return &returnMcisCommandResult, returnStatus - - // resultMcisCommandResult := tbmcis.AgentInstallContentWrapper{} - // if err != nil { - // fmt.Println(err) - // return &resultMcisCommandResult, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - // } - - // respBody := resp.Body - // respStatus := resp.StatusCode - - // // TODO : result는 resultArray인데.... - // json.NewDecoder(respBody).Decode(resultMcisCommandResult) - // fmt.Println(resultMcisCommandResult) - // return &resultMcisCommandResult, fwmodels.WebStatus{StatusCode: respStatus} - // if err != nil { - // fmt.Println(err) - // return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - // } - - // respBody := resp.Body - // respStatus := resp.StatusCode - - // return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Delete All MCISs -func DelAllMcis(nameSpaceID string, optionParam string) (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - optionParamVal := "" - - if optionParam != "" { - optionParamVal = "?option=" + optionParam - } - - // url := util.TUMBLEBUG + urlParam - url := util.TUMBLEBUG + urlParam + optionParamVal - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttpWithoutParam(url, http.MethodDelete) - - resultInfo := tbcommon.TbSimpleMsg{} - - if err != nil { - fmt.Println(err) - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("DelAllMcis ", failResultInfo) - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// MCIS 삭제. TODO : 해당 namespace의 MCIS만 삭제 가능... 창 두개에서 1개는 MCIS삭제, 1개는 namespace 변경이 있을 수 있으므로 UI에서 namespace도 넘겨서 비교할 것. -// optionParam은 없거나 force, terminate 가 있음. -func DelMcis(nameSpaceID string, mcisID string, optionParam string) (io.ReadCloser, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - optionParamVal := "" - // install, init, cpus, cpum, memR, memW, fioR, fioW, dbR, dbW, rtt, mrtt, clean - if optionParam != "" { - optionParamVal = "?option=" + optionParam - } - - // url := util.TUMBLEBUG + urlParam - url := util.TUMBLEBUG + urlParam + optionParamVal - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/mcis/" + mcisID - - if mcisID == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "MCIS ID is required"} - } - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("DelMcis ", failResultInfo) - return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// MCIS에 VM 생성. path에 mcisID가 있음. VMInfo에는 mcisID가 없음. -func RegVM(nameSpaceID string, mcisID string, vmInfo *tbmcis.TbVmInfo) (*tbmcis.TbVmInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/vm" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/mcis/" + mcisID + "/vm" - - pbytes, _ := json.Marshal(vmInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnVmInfo := tbmcis.TbVmInfo{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return &returnVmInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnVmInfo) - fmt.Println(returnVmInfo) - } - returnStatus.StatusCode = respStatus - - // return respBody, respStatusCode - return &returnVmInfo, returnStatus - - // resultVmResult := tumblebug.VmInfo{} - // if err != nil { - // fmt.Println(err) - // return &resultVmResult, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - // } - - // respBody := resp.Body - // respStatus := resp.StatusCode - - // // TODO : result는 resultArray인데.... - // json.NewDecoder(respBody).Decode(resultVmResult) - // fmt.Println(resultVmResult) - // return &resultVmResult, fwmodels.WebStatus{StatusCode: respStatus} - // if err != nil { - // fmt.Println(err) - // return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - // } - - // respBody := resp.Body - // respStatus := resp.StatusCode - - // return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -func DelVM(nameSpaceID string, mcisID string, vmID string) (io.ReadCloser, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/vm/{vmId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{vmId}"] = vmID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/mcis/" + mcisID + "/vm" - // /ns/{nsId}/mcis/{mcisId}/vm/{vmId} - - if vmID == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "vmID ID is required"} - } - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - // body, err := util.CommonHttpDelete(url, pbytes) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 특정 VM 조회 -func GetVmData(nameSpaceID string, mcisID string, vmID string) (*tbmcis.TbVmInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/vm/{vmId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{vmId}"] = vmID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/mcis/" + mcisID + "/vm/" + vmID - - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - // defer body.Close() - vmInfo := tbmcis.TbVmInfo{} - if err != nil { - fmt.Println(err) - return &vmInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("GetVmData ", failResultInfo) - return &vmInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&vmInfo) - fmt.Println(vmInfo) - - return &vmInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func RegCspVm(nameSpaceID string, mcisReq *tbmcis.TbMcisReq) (*tbmcis.TbMcisInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/registerCspVm" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(mcisReq) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnMcisInfo := tbmcis.TbMcisInfo{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return &returnMcisInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnMcisInfo) - fmt.Println(returnMcisInfo) - } - returnStatus.StatusCode = respStatus - - return &returnMcisInfo, returnStatus -} - -// Configure Cloud Adaptive Network (cb-network agent) to MCIS -func RegAdaptiveNetwork(nameSpaceID string, mcisID string, networkReq *tbmcis.NetworkReq) (*tbmcis.AgentInstallContentWrapper, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/network/mcis/{mcisId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(networkReq) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - agentInstallContentWrapper := tbmcis.AgentInstallContentWrapper{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return &agentInstallContentWrapper, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&agentInstallContentWrapper) - fmt.Println(agentInstallContentWrapper) - } - returnStatus.StatusCode = respStatus - - return &agentInstallContentWrapper, returnStatus -} - -// Inject Cloud Information For Cloud Adaptive Network -func UpdateAdaptiveNetwork(nameSpaceID string, mcisID string, networkReq *tbmcis.NetworkReq) (*tbmcis.AgentInstallContentWrapper, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/network/mcis/{mcisId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(networkReq) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - - agentInstallContentWrapper := tbmcis.AgentInstallContentWrapper{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return &agentInstallContentWrapper, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&agentInstallContentWrapper) - fmt.Println(agentInstallContentWrapper) - } - returnStatus.StatusCode = respStatus - - return &agentInstallContentWrapper, returnStatus -} - -// Get MCIS recommendation -// Deprecated at 0.4.5 -// func GetMcisRecommand(nameSpaceID string, mcisID string, mcisRecommandReq *tumblebug.McisRecommendReq) (*tumblebug.McisRecommendInfo, fwmodels.WebStatus) { -// var originalUrl = "/ns/{nsId}/mcis/recommend" - -// var paramMapper = make(map[string]string) -// paramMapper["{nsId}"] = nameSpaceID -// urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - -// url := util.TUMBLEBUG + urlParam -// // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/mcis/recommend" - -// pbytes, _ := json.Marshal(mcisRecommandReq) -// resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - -// returnMcisRecommendInfo := tumblebug.McisRecommendInfo{} -// returnStatus := fwmodels.WebStatus{} - -// respBody := resp.Body -// respStatus := resp.StatusCode - -// if err != nil { -// fmt.Println(err) -// return &returnMcisRecommendInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} -// } -// log.Println(respBody) -// spew.Dump(respBody) -// if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set -// errorInfo := fwmodels.ErrorInfo{} -// json.NewDecoder(respBody).Decode(&errorInfo) -// fmt.Println("respStatus != 200 reason ", errorInfo) -// returnStatus.Message = errorInfo.Message -// } else { -// json.NewDecoder(respBody).Decode(&returnMcisRecommendInfo) -// fmt.Println(returnMcisRecommendInfo) -// } -// returnStatus.StatusCode = respStatus - -// return &returnMcisRecommendInfo, returnStatus - -// // mcisRecommandesult := tumblebug.McisRecommendInfo{} -// // if err != nil { -// // fmt.Println(err) -// // return &mcisRecommandesult, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} -// // } - -// // respBody := resp.Body -// // respStatus := resp.StatusCode - -// // // TODO : result는 resultArray인데.... -// // json.NewDecoder(respBody).Decode(mcisRecommandesult) -// // fmt.Println(mcisRecommandesult) -// // return &mcisRecommandesult, fwmodels.WebStatus{StatusCode: respStatus} -// // if err != nil { -// // fmt.Println(err) -// // return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} -// // } - -// // respBody := resp.Body -// // respStatus := resp.StatusCode - -// // return respBody, fwmodels.WebStatus{StatusCode: respStatus} -// } - -// VM 에 DataDisk를 Attach 또는 Detach ( commane로 구분 ) -func AttachDetachDataDiskToVM(nameSpaceID string, mcisID string, vmID string, optionParam string, attachDetachDataDiskReq *tbmcir.TbAttachDetachDataDiskReq) (*tbmcis.TbVmInfo, fwmodels.WebStatus) { - //var originalUrl = "/ns/{nsId}/mcis/{mcisId}/vm/{vmId}/{command}" - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/vm/{vmId}/dataDisk" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{vmId}"] = vmID - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - urlParam += "?option=" + optionParam - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(attachDetachDataDiskReq) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - - vmInfo := tbmcis.TbVmInfo{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return &vmInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&vmInfo) - fmt.Println(vmInfo) - } - returnStatus.StatusCode = respStatus - - return &vmInfo, returnStatus -} - -// AsyncAttachDetachDataDiskToVM -func AsyncAttachDetachDataDiskToVM(nameSpaceID string, mcisID string, vmID string, optionParam string, attachDetachDataDiskReq *tbmcir.TbAttachDetachDataDiskReq, c buffalo.Context) { - taskKey := nameSpaceID + "||" + "vm" + "||" + vmID - lifecycle := "attache" - if optionParam == "detach" { - lifecycle = util.DISK_LIFECYCLE_DETACHED - } - _, respStatus := AttachDetachDataDiskToVM(nameSpaceID, mcisID, vmID, optionParam, attachDetachDataDiskReq) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - StoreWebsocketMessage(util.TASK_TYPE_VM, taskKey, lifecycle, util.TASK_STATUS_FAIL, c) - } else { - StoreWebsocketMessage(util.TASK_TYPE_VM, taskKey, lifecycle, util.TASK_STATUS_COMPLETE, c) - } -} - -// VM에서 Attach 가능한 DataDisk 목록 : Get available dataDisks for a VM -func GetAvailableDataDiskListForVM(nameSpaceID string, mcisID string, vmID string) ([]mcir.TbDataDiskInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/vm/{vmId}/dataDisk" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{vmId}"] = vmID - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - availableDiskList := mcir.RestGetAvailableDataDisksResponse{} - json.NewDecoder(respBody).Decode(&availableDiskList) - - log.Println(respBody) - - return availableDiskList.DataDisk, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Mcis에 SubGroup 목록 조회 -func McisSubGroupList(nameSpaceID string, mcisID string) (*tbcommon.TbIdList, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/subgroup" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - // defer body.Close() - idList := tbcommon.TbIdList{} - if err != nil { - fmt.Println(err) - return &idList, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("McisSubGroupList ", failResultInfo) - return &idList, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&idList) - fmt.Println(idList) - - return &idList, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Mcis의 SubGroup 내 VM 목록조회. ID 만 반환 -func VmIdListBySubgroupID(nameSpaceID string, mcisID string, subGroupID string) (*tbcommon.TbIdList, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/subgroup/{subgroupId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{subgroupId}"] = subGroupID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - // defer body.Close() - idList := tbcommon.TbIdList{} - if err != nil { - fmt.Println(err) - return &idList, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("McisSubGroupList ", failResultInfo) - return &idList, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&idList) - fmt.Println(idList) - - return &idList, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Mcis의 SubGroup 내 VM 목록조회 -// TODO : return형태가 다를 수 있으므로 조회 결과대로 수정할 것. -func SubGroupVmListByOption(nameSpaceID string, mcisID string, subGroupID string, optionParam string) (*tbcommon.TbIdList, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/subgroup/{subgroupId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{subgroupId}"] = subGroupID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - optionParamVal := "" - - if optionParam != "" { - optionParamVal = "?option=" + optionParam - } - - // url := util.TUMBLEBUG + urlParam - url := util.TUMBLEBUG + urlParam + optionParamVal - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - // defer body.Close() - idList := tbcommon.TbIdList{} - if err != nil { - fmt.Println(err) - return &idList, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("McisSubGroupList ", failResultInfo) - return &idList, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&idList) - fmt.Println(idList) - - return &idList, fwmodels.WebStatus{StatusCode: respStatus} -} - -// SubGroup의 vm개수 조정 -func ScaleOutSubGroup(nameSpaceID string, mcisID string, subGroupID string, subGroupScaleOutReq *mcis.TbScaleOutSubGroupReq) (*mcis.TbMcisInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/subgroup/{subgroupId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{subgroupId}"] = subGroupID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(subGroupScaleOutReq) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnMcisInfo := tbmcis.TbMcisInfo{} - returnStatus := fwmodels.WebStatus{} - - if err != nil { - fmt.Println(err) - return &returnMcisInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - returnStatus.StatusCode = respStatus - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("RegMcisDynamic ", failResultInfo) - return &returnMcisInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&returnMcisInfo) - fmt.Println(returnMcisInfo) - - return &returnMcisInfo, returnStatus -} - -// VM의 snapshot 생성 -func RegVmSnapshot(nameSpaceID string, mcisID string, vmID string, vmSnapshotReq *mcis.TbVmSnapshotReq) (*mcis.TbCustomImageInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/vm/{vmId}/snapshot" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{vmId}"] = vmID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(vmSnapshotReq) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnCustomImageInfo := tbmcis.TbCustomImageInfo{} - returnStatus := fwmodels.WebStatus{} - - if err != nil { - fmt.Println(err) - return &returnCustomImageInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - returnStatus.StatusCode = respStatus - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("RegSnapshot ", failResultInfo) - return &returnCustomImageInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&returnCustomImageInfo) - fmt.Println(returnCustomImageInfo) - - return &returnCustomImageInfo, returnStatus -} - -func AsyncRegVmSnapshot(nameSpaceID string, mcisID string, vmID string, vmSnapshotReq *mcis.TbVmSnapshotReq, c buffalo.Context) { - taskKey := nameSpaceID + "||" + "vm" + "||" + vmID - lifecycle := "snapshot" - - _, respStatus := RegVmSnapshot(nameSpaceID, mcisID, vmID, vmSnapshotReq) - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - StoreWebsocketMessage(util.TASK_TYPE_VM, taskKey, lifecycle, util.TASK_STATUS_FAIL, c) - } else { - StoreWebsocketMessage(util.TASK_TYPE_VM, taskKey, lifecycle, util.TASK_STATUS_COMPLETE, c) - } -} diff --git a/mc_web_console_api/handler/McisPolicyHandler.go b/mc_web_console_api/handler/McisPolicyHandler.go deleted file mode 100644 index b55064fd..00000000 --- a/mc_web_console_api/handler/McisPolicyHandler.go +++ /dev/null @@ -1,180 +0,0 @@ -package handler - -import ( - "encoding/json" - "fmt" - "io" - "log" - "net/http" - - // "os" - - // "mc_web_console_api/fwmodels/spider" - - fwmodels "mc_web_console_api/fwmodels" - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - - // tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - tbmcis "mc_web_console_api/fwmodels/tumblebug/mcis" - - util "mc_web_console_api/util" -) - -// List all MCIS Policys -func GetMcisPolicyList(nameSpaceID string) ([]tbmcis.RestGetAllMcisPolicyResponse, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/policy/mcis" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/policy/mcis" - - // resp, err := util.CommonHttp(url, nil, http.MethodGet) - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - mcisPolicyList := map[string][]tbmcis.RestGetAllMcisPolicyResponse{} - json.NewDecoder(respBody).Decode(&mcisPolicyList) - fmt.Println(mcisPolicyList["mcisPolicy"]) - log.Println(respBody) - util.DisplayResponse(resp) // 수신내용 확인 - - return mcisPolicyList["mcisPolicy"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// Get McisPolish Data -func GetMcisPolicyInfoData(nameSpaceID string, mcisID string) (*tbmcis.RestGetAllMcisPolicyResponse, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/policy/mcis/{mcisId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/policy/mcis/" + mcisID - - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - // defer body.Close() - mcisPolicyInfo := tbmcis.RestGetAllMcisPolicyResponse{} - if err != nil { - fmt.Println(err) - return &mcisPolicyInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&mcisPolicyInfo) - fmt.Println(mcisPolicyInfo) - - return &mcisPolicyInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func RegMcisPolicy(nameSpaceID string, mcisID string, mcisPolicyInfo *tbmcis.McisPolicyInfo) (*tbmcis.McisPolicyInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/policy/mcis/{mcisId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/policy/mcis" + mcisID - - pbytes, _ := json.Marshal(mcisPolicyInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnMcisPolicyInfo := tbmcis.McisPolicyInfo{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return &returnMcisPolicyInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnMcisPolicyInfo) - fmt.Println(returnMcisPolicyInfo) - } - returnStatus.StatusCode = respStatus - - return &returnMcisPolicyInfo, returnStatus -} - -func DelAllMcisPolicy(nameSpaceID string) (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/policy/mcis" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - resp, err := util.CommonHttpWithoutParam(url, http.MethodDelete) - - resultInfo := tbcommon.TbSimpleMsg{} - - if err != nil { - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func DelMcisPolicy(nameSpaceID string, mcisID string) (io.ReadCloser, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/policy/mcis/{mcisId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/policy/mcis/" + mcisID - - if mcisID == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "MCIS ID is required"} - } - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} diff --git a/mc_web_console_api/handler/McksHandler.go b/mc_web_console_api/handler/McksHandler.go deleted file mode 100644 index 143af50a..00000000 --- a/mc_web_console_api/handler/McksHandler.go +++ /dev/null @@ -1,510 +0,0 @@ -package handler - -import ( - // "io" - // "os" - "encoding/json" - "fmt" - "log" - "net/http" - - fwmodels "mc_web_console_api/fwmodels" - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - - // spider "mc_web_console_api/fwmodels/spider" - "mc_web_console_api/fwmodels/ladybug" - // "mc_web_console_api/fwmodels/tumblebug" - - util "mc_web_console_api/util" - - "github.com/gobuffalo/buffalo" -) - -// Health Check -func GetHealthy() fwmodels.WebStatus { - var originalUrl = "/healthy" - urlParam := util.MappingUrlParameter(originalUrl, nil) - url := util.MCKS + urlParam - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - if err != nil { - fmt.Println(err) - return fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - result := "" - json.NewDecoder(respBody).Decode(&result) - log.Println(result) - - return fwmodels.WebStatus{StatusCode: respStatus, Message: result} -} - -// Cluster 목록 조회 -func GetClusterList(nameSpaceID string) ([]ladybug.ClusterInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{namespace}/clusters" - - var paramMapper = make(map[string]string) - paramMapper["{namespace}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.MCKS + urlParam - // url := util.MCKS + "/ns/" + nameSpaceID + "/clusters" - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - // 원래는 items 와 kind 가 들어오는데 - // kind에는 clusterlist 라는 것만 있고 실제로는 items 에 cluster 정보들이 있음. - // 그래서 굳이 kind까지 처리하지 않고 item만 return - clusterList := map[string][]ladybug.ClusterInfo{} - json.NewDecoder(respBody).Decode(&clusterList) - fmt.Println(clusterList["items"]) - log.Println(respBody) - // util.DisplayResponse(resp) // 수신내용 확인 - - return clusterList["items"], fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetClusterListByID(nameSpaceID string) ([]string, fwmodels.WebStatus) { - var originalUrl = "/ns/{namespace}/clusters" - - var paramMapper = make(map[string]string) - paramMapper["{namespace}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.MCKS + urlParam + "?option=id" - // url := util.MCKS + "/ns/" + nameSpaceID + "/clusters" - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - // 원래는 items 와 kind 가 들어오는데 - // kind에는 clusterlist 라는 것만 있고 실제로는 items 에 cluster 정보들이 있음. - // 그래서 굳이 kind까지 처리하지 않고 item만 return - clusterIdList := []string{} - json.NewDecoder(respBody).Decode(&clusterIdList) - log.Println(respBody) - // util.DisplayResponse(resp) // 수신내용 확인 - - return clusterIdList, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 특정 Cluster 조회 -func GetClusterData(nameSpaceID string, cluster string) (*ladybug.ClusterInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{namespace}/clusters/{cluster}" - - var paramMapper = make(map[string]string) - paramMapper["{namespace}"] = nameSpaceID - paramMapper["{cluster}"] = cluster - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.MCKS + urlParam - - // resp, err := util.CommonHttp(url, nil, http.MethodGet) - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - // defer body.Close() - clusterInfo := ladybug.ClusterInfo{} - if err != nil { - fmt.Println(err) - return &clusterInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&clusterInfo) - fmt.Println(clusterInfo) - - return &clusterInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Cluster 생성 -func RegCluster(nameSpaceID string, clusterReq *ladybug.ClusterRegReq) (*ladybug.ClusterInfo, fwmodels.WebStatus) { - - var originalUrl = "/ns/{namespace}/clusters" - - var paramMapper = make(map[string]string) - paramMapper["{namespace}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.MCKS + urlParam - - pbytes, _ := json.Marshal(clusterReq) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnClusterInfo := ladybug.ClusterInfo{} - returnStatus := fwmodels.WebStatus{} - - if err != nil { - fmt.Println(err) - return &returnClusterInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnClusterInfo) - fmt.Println(returnClusterInfo) - } - returnStatus.StatusCode = respStatus - - return &returnClusterInfo, returnStatus -} - -// Cluster 생성 -func RegClusterByAsync(nameSpaceID string, clusterReq *ladybug.ClusterRegReq, c buffalo.Context) { - - var originalUrl = "/ns/{namespace}/clusters" - - var paramMapper = make(map[string]string) - paramMapper["{namespace}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.MCKS + urlParam - - pbytes, _ := json.Marshal(clusterReq) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - taskKey := nameSpaceID + "||" + "mcks" + "||" + clusterReq.Name // TODO : 공통 function으로 뺄 것. - - if err != nil { - fmt.Println(err) - StoreWebsocketMessage(util.TASK_TYPE_MCKS, taskKey, util.MCKS_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - //errorInfo := fwmodels.ErrorInfo{} - //json.NewDecoder(respBody).Decode(&errorInfo) - //fmt.Println("respStatus != 200 reason ", errorInfo) - //returnStatus.Message = errorInfo.Message - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("RegMcksByAsync ", failResultInfo) - StoreWebsocketMessage(util.TASK_TYPE_MCKS, taskKey, util.MCKS_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - - } else { - returnClusterInfo := ladybug.ClusterInfo{} - json.NewDecoder(respBody).Decode(&returnClusterInfo) - fmt.Println(returnClusterInfo) - StoreWebsocketMessage(util.TASK_TYPE_MCKS, taskKey, util.MCKS_LIFECYCLE_CREATE, util.TASK_STATUS_COMPLETE, c) // session에 작업내용 저장 - } - -} - -// Cluster 삭제 -func DelClusters(nameSpaceID string, clusterName string) (*ladybug.StatusInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{namespace}/clusters/{cluster}" - - var paramMapper = make(map[string]string) - paramMapper["{namespace}"] = nameSpaceID - paramMapper["{cluster}"] = clusterName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.MCKS + urlParam - - if clusterName == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "cluster is required"} - } - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - statusInfo := ladybug.StatusInfo{} - if err != nil { - fmt.Println("delCluster ", err) - return &statusInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&statusInfo) - fmt.Println(statusInfo) - - if respStatus != 200 && respStatus != 201 { - fmt.Println(respBody) - return &statusInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: statusInfo.Message} - } - return &statusInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Cluster 삭제 비동기 처리 -func DelClusterByAsync(nameSpaceID string, clusterName string, c buffalo.Context) { - var originalUrl = "/ns/{namespace}/clusters/{cluster}" - - var paramMapper = make(map[string]string) - paramMapper["{namespace}"] = nameSpaceID - paramMapper["{cluster}"] = clusterName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.MCKS + urlParam - - //if clusterName == "" { - // return nil, fwmodels.WebStatus{StatusCode: 500, Message: "cluster is required"} - //} - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - - //statusInfo := ladybug.StatusInfo{} - //if err != nil { - // fmt.Println("delCluster ", err) - // return &statusInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - //} - - //respBody := resp.Body - //respStatus := resp.StatusCode - // - //json.NewDecoder(respBody).Decode(&statusInfo) - //fmt.Println(statusInfo) - - taskKey := nameSpaceID + "||" + "mcks" + "||" + clusterName - - if err != nil { - fmt.Println(err) - StoreWebsocketMessage(util.TASK_TYPE_MCKS, taskKey, util.MCKS_LIFECYCLE_DELETE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - //errorInfo := fwmodels.ErrorInfo{} - //json.NewDecoder(respBody).Decode(&errorInfo) - //fmt.Println("respStatus != 200 reason ", errorInfo) - //returnStatus.Message = errorInfo.Message - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("DelMcksByAsync ", failResultInfo) - StoreWebsocketMessage(util.TASK_TYPE_MCKS, taskKey, util.MCKS_LIFECYCLE_DELETE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - - } else { - returnClusterInfo := ladybug.ClusterInfo{} - json.NewDecoder(respBody).Decode(&returnClusterInfo) - fmt.Println(returnClusterInfo) - StoreWebsocketMessage(util.TASK_TYPE_MCKS, taskKey, util.MCKS_LIFECYCLE_DELETE, util.TASK_STATUS_COMPLETE, c) // session에 작업내용 저장 - } -} - -// MCKS의 상태값 숫자로 표시 -func GetMcksStatusCountMap(clusterList []ladybug.ClusterInfo) map[string]int { - mcksStatusRunning := 0 - mcksStatusStopped := 0 - mcksStatusTerminated := 0 - - for _, clusterInfo := range clusterList { - mcksStatus := util.GetMcksStatus(clusterInfo.Status.Phase) - if mcksStatus == util.MCKS_STATUS_RUNNING { - mcksStatusRunning++ - } else if mcksStatus == util.MCKS_STATUS_TERMINATED { - mcksStatusTerminated++ - } else { - mcksStatusStopped++ - } - } - - mcksStatusMap := make(map[string]int) - mcksStatusMap["RUNNING"] = mcksStatusRunning - mcksStatusMap["STOPPED"] = mcksStatusStopped - mcksStatusMap["TERMINATED"] = mcksStatusTerminated - mcksStatusMap["TOTAL"] = mcksStatusRunning + mcksStatusStopped + mcksStatusTerminated - - return mcksStatusMap -} - -// Node의 간단정보(credential 제외) + kind별 node 갯수 return -func GetSimpleNodeCountMap(cluster ladybug.ClusterInfo) ([]ladybug.NodeSimpleInfo, map[string]int) { - var nodeSimpleList []ladybug.NodeSimpleInfo - nodeRoleCountMap := map[string]int{} - for nodeIndex, nodeInfo := range cluster.Nodes { - nodeSimpleObj := ladybug.NodeSimpleInfo{ - NodeIndex: nodeIndex, - NodeName: nodeInfo.Name, - NodeKind: nodeInfo.Kind, // Node냐 cluster냐 - NodeCsp: nodeInfo.Csp, - NodePublicIp: nodeInfo.PublicIp, - NodeRole: nodeInfo.Role, // Control-plane냐, Worker냐 - NodeSpec: nodeInfo.Spec, - } - nodeSimpleList = append(nodeSimpleList, nodeSimpleObj) - - _, exists := nodeRoleCountMap[nodeInfo.Role] - if !exists { - nodeRoleCountMap[nodeInfo.Role] = 0 - } - nodeRoleCountMap[nodeInfo.Role] += 1 - } - log.Println("nodeRoleCountMap") - log.Println(nodeRoleCountMap) - return nodeSimpleList, nodeRoleCountMap -} - -//////// - -// Node 목록 조회 -func GetNodeList(nameSpaceID string, clusterName string) (ladybug.NodeList, fwmodels.WebStatus) { - var originalUrl = "/ns/{namespace}/clusters/{cluster}/nodes" - - var paramMapper = make(map[string]string) - paramMapper["{namespace}"] = nameSpaceID - paramMapper["{cluster}"] = clusterName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.MCKS + urlParam - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - nodeList := ladybug.NodeList{} // 이름은 List이나 1개의 객체임 - if err != nil { - fmt.Println(err) - return nodeList, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&nodeList) - fmt.Println(nodeList) - log.Println(respBody) - // util.DisplayResponse(resp) // 수신내용 확인 - - return nodeList, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 특정 Cluster 조회 -func GetNodeData(nameSpaceID string, clusterName string, node string) (*ladybug.NodeInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{namespace}/clusters/{cluster}/nodes/{node}" - - var paramMapper = make(map[string]string) - paramMapper["{namespace}"] = nameSpaceID - paramMapper["{cluster}"] = clusterName - paramMapper["{node}"] = node - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.MCKS + urlParam - - // resp, err := util.CommonHttp(url, nil, http.MethodGet) - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - // defer body.Close() - nodeInfo := ladybug.NodeInfo{} - if err != nil { - fmt.Println(err) - return &nodeInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&nodeInfo) - fmt.Println(nodeInfo) - - return &nodeInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Node 생성 -func RegNode(nameSpaceID string, clusterName string, nodeRegReq *ladybug.NodeRegReq) (*ladybug.NodeInfo, fwmodels.WebStatus) { - - var originalUrl = "/ns/{namespace}/clusters/{cluster}/nodes" - - var paramMapper = make(map[string]string) - paramMapper["{namespace}"] = nameSpaceID - paramMapper["{cluster}"] = clusterName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.MCKS + urlParam - - pbytes, _ := json.Marshal(nodeRegReq) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnNodeInfo := ladybug.NodeInfo{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return &returnNodeInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnNodeInfo) - fmt.Println(returnNodeInfo) - } - returnStatus.StatusCode = respStatus - - return &returnNodeInfo, returnStatus -} - -// Node 삭제 -func DelNode(nameSpaceID string, clusterName string, node string) (*ladybug.StatusInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{namespace}/clusters/{cluster}/nodes/{node}" - - var paramMapper = make(map[string]string) - paramMapper["{namespace}"] = nameSpaceID - paramMapper["{cluster}"] = clusterName - paramMapper["{node}"] = node - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.MCKS + urlParam - - if clusterName == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "cluster is required"} - } - if node == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "node is required"} - } - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - statusInfo := ladybug.StatusInfo{} - if err != nil { - fmt.Println(err) - return &statusInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&statusInfo) - fmt.Println(statusInfo) - - return &statusInfo, fwmodels.WebStatus{StatusCode: respStatus} -} diff --git a/mc_web_console_api/handler/MonitoringHandler.go b/mc_web_console_api/handler/MonitoringHandler.go deleted file mode 100644 index 42e64ebf..00000000 --- a/mc_web_console_api/handler/MonitoringHandler.go +++ /dev/null @@ -1,995 +0,0 @@ -package handler - -import ( - "encoding/json" - "fmt" - "io" - - // "io/ioutil" - "log" - "net/http" - - // "strconv" - // "os" - - // "mc_web_console_api/fwmodels/spider" - fwmodels "mc_web_console_api/fwmodels" - "mc_web_console_api/fwmodels/dragonfly" - - // "mc_web_console_api/fwmodels/tumblebug" - // tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - // tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - tbmcis "mc_web_console_api/fwmodels/tumblebug/mcis" - - util "mc_web_console_api/util" -) - -// VM 에 모니터링 Agent 설치 -// /ns/{nsId}/monitoring/install/mcis/{mcisId} -func RegBenchmarkAgentInVm(nameSpaceID string, mcisID string, vmMonitoringAgentReg *tbmcis.McisCmdReq) (*tbmcis.AgentInstallContentWrapper, fwmodels.WebStatus) { - fmt.Println("RegBenchmarkAgentInVm ************ : ") - var originalUrl = "/ns/{nsId}/monitoring/install/mcis/{mcisId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/monitoring/install/mcis/" - - pbytes, _ := json.Marshal(vmMonitoringAgentReg) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - vmMonitoringAgentInfo := tbmcis.AgentInstallContentWrapper{} - if err != nil { - fmt.Println(err) - return &vmMonitoringAgentInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - returnStatus := fwmodels.WebStatus{} - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&vmMonitoringAgentInfo) - fmt.Println(vmMonitoringAgentInfo) - } - returnStatus.StatusCode = respStatus - - return &vmMonitoringAgentInfo, returnStatus -} - -func RegMonitoringAgentInVm(nameSpaceID string, mcisID string, vmMonitoringAgentReg *dragonfly.VmMonitoringInstallReg) (*fwmodels.WebStatus, fwmodels.WebStatus) { - fmt.Println("RegMonitoringAgentInVm ************ : ") - //var originalUrl = "/agent/install" - var originalUrl = "/agent" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - // Command string `json:"command"` - // PublicIp string `json:"ip"` - // McisID string `json:"mcis_id"` - // SshKey string `json:"ssh_key"` - // UserName string `json:"user_name"` - // VmID string `json:"vm_id"` - url := util.DRAGONFLY + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/monitoring/install/mcis/" - // _ = writer.WriteField("mcis_id", "7e3130a0-a811-47b8-a82c-b155267edef5") - // _ = writer.WriteField("vm_id", "c9f01668-4db4-4521-8d54-14501e31d2c7") - // _ = writer.WriteField("public_ip", "0.0.0.0") - // _ = writer.WriteField("user_name", "cbuser") - // _ = writer.WriteField("ssh_key", "-----BEGIN RSA PRIVATE KEY-----\nMIIJKAIBAAKCAgEAyUpusHpMZmFnxMjnugHi2n3CejwQqfXpZJnD6DE5//v399JS\nozfEZsf01Nni/uNrJV6tdJOGIUt7lxuAY7D5rOdp6UrxXs0SBLi4ssJUfEwfUuOg\nhnDv2aBQ4lmrCSEyNNhWX86e+Jbypk55RbQGJUydWre0r9QOxATqZUIfKNv3SvDn\nqbje2iBpVAj463udT7Sce4bX3d2BhLwl/bHUSONV9hAqJo9D6LZQ/eQwd6ZL0mw1\nG5HVP3qiQ8Px0kUtsMQ00TM5w2Z1w3rdP3rkGHjccNukBJ+7EdW/xdiQOhFcTT5X\n6bRcsnGMB4pwZHyKtjPOG3c+/J8jc6b7yIAo+dYVc2ZaZEZ3I2MP7hkitHpQwUqh\nJpv9inByO6Ezu/5afD2anoRHm74oaFojpNU5hYe/wtCN5TESlPyS0NM0WkIRGULX\na+DbV6WfsgSanOYY32m/KZwTQdM9bRrsBRzTVYgKnEZ8xR9d38mkORVUumkOLs5U\nEJMv0GCOA9umdlS44RuEk+sfZHKuTRiAfEEXREPwB/SBOR1Ob13Ox23vxFFQKE8n\nu+q1TL2DrVbpLfcRMTXqM1UoEPRSHd4pup+pAYRBooVMxAKW5YIiNi8yLdGNXghy\ndZgWFSFnhc875fWdqIjRffeAzqo2Jf6597omwdrmJ5EDY+PMi4nz/rWDRtsCAwEA\nAQKCAgBQupViGeqCNRaVCa5GH3OIBV/1/hkA0StluXWkrfmA/OEadzPFWhxezFsY\n8rnjV/ok5q/STUhCGi/bDqCTWusHuVf0xKXBS6WqVxtcNiwEHdOCPuCmiqznLzDB\nVw0NgE7OeuVJT2jack+m+1oP5n+AfhWtyHei/P1fCEmpirdMf8vSNoPywb4+5TjZ\nBzAt4UnaKamIsS/qP2guf/cMpEFraiGTqi/9fv/RWS1qZhY6JmvKXLN/9yD7cIeb\nff6CQlRszIQSUuUbxP/+AkyxpOvOFMr0SGKjqBwyrvNWueA+KbBHGnXPuRJkTr3G\nWHNzGa/YGzbSNSUB1CE3xQS+CQhlVIvGRLvmzftpsugaxOuy117vFNDXFeTrQWMK\nzSfDC+zd+Cyq4h0NjnRcHNhip0hjVdLGK1U2ag42asOHhIAkGJ+QAsKt2qN6Au1o\nhSCjlsEy8W+qsA1fLMqIiAcXQ9TqcopC2F/qzDz7fMBJ7bqSo1zKMQzt2B9pcu8J\n7QJ+F0srW05ea0SXzm2Z4tWuGsMAxy6TX5yrm8HgGwyAfv6kVpyPRvX3kkYKNngm\nZ0sNfG9/Sl16c6CMHNTsbWINFUFKpMFP+lkw8OW95Cnd757FB3Y/kzEe2/XWzYuZ\nHBapViIKVTHGr0neev2X4ZxlOtuHvE5fXyaqBrxu4jbTmzbXoQKCAQEA2ovN7D/K\nXblCbAKsu9s6OAJdEp4y/cMkbm5vwhEi/ld4ypxuQH4MUpqh1NS4o9nQziKaOkKz\nAUuxlcUMH/upR4MIxTQrGlYnT41+bdwnZ21IDnZiGHE+Pfp3hw0vdZv25AeQSk/L\nyIvHvmowBzaD0LjXcZWFGb6B57SG8tMTtw5mlWGk2/HkeN1IA6aluwNMMCDKsoV6\ncP+uQDNGDuXPbDOvjpzwfyH1aJHQCyj/vMCQNbaRqOL45UyMk2/6lmMtRwBMS+CC\n4ofRpiLOYEEICaI9uFSodRWiTfrkJMQiIIvTjDIXD9omHiq0/zEe5UqlkiefcVPp\nW/5NOYGReiq1/wKCAQEA68mW+q/Hqu5Y0coS1lcGSXUXyJbhUdRQhNsfDBufPI4U\nMQJxulckA8mDf9ljVTm7/SX7m5ki2Aj1UDBGCzu5bOcyUtWfAS39+koJBVZkb8e9\n+nITIu+Wycz6diX7EHteuVDLrUuuiUZZtkJYtO+TYG7EMiuuD05OVRSUmJrdR9Or\n5mMzENzTH7+4Dh2AL6fwp2SLY2jqa4EXPsF0tuZku/YyC8yIaIVjmVV5aQijCDQ6\n/OH3I2qdNRMc8AswhI4ZXyZosbeRthBp+rMkZQtcV0GCAh0Uf8uh0QZCm9xD9f8C\nnYXEoUkZtvoTnv3GQVp36t8Q0PfkXl5CYRDa/6MHJQKCAQEAijMsRgBU1Q3I/gp2\n9th8KVz9RD+8GRKk4ByAGaXCjjn8TYu8gJX07uuP+MmH9T1ROHlTNBJnpiMaqo4P\ny83Vzz4Cdso1k5L1iu38DDbSyCmoDlU4VSKPbJwNp95jq6iz6KEL0qJBSJFz/2qg\n8n67vmqU+uPFZnE9LqvPRpDJ/9Fgd4hmuxttEi1EU+K3HNrJ/AlQhLG5qulUZI7H\n97XFhDPvCW0e/BYaXUUP3W7Qwai3yO+pjrXxFPdiUf3W5fDTefmrRbQ0sFGY9sk9\n3kphbc4l34HRgTDsEQnd6Y4J0rD5Vsd6I/Ecd6kkCdgjJHYe25yoy/53LFBUv0+7\nEhkeOwKCAQAwEs/3mLNLBIGTdHHWxbOAcqFAwpJ6DqHEFLEF1PPocsdnHqp1ZaLw\nKrvm6zm3fKf5ey8LkHNsPJdXnCAL1kd+Dr1R6kAbC3eG+mVQc0bTC5SOZYfFTbge\nuO4v/Jptx9mOSwzb7lxNnMxZvrk7WsVfmfXijMlWUY7jBekuHBUVufCIbp1QyNU6\n2en65sTl8oW8e2F4CUISXSWSI/tZ9yt+rzmQ8ki1lsyxzJ2ObrZey9djC+dJj0ky\nMw1pW76uqBJANiKOaXEJ/9q7xJ6dA232VGLfb3Jog+ogJfiaspQgqbesykNG5xKZ\nHe+2MOOlG37rokNZd9FV9D3wcHFWQbUJAoIBAAVHUFgrxLbkBu+2j4YLCncm/FGA\nDdsPpuCxdTn4hV8sELu4ZpbEDC/f2OUh4klO74ZeFpIulkMAZCpD0fLwPkcV2UWw\nQeL8B32dKiq0gogk+2WZX7s/s2WLx8o0OYnmbQcOcxwJrOZyMPOW8m85NbmUjhd1\n+l87QeXc9ahAt6XHy3Q2j4iuOQzaj0g5PU7LhjvcKHNxVXe27Ms9DM2C4q6eRxvy\n/aLFlcKIi7Y3lkkjam4tW7YtLrudybft6Tqn0FZy/cIFfAEP+jk6IjGobgXdc9uy\nzKNCIXom5Q/0M6ChQU5AskQd0xNgoBU+9nYXXXwxnIVusW6we008Qje1ktY=\n-----END RSA PRIVATE KEY-----\n") - // _ = writer.WriteField("cspType", "test") - - // pbytes, _ := json.Marshal(vmMonitoringAgentReg) - // fmt.Println(string(pbytes)) - // resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - fmt.Println("RegMonitoringAgentInVm : ", url) - - fmt.Println(vmMonitoringAgentReg) - - urlValues, convertErr := util.StructToMapByJson(vmMonitoringAgentReg) - if convertErr != nil { - log.Println(convertErr) - } - //vmMonitoringInstallReg - fmt.Println(urlValues) - //resp, err := util.CommonHttpFormData(url, urlValues, http.MethodPost) - pbytes, _ := json.Marshal(vmMonitoringAgentReg) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - webStatus := fwmodels.WebStatus{} - if err != nil { - fmt.Println(err) - return &webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return &fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return &webStatus, fwmodels.WebStatus{StatusCode: respStatus} -} - -// TB 호출을 통한 Get Monitoring Data -func GetMcisMonitoringDurationInfo(nameSpaceID string, mcisID string, metric string) (*tbmcis.MonResultSimpleResponse, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/monitoring/mcis/{mcisId}/metric/{metric}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{metric}"] = metric - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/monitoring/mcis/" + mcisID + "/metric/" + metric - - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - // defer body.Close() - vmMonitoringResult := tbmcis.MonResultSimpleResponse{} - if err != nil { - fmt.Println(err) - return &vmMonitoringResult, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&vmMonitoringResult) - fmt.Println(vmMonitoringResult) - - return &vmMonitoringResult, fwmodels.WebStatus{StatusCode: respStatus} -} - -// VM monitoring -// Get vm monitoring info -// 멀티 클라우드 인프라 VM 모니터링 정보 조회 -func GetVmMonitoring(vmMonitoring *dragonfly.VmMonitoringReq) (map[string]interface{}, fwmodels.WebStatus) { - //func GetVmMonitoring(vmMonitoring *dragonfly.VmMonitoring) (*dragonfly.VmMonitoringInfo, fwmodels.WebStatus) { - nameSpaceID := vmMonitoring.NameSpaceID - mcisID := vmMonitoring.McisID - vmID := vmMonitoring.VmID - metric := vmMonitoring.Metric - periodType := vmMonitoring.PeriodType - statisticsCriteria := vmMonitoring.StatisticsCriteria - duration := vmMonitoring.Duration - - var originalUrl = "/ns/:ns_id/mcis/:mcis_id/vm/:vm_id/metric/:metric_name/info?periodType={periodType}&statisticsCriteria={statisticsCriteria}&duration={duration}" - //{{ip}}:{{port}}/dragonfly/ns/:ns_id/mcis/:mcis_id/vm/:vm_id/metric/:metric_name/info?periodType=m&statisticsCriteria=last&duration=5m - var paramMapper = make(map[string]string) - paramMapper[":ns_id"] = nameSpaceID - paramMapper[":mcis_id"] = mcisID - paramMapper[":vm_id"] = vmID - paramMapper[":metric_name"] = metric - paramMapper["{periodType}"] = periodType - paramMapper["{statisticsCriteria}"] = statisticsCriteria - paramMapper["{duration}"] = duration - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.DRAGONFLY + urlParam - - //"/mcis/"+mcis_id+"/vm/"+vm_id+"/metric/"+metric+"/info?periodType="+periodType+"&statisticsCriteria="+statisticsCriteria+"&duration="+duration; - // urlParam := "periodType=" + vmMonitoring.PeriodType + "&statisticsCriteria=" + vmMonitoring.StatisticsCriteria + "&duration=" + vmMonitoring.Duration - // url := util.DRAGONFLY + "/ns/" + vmMonitoring.NameSpaceID + "/mcis/" + vmMonitoring.McisID + "/vm/" + vmMonitoring.VmID + "/metric/" + vmMonitoring.Metric + "/info?" + urlParam - - // resp, err := util.CommonHttp(url, nil, http.MethodGet) - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - // defer body.Close() - //vmMonitoringInfo := dragonfly.VmMonitoringInfo{} - vmMonitoringInfo := make(map[string]interface{}) - if err != nil { - fmt.Println(err) - return vmMonitoringInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - respBody := resp.Body - respStatus := resp.StatusCode - fmt.Println("respStatus", respStatus) - if metric == "cpu" { - vmMonitoringInfoByCpu := dragonfly.VmMonitoringInfoByCpu{} - json.NewDecoder(respBody).Decode(&vmMonitoringInfoByCpu) - - //vmMonitoringInfo.ValuesByCpu = vmMonitoringInfoByCpu - vmMonitoringInfo[metric] = vmMonitoringInfoByCpu - } else if metric == "memory" { - vmMonitoringInfoByMemory := dragonfly.VmMonitoringInfoByMemory{} - json.NewDecoder(respBody).Decode(&vmMonitoringInfoByMemory) - - //vmMonitoringInfo.ValuesByMemory = vmMonitoringInfoByMemory - vmMonitoringInfo[metric] = vmMonitoringInfoByMemory - } else if metric == "disk" { - vmMonitoringInfoByDisk := dragonfly.VmMonitoringInfoByDisk{} - json.NewDecoder(respBody).Decode(&vmMonitoringInfoByDisk) - - //vmMonitoringInfo.ValuesByDisk = vmMonitoringInfoByDisk - vmMonitoringInfo[metric] = vmMonitoringInfoByDisk - } else if metric == "network" { - vmMonitoringInfoByNetwork := dragonfly.VmMonitoringInfoByNetwork{} - json.NewDecoder(respBody).Decode(&vmMonitoringInfoByNetwork) - - //vmMonitoringInfo.ValuesByNetwork = vmMonitoringInfoByNetwork - vmMonitoringInfo[metric] = vmMonitoringInfoByNetwork - } - - //json.NewDecoder(respBody).Decode(&vmMonitoringInfo) - //fmt.Println(vmMonitoringInfo) - - //return &vmMonitoringInfo, fwmodels.WebStatus{StatusCode: respStatus} - return vmMonitoringInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 멀티 클라우드 인프라 MCIS 온디맨드 모니터링 정보 조회 -// Get MCIS on-demand monitoring metric info -// TODO : 현재 DF의 function 정의가 잘못되어 있음. mcis 모니터링인데 vm과 vm ip를 넣어서 보냄( vm 모티너링과 param이 동일함.) 수정요청할 것 -func GetMcisOnDemandMonitoringMetricInfo(mcisVmMonitoring *dragonfly.McisMonitoringOnDemandInfoReq) (*dragonfly.McisMonitoringOnDemandInfo, fwmodels.WebStatus) { - - var originalUrl = "/ns/:ns_id/mcis/:mcis_id/mcis_metric/:metric_name/mcis-monitoring-info" - //{{ip}}:{{port}}/dragonfly/ns/:ns_id/mcis/:mcis_id/vm/:vm_id/agent_ip/:agent_ip/mcis_metric/:metric_name/mcis-monitoring-info - var paramMapper = make(map[string]string) - paramMapper[":ns_id"] = mcisVmMonitoring.NameSpaceID - paramMapper[":mcis_id"] = mcisVmMonitoring.McisID - paramMapper[":metric_name"] = mcisVmMonitoring.MetricName // 메트릭 정보 ( "InitDB" | "ResetDB" | "CpuM" | "CpuS" | "MemR" | "MemW" | "FioW" | "FioR" | "DBW" | DBR" | "Rtt" | "Mrtt" ) - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.DRAGONFLY + urlParam - - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - // defer body.Close() - mcisMonitoringInfo := dragonfly.McisMonitoringOnDemandInfo{} - if err != nil { - fmt.Println(err) - return &mcisMonitoringInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&mcisMonitoringInfo) - fmt.Println(mcisMonitoringInfo) - - return &mcisMonitoringInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 멀티 클라우드 인프라 VM 온디맨드 모니터링 정보 조회 -// Get vm on-demand monitoring metric info GetMcisVmOnDemandMonitoringMetricInfo -func GetMcisVmOnDemandMonitoringMetricInfo(vmMonitoring *dragonfly.VmMonitoringReq) (*dragonfly.VmMonitoringOnDemandInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/:ns_id/mcis/:mcis_id/vm/:vm_id/agent_ip/:agent_ip/metric/:metric_name/ondemand-monitoring-info" - // {{ip}}:{{port}}/dragonfly/ns/:ns_id/mcis/:mcis_id/vm/:vm_id/agent_ip/:agent_ip/metric/:metric_name/ondemand-monitoring-info - var paramMapper = make(map[string]string) - paramMapper[":ns_id"] = vmMonitoring.NameSpaceID - paramMapper[":mcis_id"] = vmMonitoring.McisID - paramMapper[":vm_id"] = vmMonitoring.VmID - paramMapper[":agent_ip"] = vmMonitoring.AgentIp - paramMapper[":metric_name"] = vmMonitoring.Metric - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.DRAGONFLY + urlParam - - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - // defer body.Close() - vmMonitoringInfo := dragonfly.VmMonitoringOnDemandInfo{} - if err != nil { - fmt.Println(err) - return &vmMonitoringInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&vmMonitoringInfo) - fmt.Println(vmMonitoringInfo) - - return &vmMonitoringInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetMcisVmOnDemandNetworkPacketInfo(vmMonitoring *dragonfly.VmMonitoringReq) (*dragonfly.VmMonitoringOnDemandInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/:ns_id/mcis/:mcis_id/vm/:vm_id/watchtime/:watch_time/mcis-networkpacket-info" - - var paramMapper = make(map[string]string) - paramMapper[":ns_id"] = vmMonitoring.NameSpaceID - paramMapper[":mcis_id"] = vmMonitoring.McisID - paramMapper[":vm_id"] = vmMonitoring.VmID - paramMapper[":watch_time"] = vmMonitoring.WatchTime - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.DRAGONFLY + urlParam - - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - // defer body.Close() - vmMonitoringInfo := dragonfly.VmMonitoringOnDemandInfo{} - if err != nil { - fmt.Println(err) - return &vmMonitoringInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&vmMonitoringInfo) - fmt.Println(vmMonitoringInfo) - - return &vmMonitoringInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetMcisVmOnDemandProcessUsageInfo(vmMonitoring *dragonfly.VmMonitoringReq) (*dragonfly.VmMonitoringOnDemandInfo, fwmodels.WebStatus) { - var originalUrl = "/agent_ip/:agent_ip/mcis-process-info" - - var paramMapper = make(map[string]string) - paramMapper[":agent_ip"] = vmMonitoring.AgentIp - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.DRAGONFLY + urlParam - - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - // defer body.Close() - vmMonitoringInfo := dragonfly.VmMonitoringOnDemandInfo{} - if err != nil { - fmt.Println(err) - return &vmMonitoringInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&vmMonitoringInfo) - fmt.Println(vmMonitoringInfo) - - return &vmMonitoringInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 모니터링 정책 조회 -// Get monitoring config -func GetMonitoringConfig() (*dragonfly.MonitoringConfig, fwmodels.WebStatus) { - var originalUrl = "/config" - //{{ip}}:{{port}}/dragonfly/config - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.DRAGONFLY + urlParam - // url := util.DRAGONFLY + "/config" - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - // defer body.Close() - monitoringConfig := dragonfly.MonitoringConfig{} - - if err != nil { - log.Println(err) - return &monitoringConfig, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&monitoringConfig) - log.Println(monitoringConfig) - - return &monitoringConfig, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 모니터링 정책 설정 -func PutMonigoringConfig(monitoringConfigReg *dragonfly.MonitoringConfigReg) (*dragonfly.MonitoringConfig, fwmodels.WebStatus) { - var originalUrl = "/config" - //{{ip}}:{{port}}/dragonfly/config - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.DRAGONFLY + urlParam - // url := util.DRAGONFLY + "/config" - - fmt.Println("Update MonigoringConfigReg : ", url) - - //fmt.Println(monitoringConfigReg) - // - urlValues, convertErr := util.StructToMapByJson(monitoringConfigReg) - if convertErr != nil { - log.Println(convertErr) - } - - fmt.Println(urlValues) - //resp, err := util.CommonHttpFormData(url, urlValues, http.MethodPut) - pbytes, _ := json.Marshal(monitoringConfigReg) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - resultMonitoringConfig := dragonfly.MonitoringConfig{} - - if err != nil { - log.Println("-----") - fmt.Println(err) - log.Println("-----1111") - fmt.Println(err.Error()) - log.Println("-----222") - return &resultMonitoringConfig, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - log.Println("respStatusCode = ", resp.StatusCode) - log.Println("respStatus = ", resp.Status) - if respStatus != 200 && respStatus != 201 { - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println(errorInfo) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: errorInfo.Message} - } - - // 응답에 생성한 객체값이 옴 - json.NewDecoder(respBody).Decode(&resultMonitoringConfig) - fmt.Println(resultMonitoringConfig) - // return respBody, respStatusCode - return &resultMonitoringConfig, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 모니터링 정책 초기화 -func ResetMonigoringConfig(monitoringConfig *dragonfly.MonitoringConfig) (*dragonfly.MonitoringConfig, fwmodels.WebStatus) { - var originalUrl = "/config/reset" - //{{ip}}:{{port}}/dragonfly/config/reset - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.DRAGONFLY + urlParam - // url := util.DRAGONFLY + "/config/reset" - - resp, err := util.CommonHttp(url, nil, http.MethodPut) - resultMonitoringConfig := dragonfly.MonitoringConfig{} - if err != nil { - log.Println("-----") - fmt.Println(err) - log.Println("-----1111") - fmt.Println(err.Error()) - log.Println("-----222") - return &resultMonitoringConfig, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - log.Println("respStatusCode = ", resp.StatusCode) - log.Println("respStatus = ", resp.Status) - if respStatus != 200 && respStatus != 201 { - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println(errorInfo) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: errorInfo.Message} - } - - // 응답에 생성한 객체값이 옴 - json.NewDecoder(respBody).Decode(&resultMonitoringConfig) - fmt.Println(resultMonitoringConfig) - // return respBody, respStatusCode - return &resultMonitoringConfig, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Install agent to vm -// 모니터링 에이전트 설치 : 위에 RegMonitoringAgentInVm 와 뭐가 다른거지? -func InstallAgentToVm(nameSpaceID string, vmMonitoringInstallReg *dragonfly.VmMonitoringInstallReg) (*dragonfly.VmMonitoringInstallReg, fwmodels.WebStatus) { - //var originalUrl = "/agent/install" - var originalUrl = "/agent/install" - //{{ip}}:{{port}}/dragonfly/agent/install - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.DRAGONFLY + urlParam - // url := util.DRAGONFLY + "/agent/install/" - - pbytes, _ := json.Marshal(vmMonitoringInstallReg) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnVmMonitoringInstallReg := dragonfly.VmMonitoringInstallReg{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return &returnVmMonitoringInstallReg, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnVmMonitoringInstallReg) - fmt.Println(returnVmMonitoringInstallReg) - } - returnStatus.StatusCode = respStatus - - return &returnVmMonitoringInstallReg, returnStatus -} - -// 모니터링 에이전트 제거 -// Uninstall agent to vm -func UnInstallAgentToVm(nameSpaceID string, vmMonitoringInstallReg *dragonfly.VmMonitoringInstallReg) (*dragonfly.VmMonitoringInstallReg, fwmodels.WebStatus) { - //var originalUrl = "/agent/uninstall" - var originalUrl = "/agent" - //{{ip}}:{{port}}/dragonfly/agent/uninstall - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.DRAGONFLY + urlParam - // url := util.DRAGONFLY + "/agent/uninstall/" - - pbytes, _ := json.Marshal(vmMonitoringInstallReg) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnVmMonitoringInstallReg := dragonfly.VmMonitoringInstallReg{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return &returnVmMonitoringInstallReg, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnVmMonitoringInstallReg) - fmt.Println(returnVmMonitoringInstallReg) - } - returnStatus.StatusCode = respStatus - - return &returnVmMonitoringInstallReg, returnStatus -} - -// 알람 목록 조회 -// List monitoring alert -func GetMonitoringAlertList() ([]dragonfly.VmMonitoringAlertInfo, fwmodels.WebStatus) { - fmt.Print("#########GetMonitoringAlertList############") - var originalUrl = "/alert/tasks" - // {{ip}}:{{port}}/dragonfly/alert/tasks - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.DRAGONFLY + urlParam - // url := util.DRAGONFLY + "/alert/tasks" - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - // vmMonitoringAlertInfoList := dragonfly.VmMonitoringAlertInfo{} - vmMonitoringAlertInfoList := []dragonfly.VmMonitoringAlertInfo{} - if err != nil { - fmt.Println(err) - return vmMonitoringAlertInfoList, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - //vmMonitoringAlertInfoList := []dragonfly.VmMonitoringAlertInfo{} - json.NewDecoder(respBody).Decode(&vmMonitoringAlertInfoList) - - // robots, _ := ioutil.ReadAll(resp.Body) - // log.Println(fmt.Print(string(robots))) - - // json.NewDecoder(respBody).Decode(&vmMonitoringAlertInfoList) - // fmt.Println(vmMonitoringAlertInfoList) - - return vmMonitoringAlertInfoList, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 알람 조회 -// monitoring alert -func GetMonitoringAlertData(taskName string) (dragonfly.VmMonitoringAlertInfo, fwmodels.WebStatus) { - var originalUrl = "/alert/task/:task_name" - // {{ip}}:{{port}}/dragonfly/alert/task/:task_name - var paramMapper = make(map[string]string) - paramMapper[":task_name"] = taskName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.DRAGONFLY + urlParam - // url := util.DRAGONFLY + "/alert/task/" + taskName - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - vmMonitoringAlertInfo := dragonfly.VmMonitoringAlertInfo{} - if err != nil { - fmt.Println(err) - return vmMonitoringAlertInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&vmMonitoringAlertInfo) - - return vmMonitoringAlertInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 알람 생성 -// Create Monitoring Alert -func RegMonitoringAlert(vmMonitoringAlertInfo *dragonfly.VmMonitoringAlertInfo) (*dragonfly.VmMonitoringAlertInfo, fwmodels.WebStatus) { - fmt.Println("RegMonitoringAlert ************ : ") - var originalUrl = "/alert/task" - // {{ip}}:{{port}}/dragonfly/alert/task - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.DRAGONFLY + urlParam - // url := util.DRAGONFLY + "/alert/task" - - pbytes, _ := json.Marshal(vmMonitoringAlertInfo) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - //urlValues, convertErr := util.StructToMapByJson(vmMonitoringAlertInfo) - //if convertErr != nil { - // log.Println(convertErr) - //} - // - //fmt.Println(urlValues) - //resp, err := util.CommonHttpFormData(url, urlValues, http.MethodPost) - - resultVmMonitoringAlertInfo := dragonfly.VmMonitoringAlertInfo{} - if err != nil { - fmt.Println(err) - return &resultVmMonitoringAlertInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - returnStatus := fwmodels.WebStatus{} - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&resultVmMonitoringAlertInfo) - fmt.Println(resultVmMonitoringAlertInfo) - } - returnStatus.StatusCode = respStatus - - return &resultVmMonitoringAlertInfo, returnStatus -} - -// 알람 수정 -// Update Monitoring Alert -func PutMonitoringAlert(taskName string, vmMonitoringAlertInfo *dragonfly.VmMonitoringAlertInfo) (*dragonfly.VmMonitoringAlertInfo, fwmodels.WebStatus) { - fmt.Println("PutMonitoringAlert ************ : ") - var originalUrl = "/alert/task" - // {{ip}}:{{port}}/dragonfly/alert/task - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.DRAGONFLY + urlParam - // url := util.DRAGONFLY + "/alert/task/" + taskName - - pbytes, _ := json.Marshal(vmMonitoringAlertInfo) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - - resultVmMonitoringAlertInfo := dragonfly.VmMonitoringAlertInfo{} - if err != nil { - fmt.Println(err) - return &resultVmMonitoringAlertInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - returnStatus := fwmodels.WebStatus{} - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&resultVmMonitoringAlertInfo) - fmt.Println(resultVmMonitoringAlertInfo) - } - returnStatus.StatusCode = respStatus - - return &resultVmMonitoringAlertInfo, returnStatus -} - -// 알람 제거 -// Delete Monitoring Alert -func DelMonitoringAlert(taskName string) (io.ReadCloser, fwmodels.WebStatus) { - var originalUrl = "/alert/task/:task_name" - // {{ip}}:{{port}}/dragonfly/alert/task/:task_name - var paramMapper = make(map[string]string) - paramMapper[":task_name"] = taskName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.DRAGONFLY + urlParam - // url := util.DRAGONFLY + "/alert/task/" + taskName - - if taskName == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "TaskName is required"} - } - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 알람 이벤트 핸들러 조회 -// Get monitoring alert event-handler -// type : 이벤트 핸들러 유형 ( "slack" | "smtp" ) -// name : slackHandler(EventHandlerName) -func GetMonitoringAlertEventHandlerData(eventHandlerType string, eventName string) (dragonfly.VmMonitoringAlertInfo, fwmodels.WebStatus) { - var originalUrl = "/alert/eventhandler/type/:type/event/:name" - //{{ip}}:{{port}}/dragonfly/alert/eventhandler/type/:type/event/:name - var paramMapper = make(map[string]string) - paramMapper[":type"] = eventHandlerType - paramMapper[":name"] = eventName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.DRAGONFLY + urlParam - // url := util.DRAGONFLY + "/alert/eventhandler/type/" + eventHandlerType + "/event/" + eventName - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - vmMonitoringAlertInfo := dragonfly.VmMonitoringAlertInfo{} - if err != nil { - fmt.Println(err) - return vmMonitoringAlertInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&vmMonitoringAlertInfo) - - return vmMonitoringAlertInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 알람 이벤트 핸들러 목록 조회(slack, smtp...) -// List monitoring alert event handler -func GetMonitoringAlertEventHandlerList() ([]dragonfly.VmMonitoringAlertEventHandlerInfo, fwmodels.WebStatus) { - fmt.Print("#########GetMonitoringAlertEventHandlerList############") - var originalUrl = "/alert/eventhandlers" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.DRAGONFLY + urlParam - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - vmMonitoringAlertEventHandlerInfoList := []dragonfly.VmMonitoringAlertEventHandlerInfo{} - if err != nil { - fmt.Println(err) - return vmMonitoringAlertEventHandlerInfoList, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&vmMonitoringAlertEventHandlerInfoList) - - return vmMonitoringAlertEventHandlerInfoList, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 알람 이벤트 핸들러 생성 -// Create monitoring alert event-handler -func RegMonitoringAlertEventHandler(vmMonitoringAlertEventHandlerInfoReg *dragonfly.VmMonitoringAlertEventHandlerInfoReg) (*dragonfly.VmMonitoringAlertEventHandlerInfoReg, fwmodels.WebStatus) { - fmt.Println("RegMonitoringAlertEventHandler ************ : ") - var originalUrl = "/alert/eventhandler" - // {{ip}}:{{port}}/dragonfly/alert/eventhandler - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.DRAGONFLY + urlParam - // url := util.DRAGONFLY + "/alert/eventhandler" - - pbytes, _ := json.Marshal(vmMonitoringAlertEventHandlerInfoReg) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - //urlValues, convertErr := util.StructToMapByJson(vmMonitoringAlertEventHandlerInfoReg) - //if convertErr != nil { - // log.Println(convertErr) - //} - // - //fmt.Println(urlValues) - //resp, err := util.CommonHttpFormData(url, urlValues, http.MethodPost) - - resultVmMonitoringAlertEventHandlerInfoReg := dragonfly.VmMonitoringAlertEventHandlerInfoReg{} - if err != nil { - fmt.Println(err) - return &resultVmMonitoringAlertEventHandlerInfoReg, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - returnStatus := fwmodels.WebStatus{} - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&resultVmMonitoringAlertEventHandlerInfoReg) - fmt.Println(resultVmMonitoringAlertEventHandlerInfoReg) - } - returnStatus.StatusCode = respStatus - - return &resultVmMonitoringAlertEventHandlerInfoReg, returnStatus -} - -// 알람 이벤트 핸들러 수정( handlerType=slack) -func PutMonitoringAlertEventHandlerSlack(eventHandlerType string, eventName string, vmMonitoringAlertEventHandlerSlackInfo *dragonfly.EventHandlerOptionSlack) (*dragonfly.VmMonitoringAlertEventHandlerSlackInfo, fwmodels.WebStatus) { - fmt.Println("PutMonitoringAlertEventHandler ************ : ") - var originalUrl = "/alert/eventhandler/type/:type/event/:name" - // {{ip}}:{{port}}/dragonfly/alert/eventhandler/type/:type/event/:name - var paramMapper = make(map[string]string) - paramMapper[":type"] = eventHandlerType - paramMapper[":name"] = eventName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.DRAGONFLY + urlParam - // url := util.DRAGONFLY + "/alert/eventhandler/type/" + eventHandlerType + "/event/" + eventName - - pbytes, _ := json.Marshal(vmMonitoringAlertEventHandlerSlackInfo) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - - resultVmMonitoringAlertEventHandlerInfo := dragonfly.VmMonitoringAlertEventHandlerSlackInfo{} - if err != nil { - fmt.Println(err) - return &resultVmMonitoringAlertEventHandlerInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - returnStatus := fwmodels.WebStatus{} - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&resultVmMonitoringAlertEventHandlerInfo) - fmt.Println(resultVmMonitoringAlertEventHandlerInfo) - } - returnStatus.StatusCode = respStatus - - return &resultVmMonitoringAlertEventHandlerInfo, returnStatus -} - -// 알람 이벤트 핸들러 수정( handlerType=smtp) -func PutMonitoringAlertEventHandlerSmtp(eventHandlerType string, eventName string, vmMonitoringAlertEventHandlerInfo *dragonfly.EventHandlerOptionSmtp) (*dragonfly.VmMonitoringAlertEventHandlerSmtpInfo, fwmodels.WebStatus) { - fmt.Println("PutMonitoringAlertEventHandlerSmtp ************ : ") - var originalUrl = "/alert/eventhandler/type/:type/event/:name" - // {{ip}}:{{port}}/dragonfly/alert/eventhandler/type/:type/event/:name - var paramMapper = make(map[string]string) - paramMapper[":type"] = eventHandlerType - paramMapper[":name"] = eventName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.DRAGONFLY + urlParam - // url := util.DRAGONFLY + "/alert/eventhandler/type/" + eventHandlerType + "/event/" + eventName - // {{ip}}:{{port}}/dragonfly/alert/eventhandler/type/:type/event/:name - - pbytes, _ := json.Marshal(vmMonitoringAlertEventHandlerInfo) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - - resultVmMonitoringAlertEventHandlerInfo := dragonfly.VmMonitoringAlertEventHandlerSmtpInfo{} - if err != nil { - fmt.Println(err) - return &resultVmMonitoringAlertEventHandlerInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - returnStatus := fwmodels.WebStatus{} - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&resultVmMonitoringAlertEventHandlerInfo) - fmt.Println(resultVmMonitoringAlertEventHandlerInfo) - } - returnStatus.StatusCode = respStatus - - return &resultVmMonitoringAlertEventHandlerInfo, returnStatus -} - -// 알람 제거 -// Delete monitoring alert event-handler -func DelMonitoringAlertEventHandler(eventHandlerType string, eventName string) (io.ReadCloser, fwmodels.WebStatus) { - var originalUrl = "/alert/eventhandler/type/:type/event/:name" - // {{ip}}:{{port}}/dragonfly/alert/eventhandler/type/:type/event/:name - var paramMapper = make(map[string]string) - paramMapper[":type"] = eventHandlerType - paramMapper[":name"] = eventName - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.DRAGONFLY + urlParam - // url := util.DRAGONFLY + "/alert/eventhandler/type/" + eventHandlerType + "/event/" + eventName - - if eventHandlerType == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "eventHandlerType is required"} - } - if eventName == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "eventName is required"} - } - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 알람 로그 정보 목록 조회 -// List monitoring alert event -func GetMonitoringAlertLogList(taskName string, logLevel string) ([]dragonfly.VmMonitoringAlertLog, fwmodels.WebStatus) { - if logLevel == "" { - logLevel = "warning" - } - var originalUrl = "/alert/task/:task_name/events?level={logLevel}" - // {{ip}}:{{port}}/dragonfly/alert/task/:task_name/events?level=warning - var paramMapper = make(map[string]string) - paramMapper[":task_name"] = taskName - paramMapper["{logLevel}"] = logLevel - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - // - url := util.DRAGONFLY + urlParam - - //resp, err := util.CommonHttpFormData(url, nil, http.MethodGet) - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - vmMonitoringAlertLogList := []dragonfly.VmMonitoringAlertLog{} - json.NewDecoder(respBody).Decode(&vmMonitoringAlertLogList) - - // fmt.Println("check") - // fmt.Println(vmMonitoringAlertLogList) - - return vmMonitoringAlertLogList, fwmodels.WebStatus{StatusCode: respStatus} -} diff --git a/mc_web_console_api/handler/MyImageHandler.go b/mc_web_console_api/handler/MyImageHandler.go deleted file mode 100644 index 46eb7586..00000000 --- a/mc_web_console_api/handler/MyImageHandler.go +++ /dev/null @@ -1,264 +0,0 @@ -package handler - -import ( - "encoding/json" - "fmt" - "log" - - // "math" - "net/http" - // "strconv" - // "sync" - - //"github.com/davecgh/go-spew/spew" - - // "mc_web_console_api/fwmodels/spider" - // "mc_web_console_api/fwmodels/tumblebug" - "mc_web_console_api/fwmodels" - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - - util "mc_web_console_api/util" -) - -// MyImage 목록 조회 -func GetMyImageList(nameSpaceID string, optionParam string, filterKeyParam string, filterValParam string) ([]tbmcir.TbCustomImageInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/customImage" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - if optionParam != "" { - urlParam += "?option=" + optionParam - } else { - urlParam += "?option=" - } - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - - url := util.TUMBLEBUG + urlParam - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - log.Println(respBody) - myImageInfoList := map[string][]tbmcir.TbCustomImageInfo{} - json.NewDecoder(respBody).Decode(&myImageInfoList) - //spew.Dump(body) - fmt.Println(myImageInfoList["customImage"]) - - return myImageInfoList["customImage"], fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetMyImageListByID(nameSpaceID string, filterKeyParam string, filterValParam string) ([]string, fwmodels.WebStatus) { - fmt.Println("GetMyImageListByID ************ : ") - var originalUrl = "/ns/{nsId}/resources/customImage" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - urlParam += "?option=id" - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - url := util.TUMBLEBUG + urlParam - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - log.Println(respBody) - //vNetInfoList := map[string][]string{} - myImageInfoList := tbcommon.TbIdList{} - json.NewDecoder(respBody).Decode(&myImageInfoList) - - return myImageInfoList.IDList, fwmodels.WebStatus{StatusCode: respStatus} -} - -// List 조회시 optionParam 추가 -func GetMyImageListByOption(nameSpaceID string, optionParam string, filterKeyParam string, filterValParam string) ([]tbmcir.TbCustomImageInfo, fwmodels.WebStatus) { - fmt.Println("GetMyImageListByOption ************ : ") - var originalUrl = "/ns/{nsId}/resources/customImage" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - if optionParam != "" { - urlParam += "?option=" + optionParam - } else { - urlParam += "?option=" - } - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - url := util.TUMBLEBUG + urlParam - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - log.Println(respBody) - myImageInfoList := map[string][]tbmcir.TbCustomImageInfo{} - json.NewDecoder(respBody).Decode(&myImageInfoList) - //spew.Dump(body) - fmt.Println(myImageInfoList["customImage"]) - - return myImageInfoList["customImage"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// CSP에 등록 된 customImage를 TB의 customImage로 등록 -func RegCspCustomImageToMyImage(nameSpaceID string, myImageReqInfo *tbmcir.TbCustomImageReq) (*tbmcir.TbCustomImageInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/myImage" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - fmt.Println("myImageReqInfo : ", myImageReqInfo) - - pbytes, _ := json.Marshal(myImageReqInfo) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - resultMyImageInfo := tbmcir.TbCustomImageInfo{} - if err != nil { - fmt.Println(err) - return &resultMyImageInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - fmt.Println("respStatus ", respStatus) - - if respStatus == 500 { - webStatus := fwmodels.WebStatus{} - json.NewDecoder(respBody).Decode(&webStatus) - fmt.Println(webStatus) - webStatus.StatusCode = respStatus - return &resultMyImageInfo, webStatus - } - // 응답에 생성한 객체값이 옴 - json.NewDecoder(respBody).Decode(&resultMyImageInfo) - fmt.Println(resultMyImageInfo) - - return &resultMyImageInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Namespace내 모든 MyImage 삭제 -func DelAllMyImage(nameSpaceID string) (fwmodels.WebStatus, fwmodels.WebStatus) { - webStatus := fwmodels.WebStatus{} - - var originalUrl = "/ns/{nsId}/resources/myImage" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam + "?match=match" - - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - - if err != nil { - fmt.Println(err) - return webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return webStatus, fwmodels.WebStatus{StatusCode: respStatus} -} - -// MyImage 삭제 -func DelMyImage(nameSpaceID string, myImageID string) (fwmodels.WebStatus, fwmodels.WebStatus) { - webStatus := fwmodels.WebStatus{} - - var originalUrl = "/ns/{nsId}/resources/customImage/{myImageId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{myImageId}"] = myImageID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - - if err != nil { - fmt.Println(err) - return webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return webStatus, fwmodels.WebStatus{StatusCode: respStatus} -} - -// MyImage 상세 조회 -func MyImageGet(nameSpaceID string, myImageID string) (*tbmcir.TbCustomImageInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/customImage/{myImageId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{myImageId}"] = myImageID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - - fmt.Println("nameSpaceID : ", nameSpaceID) - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - myImageInfo := tbmcir.TbCustomImageInfo{} - if err != nil { - fmt.Println(err) - return &myImageInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&myImageInfo) - fmt.Println(myImageInfo) - - return &myImageInfo, fwmodels.WebStatus{StatusCode: respStatus} -} diff --git a/mc_web_console_api/handler/NameSpaceHandler.go b/mc_web_console_api/handler/NameSpaceHandler.go deleted file mode 100644 index 7e271483..00000000 --- a/mc_web_console_api/handler/NameSpaceHandler.go +++ /dev/null @@ -1,463 +0,0 @@ -package handler - -import ( - "encoding/json" - // "errors" - "fmt" - "log" - "net/http" - - "mc_web_console_api/fwmodels" - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - "mc_web_console_api/fwmodels/webconsole" - "mc_web_console_api/models" - - // tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - // tbmcis "mc_web_console_api/fwmodels/tumblebug/mcis" - - util "mc_web_console_api/util" - - "github.com/davecgh/go-spew/spew" - "github.com/gobuffalo/pop/v6" - "github.com/gofrs/uuid" - "github.com/pkg/errors" -) - -// var NameSpaceUrl = "http://15.165.16.67:1323" -// var NameSpaceUrl = os.Getenv("TUMBLE_URL") - -// type NSInfo struct { -// ID string `json:"id"` -// Name string `json:"name"` -// Description string `json:"description"` -// } - -// 저장된 namespace가 없을 때 최초 1개 생성하고 해당 namespace 정보를 return : 검증 필요(TODO : 이미 namespace가 있어서 확인 못함) -func CreateDefaultNamespace() (*tbcommon.TbNsInfo, fwmodels.WebStatus) { - // nsInfo := new(fwmodels.NSInfo) - nameSpaceInfo := tbcommon.TbNsInfo{} - - // 사용자의 namespace 목록조회 - nsList, nsStatus := GetNameSpaceList() - if nsStatus.StatusCode == 500 { - log.Println(" nsStatus ", nsStatus) - return nil, nsStatus - } - - if len(nsList) > 0 { - nsStatus.StatusCode = 101 - nsStatus.Message = "Namespace already exists" - //return &nameSpaceInfo, errors.New(101, "Namespace already exists. size="+len(nsList)) - return &nameSpaceInfo, nsStatus - } - - // create default namespace - nameSpaceInfo.Name = "NS-01" // default namespace name - //nameSpaceInfo.ID = "NS-01" - nameSpaceInfo.Description = "default name space name" - respBody, respStatus := RegNameSpace(&nameSpaceInfo) - log.Println(" respBody ", respBody) // respBody에 namespace Id가 있으면 할당해서 사용할 것 - if respStatus.StatusCode != 200 && respStatus.StatusCode != 201 { - log.Println(" nsCreateErr ", respStatus) - return &nameSpaceInfo, respStatus - } - // respBody := resp.Body - // respStatus := resp.StatusCode - - return &nameSpaceInfo, respStatus -} - -// 사용자의 namespace 목록 조회 -func GetNameSpaceList() ([]tbcommon.TbNsInfo, fwmodels.WebStatus) { - fmt.Println("GetNameSpaceList start") - var originalUrl = "/ns" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns" - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - //body := HttpGetHandler(url) - - if err != nil { - // // Tumblebug 접속 확인하라고 - // fmt.Println(err) - // panic(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - nameSpaceInfoList := map[string][]tbcommon.TbNsInfo{} - // defer body.Close() - json.NewDecoder(respBody).Decode(&nameSpaceInfoList) - //spew.Dump(body) - fmt.Println(nameSpaceInfoList["ns"]) - - return nameSpaceInfoList["ns"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// Namespace 조회 시 Option에 해당하는 값만 조회. GetNameSpaceList와 TB 호출은 동일하나 option 사용으로 받아오는 param이 다름. controller에서 분기 -func GetNameSpaceListByOption(optionParam string) ([]tbcommon.TbNsInfo, fwmodels.WebStatus) { - fmt.Println("GetNameSpaceList start") - var originalUrl = "/ns" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.TUMBLEBUG + urlParam - if optionParam != "" { - url = url + "?option=" + optionParam - } - // url := util.TUMBLEBUG + "/ns" - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - //body := HttpGetHandler(url) - - if err != nil { - // // Tumblebug 접속 확인하라고 - // fmt.Println(err) - // panic(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - nameSpaceInfoList := map[string][]tbcommon.TbNsInfo{} - // defer body.Close() - json.NewDecoder(respBody).Decode(&nameSpaceInfoList) - //spew.Dump(body) - fmt.Println(nameSpaceInfoList["ns"]) - - return nameSpaceInfoList["ns"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// Namespace 조회 시 Option에 해당하는 값만 조회. GetNameSpaceList와 TB 호출은 동일하나 option 사용으로 받아오는 param이 다름 -func GetNameSpaceListByOptionID(optionParam string) ([]string, fwmodels.WebStatus) { - fmt.Println("GetNameSpaceList start") - var originalUrl = "/ns" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.TUMBLEBUG + urlParam - if optionParam == "id" { - url = url + "?option=" + optionParam - } else { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "option param is not ID"} - } - // url := util.TUMBLEBUG + "/ns" - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - //body := HttpGetHandler(url) - - if err != nil { - // // Tumblebug 접속 확인하라고 - // fmt.Println(err) - // panic(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - //nameSpaceInfoList := map[string][]string{} - nameSpaceInfoList := tbcommon.TbIdList{} - // defer body.Close() - json.NewDecoder(respBody).Decode(&nameSpaceInfoList) - //spew.Dump(body) - //fmt.Println(nameSpaceInfoList["idList"]) - // - //return nameSpaceInfoList["idList"], fwmodels.WebStatus{StatusCode: respStatus} - //fmt.Println(nameSpaceInfoList["output"]) - //return nameSpaceInfoList["output"], fwmodels.WebStatus{StatusCode: respStatus} - fmt.Println(nameSpaceInfoList.IDList) - return nameSpaceInfoList.IDList, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Get namespace -func GetNameSpaceData(nameSpaceID string) (tbcommon.TbNsInfo, fwmodels.WebStatus) { - fmt.Println("GetNameSpaceData start") - var originalUrl = "/ns/{nsId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - nameSpaceInfo := tbcommon.TbNsInfo{} - if err != nil { - return nameSpaceInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - // defer body.Close() - json.NewDecoder(respBody).Decode(&nameSpaceInfo) - fmt.Println(nameSpaceInfo) - - return nameSpaceInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// NameSpace 등록. 등록 후 생성된 Namespace 정보를 return -func RegNameSpace(nameSpaceInfo *tbcommon.TbNsInfo) (tbcommon.TbNsInfo, fwmodels.WebStatus) { - // buff := bytes.NewBuffer(pbytes) - var originalUrl = "/ns" - urlParam := util.MappingUrlParameter(originalUrl, nil) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns" - - //body, err := util.CommonHttpPost(url, nameSpaceInfo) - pbytes, _ := json.Marshal(nameSpaceInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - - resultNameSpaceInfo := tbcommon.TbNsInfo{} - if err != nil { - log.Println(err) - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return resultNameSpaceInfo, fwmodels.WebStatus{StatusCode: 500, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&resultNameSpaceInfo) - return resultNameSpaceInfo, fwmodels.WebStatus{StatusCode: respStatus} - //return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// NameSpace 수정 -func UpdateNameSpace(nameSpaceID string, nameSpaceInfo *tbcommon.TbNsReq) (tbcommon.TbNsInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns" - - pbytes, _ := json.Marshal(nameSpaceInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - - resultNameSpaceInfo := tbcommon.TbNsInfo{} - if err != nil { - fmt.Println(err) - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return resultNameSpaceInfo, fwmodels.WebStatus{StatusCode: 500, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&resultNameSpaceInfo) - - return resultNameSpaceInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// NameSpace 삭제 -func DelNameSpace(nameSpaceID string) (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - - resultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&resultInfo) - if err != nil { - fmt.Println(err) - //return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - json.NewDecoder(respBody).Decode(&resultInfo) - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: resultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// NameSpace 삭제 -func DelAllNameSpace() (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - var originalUrl = "/ns" - urlParam := util.MappingUrlParameter(originalUrl, nil) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - - resultInfo := tbcommon.TbSimpleMsg{} - - if err != nil { - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func UserNameSpaceListFromDB(userId uuid.UUID, tx *pop.Connection) ([]tbcommon.TbNsInfo, fwmodels.WebStatus) { - nsList := &models.Namespaces{} - //nsList := []models.Namespace{} - - q := tx.Eager().Where("user_id = ?", userId) - - err := q.All(nsList) - - if err != nil { - //return errors.WithStack(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - returnNsList := []tbcommon.TbNsInfo{} - for _, ns := range *nsList { - //for _, ns := range nsList { - returnNsList = append(returnNsList, tbcommon.TbNsInfo{ID: ns.ID, Name: ns.NsName}) - } - - return returnNsList, fwmodels.WebStatus{StatusCode: 200} -} - -func CheckExistsUserNamespace(userId uuid.UUID, nsId string, tx *pop.Connection) (bool, *models.UserNamespace) { - un := &models.UserNamespace{} - q := tx.Where("user_id = ?", userId).Where("ns_id = ?", nsId) - b, err := q.Exists(un) - if b { - err2 := q.First(un) - if err2 != nil { - errors.WithStack(err2) - } - } - if err != nil { - errors.WithStack(err) - } - - return b, un -} -func RegUserNamespace(un *webconsole.UserNamespaceReq, tx *pop.Connection) error { - spew.Dump("=====================") - spew.Dump(un) - spew.Dump("=====================") - us_arr := un.Us - ns_arr := un.Ns - - for _, user := range us_arr { - - user_id := uuid.Must(uuid.FromString(user)) - for _, ns := range ns_arr { - b, _ := CheckExistsUserNamespace(user_id, ns, tx) - un := &models.UserNamespace{} - if !b { - un.NamespaceID = ns - un.UserID = user_id - verr, err := un.Create(tx) - if verr.HasAny() { - spew.Dump("user_namespace at verr", *verr) - return errors.WithStack(verr) - } - if err != nil { - spew.Dump("user_namespace at err", un) - spew.Dump(err) - return errors.WithStack(err) - } - - } - - } - } - return nil -} - -func DelUserNamespace(un *webconsole.UserNamespaceReq, tx *pop.Connection) error { - spew.Dump("=====================") - spew.Dump(un) - spew.Dump("=====================") - us_arr := un.Us - ns_arr := un.Ns - - for _, user := range us_arr { - - user_id := uuid.Must(uuid.FromString(user)) - for _, ns := range ns_arr { - b, un := CheckExistsUserNamespace(user_id, ns, tx) - //un := &models.UserNamespace{} - if b { - // un.NamespaceID = ns - // un.UserID = user_id - err := tx.Destroy(un) - // if verr.HasAny() { - // spew.Dump("user_namespace at verr", *verr) - // return errors.WithStack(verr) - // } - if err != nil { - spew.Dump("user_namespace delete at err", un) - spew.Dump(err) - return errors.WithStack(err) - } - - } - - } - } - return nil -} - -func GetAssignUserNamespaces(user_id uuid.UUID, tx *pop.Connection) (error, *models.UserNamespaces) { - un := &models.UserNamespaces{} - q := tx.Eager().Where("user_id = ?", user_id) - err := q.All(un) - if err != nil { - return errors.WithStack(err), un - } - return err, un - -} - -// func GetNamespaceById(ns_id string, tx *pop.Connection) (error, *models.Namespace) { -func GetNamespaceById(nsId string) (*models.Namespace, error) { - ns := &models.Namespace{} - //err := tx.Find(ns, ns_id) - query := models.DB.Q() - err := query.Find(ns, nsId) - if err != nil { - return ns, errors.WithStack(err) - } - return ns, err -} - -// 사용자에게 공유된 모든 namespace 목록 조회 -func SharedNamespaceList(userId uuid.UUID) ([]models.Namespace, error) { - - sharedNamespaceList := []models.Namespace{} - query := models.DB.Q() - query = query.Join("user_namespaces un", "namespaces.id = un.ns_id") - query = query.Where("un.user_id = ? ", userId) - - err := query.All(&sharedNamespaceList) - if err != nil { - return sharedNamespaceList, errors.WithStack(err) - } - - return sharedNamespaceList, nil -} diff --git a/mc_web_console_api/handler/NetworkHandler.go b/mc_web_console_api/handler/NetworkHandler.go deleted file mode 100644 index 48aad1d1..00000000 --- a/mc_web_console_api/handler/NetworkHandler.go +++ /dev/null @@ -1,121 +0,0 @@ -package handler - -import ( - "encoding/json" - "fmt" - "net/http" - - // "github.com/davecgh/go-spew/spew" - - // "os" - "mc_web_console_api/fwmodels" - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - tbnetutil "mc_web_console_api/fwmodels/tumblebug/netutil" - - util "mc_web_console_api/util" - -) - - -/////////// TODO : Network 관련해서 ResourceHandler의 정의된 부분을 이쪽으로 옮길 것 (ex. vpc, subnet ...) ///////////////// - -// Design a multi-cloud network configuration -// Design a hierarchical network configuration of a VPC network or multi-cloud network consisting of multiple VPC networks -// example -// { -// "cidrBlock": "string", -// "name": "string", -// "subnets": [ -// { -// "cidrBlock": "string", -// "name": "string", -// "subnets": [ -// null -// ] -// } -// ] -// } -func DesignHierarchicalNetworkConfiguration(subnettingReq tbnetutil.SubnettingRequest)(tbcommon.TbSimpleMsg, fwmodels.WebStatus){ - var originalUrl = "/util/net/design" - - var paramMapper = make(map[string]string) - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(subnettingReq) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - resultInfo := tbcommon.TbSimpleMsg{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&resultInfo) - fmt.Println(resultInfo) - - returnStatus.StatusCode = respStatus - - return resultInfo, returnStatus -} - - -// Validate a hierarchical configuration of a VPC network or multi-cloud network consisting of multiple VPC networks -// example -// { -// "networkConfiguration": { -// "cidrBlock": "string", -// "name": "string", -// "subnets": [ -// null -// ] -// } -// } -func ValidateMultiCloudNetworkConfiguration(networkConfig tbnetutil.NetworkConfig) (tbcommon.TbSimpleMsg, fwmodels.WebStatus){ - var originalUrl = "/util/net/validate" - - var paramMapper = make(map[string]string) - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(networkConfig) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - resultInfo := tbcommon.TbSimpleMsg{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&resultInfo) - fmt.Println(resultInfo) - - returnStatus.StatusCode = respStatus - - return resultInfo, returnStatus -} - diff --git a/mc_web_console_api/handler/NlbHandler.go b/mc_web_console_api/handler/NlbHandler.go deleted file mode 100644 index ba890b86..00000000 --- a/mc_web_console_api/handler/NlbHandler.go +++ /dev/null @@ -1,372 +0,0 @@ -package handler - -import ( - "encoding/json" - "fmt" - "io" - "log" - "net/http" - - // "github.com/davecgh/go-spew/spew" - - // "os" - "mc_web_console_api/fwmodels" - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - tbmcis "mc_web_console_api/fwmodels/tumblebug/mcis" - - util "mc_web_console_api/util" - - "github.com/gobuffalo/buffalo" -) - -/* -NLB ID만 목록으로 제공 -*/ -func GetNlbIdListByMcisID(nameSpaceID string, mcisID string) ([]string, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/nlb" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - urlParam += "?option=id" - url := util.TUMBLEBUG + urlParam - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - mcisList := tbcommon.TbIdList{} - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&mcisList) - //spew.Dump(body) - fmt.Println(mcisList.IDList) - - return mcisList.IDList, fwmodels.WebStatus{StatusCode: respStatus} -} - -/* -NLB 목록을 조회 조건에 따라 검색 -*/ -func GetNlbListByOption(nameSpaceID string, mcisID string, optionParam string) ([]tbmcis.TbNLBInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/nlb" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - if optionParam != "" { - urlParam += "?option=" + optionParam - } - - url := util.TUMBLEBUG + urlParam - resp, err := util.CommonHttp(url, nil, http.MethodGet) - // resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - nlbList := map[string][]tbmcis.TbNLBInfo{} - returnStatus := fwmodels.WebStatus{} - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - json.NewDecoder(respBody).Decode(&nlbList) - fmt.Println(nlbList["nlb"]) - - returnStatus.StatusCode = respStatus - log.Println(respBody) - // util.DisplayResponse(resp) // 수신내용 확인 - - return nlbList["nlb"], returnStatus -} - -/* - NLB 등록 - async로 호출하므로 결과를 받으면 websocket으로 전달 -*/ -//RegNlbByAsync -func RegNlbByAsync(nameSpaceID string, mcisID string, nlbReq *tbmcis.TbNLBReq, c buffalo.Context) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/nlb" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - // urlParam += "?option=register" // csp에만 있는 resource를 tumblebug에 등록 할 때 option으로 register를 붙임. - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(nlbReq) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - respBody := resp.Body - respStatus := resp.StatusCode - - taskKey := nameSpaceID + "||" + "nlb" + "||" + nlbReq.Name // TODO : 공통 function으로 뺄 것. - - if err != nil { - fmt.Println(err) - log.Println("RegNlbByAsync ", err) - - StoreWebsocketMessage(util.TASK_TYPE_NLB, taskKey, util.NLB_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("RegNlbByAsync ", failResultInfo) - StoreWebsocketMessage(util.TASK_TYPE_NLB, taskKey, util.NLB_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - } else { - StoreWebsocketMessage(util.TASK_TYPE_NLB, taskKey, util.NLB_LIFECYCLE_CREATE, util.TASK_STATUS_COMPLETE, c) // session에 작업내용 저장 - } -} - -// 특정 Namespace의 MCIS 내 모든 NLB 제거 -func DelAllNlb(nameSpaceID string, mcisID string) (io.ReadCloser, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/nlb" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - // optionParamVal := "" - // if optionParam != "" { - // optionParamVal = "?match=" + optionParam - // } - - // url := util.TUMBLEBUG + urlParam + optionParamVal - url := util.TUMBLEBUG + urlParam - - if mcisID == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "MCIS ID is required"} - } - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("DelNLB ", failResultInfo) - return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// DelNlb : nlbId 에 해당하는 nlb 제거 -func DelNlb(nameSpaceID string, mcisID string, nlbID string, optionParam string) (io.ReadCloser, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/nlb/{nlbId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{nlbId}"] = nlbID - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - if mcisID == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "MCIS ID is required"} - } - if nlbID == "" { - return nil, fwmodels.WebStatus{StatusCode: 500, Message: "NLB ID is required"} - } - - // 경로안에 parameter가 있어 추가 param없이 호출 함. - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("DelNLB ", failResultInfo) - return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 특정 NLB 조회 -func GetNlbData(nameSpaceID string, mcisID string, nlbID string) (tbmcis.TbNLBInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/nlb/{nlbId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{nlbId}"] = nlbID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - if err != nil { - fmt.Println(err) - return tbmcis.TbNLBInfo{}, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - nlbInfo := tbmcis.TbNLBInfo{} - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return tbmcis.TbNLBInfo{}, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&nlbInfo) - - return nlbInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 특정 NLB의 Health -func GetNlbHealth(nameSpaceID string, mcisID string, nlbID string) (tbmcis.TbNLBInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/nlb/{nlbId}/healthz" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{nlbId}"] = nlbID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - if err != nil { - fmt.Println(err) - return tbmcis.TbNLBInfo{}, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - nlbInfo := tbmcis.TbNLBInfo{} - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return tbmcis.TbNLBInfo{}, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&nlbInfo) - fmt.Println(nlbInfo) - - return nlbInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// NLB의 TargetGroup에 VM 추가 -func AddVmToNLBTargetGroup(nameSpaceID string, mcisID string, nlbID string, nlbTargetGroupReq *tbmcis.TbNLBAddRemoveVMReq) (*tbmcis.TbNLBInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/nlb/{nlbId}/vm" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{nlbId}"] = nlbID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(nlbTargetGroupReq) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnNlbInfo := tbmcis.TbNLBInfo{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return &returnNlbInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return &returnNlbInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&returnNlbInfo) - fmt.Println(returnNlbInfo) - - returnStatus.StatusCode = respStatus - - return &returnNlbInfo, returnStatus -} - -// NLB의 TargetGroup에 VM 제거 -func RemoveVmToNLBTargetGroup(nameSpaceID string, mcisID string, nlbID string, nlbTargetGroupReq *tbmcis.TbNLBAddRemoveVMReq) (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/mcis/{mcisId}/nlb/{nlbId}/vm" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{mcisId}"] = mcisID - paramMapper["{nlbId}"] = nlbID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(nlbTargetGroupReq) - resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - - resultInfo := tbcommon.TbSimpleMsg{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&resultInfo) - fmt.Println(resultInfo) - - returnStatus.StatusCode = respStatus - - return resultInfo, returnStatus -} diff --git a/mc_web_console_api/handler/PmksHandler.go b/mc_web_console_api/handler/PmksHandler.go deleted file mode 100644 index 8c26d71e..00000000 --- a/mc_web_console_api/handler/PmksHandler.go +++ /dev/null @@ -1,498 +0,0 @@ -package handler - -import ( - "encoding/json" - "fmt" - "strings" - - "mc_web_console_api/fwmodels" - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - - // "io" - "log" - "net/http" - - // "os" - - spider "mc_web_console_api/fwmodels/spider" - - util "mc_web_console_api/util" - - "github.com/gobuffalo/buffalo" -) - -// 해당 namespace의 모든 pmks 목록 조회 -func GetPmksNamespaceClusterList(clusterReqInfo spider.AllClusterReqInfo) ([]spider.SpClusterInfo, fwmodels.WebStatus) { - // func GetPmksNamespaceClusterList(clusterReqInfo spider.ClusterReqInfo) ([]spider.SpAllClusterInfoList, fwmodels.WebStatus) { - var originalUrl = "/nscluster" - - url := util.SPIDER + originalUrl - pbytes, _ := json.Marshal(clusterReqInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - - //returnClusterList := spider.SpTotalClusterInfoList{} - returnClusterList := []spider.SpClusterInfo{} - //returnClusterList := []spider.SpAllClusterInfoList{} - if err != nil { - fmt.Println(err) - return returnClusterList, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - respBody := resp.Body - respStatus := resp.StatusCode - - fmt.Println(respStatus) - fmt.Println(respBody) - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - - //spew.Dump(respBody) - return returnClusterList, fwmodels.WebStatus{StatusCode: respStatus, Message: errorInfo.Message} - } else { - totalClusterList := spider.SpTotalClusterInfoList{} - json.NewDecoder(respBody).Decode(&totalClusterList) - //json.NewDecoder(respBody).Decode(&returnClusterList) - - // AllClusterList배열의 Cluster배열 형태를 ClusterInfo의 배열로 변환 - - for _, clusterList := range totalClusterList.AllClusterList { - log.Println(clusterList) - - for _, cluster := range clusterList.ClusterList { - cluster.ProviderName = clusterList.Provider - cluster.ConnectionName = clusterList.Connection - returnClusterList = append(returnClusterList, cluster) - } - - //returnClusterList = append(returnClusterList, clusterList.ClusterList...) - //returnClusterList = append(returnClusterList, clusterList) - } - } - - return returnClusterList, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Cluster 목록 조회 -func GetPmksClusterList(clusterReqInfo spider.ClusterReqInfo) ([]spider.SpClusterInfo, fwmodels.WebStatus) { - var originalUrl = "/cluster" - - url := util.SPIDER + originalUrl - pbytes, _ := json.Marshal(clusterReqInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - respBody := resp.Body - respStatus := resp.StatusCode - - clusterList := map[string][]spider.SpClusterInfo{} - json.NewDecoder(respBody).Decode(&clusterList) - fmt.Println("^^^^^^^^^^^^^^^^^^^^^^^") - fmt.Println(clusterList) - //log.Println(respBody) - - return clusterList["cluster"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// 특정 Cluster 조회 -func GetPmksClusterData(cluster string, clusterReqInfo spider.ClusterReqInfo) (*spider.SpClusterInfo, fwmodels.WebStatus) { - var originalUrl = "/cluster/{cluster}" - - var paramMapper = make(map[string]string) - paramMapper["{cluster}"] = cluster - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.SPIDER + urlParam - log.Println(clusterReqInfo) - pbytes, _ := json.Marshal(clusterReqInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - - // defer body.Close() - clusterInfo := spider.RespClusterInfo{} - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // util.DisplayResponse(resp) // 수신내용 확인 - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&clusterInfo) - fmt.Println(clusterInfo) - - clusterInfo.ClusterInfo.ConnectionName = clusterReqInfo.ConnectionName - return &clusterInfo.ClusterInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Cluster 생성 -func RegPmksCluster(nameSpaceID string, clusterReqInfo *spider.ClusterReqInfo) (*spider.SpClusterInfo, fwmodels.WebStatus) { - - var originalUrl = "/cluster" - - url := util.SPIDER + originalUrl - - pbytes, _ := json.Marshal(clusterReqInfo) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnClusterInfo := spider.SpClusterInfo{} - returnStatus := fwmodels.WebStatus{} - - if err != nil { - fmt.Println(err) - return &returnClusterInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnClusterInfo) - fmt.Println(returnClusterInfo) - } - returnStatus.StatusCode = respStatus - - return &returnClusterInfo, returnStatus -} - -// PMKS Cluster 생성 -func RegPmksClusterByAsync(clusterReqInfo *spider.ClusterReqInfo, c buffalo.Context) { - - var originalUrl = "/cluster" - - url := util.SPIDER + originalUrl - - pbytes, _ := json.Marshal(clusterReqInfo) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - nameSpaceID := clusterReqInfo.NameSpace - clusterName := clusterReqInfo.ReqInfo.Name - taskKey := nameSpaceID + "||" + "pmks" + "||" + clusterName // TODO : 공통 function으로 뺄 것. - - if err != nil { - fmt.Println(err) - //Message: {"code":"400","message":"no managedkubernetes ros component exists. version: 1, labels: ap-southeast-1:common:26888:5513479151634744:GC0","requestId":"67CAB7BC-C0E1-3D93-A967-C89AE46138B2","status":400} - //Message: {"code":"QuotaExceeded.Cluster", - //"message":"Exceeded the quota for creating a cluster - // (quota code: q_ManagedKubernetes_Default_ack.standard_Cluster) - // , usage 2/2.","requestId":"EEF6F445-4549-39C7-B8AB-DB83B843A296","status":400} - - errMsg := err.Error() - - //StoreWebsocketMessage(util.TASK_TYPE_PMKS, taskKey, util.PMKS_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, c) - StoreWebsocketMessageDetail(util.TASK_TYPE_PMKS, taskKey, util.PMKS_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, errMsg, c) - } else { - - respBody := resp.Body - respStatus := resp.StatusCode - //spew.Dump(resp) - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := spider.SpError{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("RegPmksByAsync failed ", failResultInfo) - log.Println("RegPmksByAsync failed-------- ", failResultInfo.Message) - - //jsonBytes, _ := json.Marshal(failResultInfo) // JSON ENCODING - //jsonString := string(jsonBytes) - //fmt.Println("personA String: ", jsonString) - - //var result map[string]interface{} - //if err := json.Unmarshal([]byte(resp), &result); err != nil { - // panic(err) - //} - - //fmt.Println(result["kind"]) // Event 출력 - //fmt.Println(result["apiVersion"]) // events.k8s.io/v1 출력 - - beginIndex := strings.Index(failResultInfo.Message, "Message:") - var endMessage string - if beginIndex == -1 { - fmt.Println("cannot find Message: ------------") - endMessage = failResultInfo.Message - } else { - findMessageBegin := failResultInfo.Message[beginIndex:] - fmt.Println("findMessageBegin : ", findMessageBegin) - - beginIndex2 := strings.Index(findMessageBegin, "{") - findMessage := findMessageBegin[beginIndex2:] - fmt.Println("findMessage : ", findMessage) - - endIndex := strings.Index(findMessage, "}") - endMessage = findMessage[:endIndex] - fmt.Println("endMessage : ", endMessage) - } - //findMessageBegin := strings.Index(failResultInfo.Message, "}")) - - //byt := []byte(endMessage) - //var dat map[string]interface{} - //if err := json.Unmarshal(byt, &dat); err != nil { - //panic(err) - //} - //fmt.Println("********************") - //fmt.Println(dat) - - //var errorDetailObj = spider.SpErrorDetail{} - //err := json.Unmarshal([]byte(endMessage), &errorDetailObj) - //if err != nil { - // fmt.Println(err) - //} - //fmt.Println("personObj Object: ", errorDetailObj) - //detailInfo := spider.SpErrorDetail{} - //json.NewDecoder(failResultInfo).Decode(&detailInfo) - //log.Println("detail failed ", detailInfo) - - //StoreWebsocketMessage(util.TASK_TYPE_PMKS, taskKey, util.PMKS_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - StoreWebsocketMessageDetail(util.TASK_TYPE_PMKS, taskKey, util.PMKS_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, endMessage, c) - } else { - returnClusterInfo := spider.ClusterInfo{} - json.NewDecoder(respBody).Decode(&returnClusterInfo) - fmt.Println(returnClusterInfo) - StoreWebsocketMessage(util.TASK_TYPE_PMKS, taskKey, util.PMKS_LIFECYCLE_CREATE, util.TASK_STATUS_COMPLETE, c) // session에 작업내용 저장 - } - } - -} - -// PmksClusterUpdateProc : 현재는 버전만 upgrade. 추후 항목 update가 생기면 function 분리할 것 -func UpdatePmksCluster(clusterReqInfo *spider.ClusterReqInfo) (spider.SpClusterInfo, fwmodels.WebStatus) { - var originalUrl = "/cluster/upgrade" - - url := util.SPIDER + originalUrl - - pbytes, _ := json.Marshal(clusterReqInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - util.DisplayResponse(resp) // 수신내용 확인 - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - - resultClusterInfo := spider.SpClusterInfo{} - if err != nil { - fmt.Println(err) - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return resultClusterInfo, fwmodels.WebStatus{StatusCode: 500, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&resultClusterInfo) - - return resultClusterInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// PMKS Cluster 삭제 -func DelPmksCluster(cluster string, clusterReqInfo spider.ClusterReqInfo) (*spider.SpClusterInfo, fwmodels.WebStatus) { - var originalUrl = "/cluster/{cluster}" - - var paramMapper = make(map[string]string) - paramMapper["{cluster}"] = cluster - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.SPIDER + urlParam - - pbytes, _ := json.Marshal(clusterReqInfo) - - resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - util.DisplayResponse(resp) // 수신내용 확인 - - resultClusterInfo := spider.SpClusterInfo{} - if err != nil { - fmt.Println("delCluster ", err) - return &resultClusterInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&resultClusterInfo) - fmt.Println(resultClusterInfo) - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - fmt.Println(failResultInfo) - return &resultClusterInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - return &resultClusterInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Cluster 삭제 비동기 처리 -func DelPmksClusterByAsync(cluster string, clusterReqInfo *spider.ClusterReqInfo, c buffalo.Context) { - var originalUrl = "/cluster/{cluster}" - - var paramMapper = make(map[string]string) - paramMapper["{cluster}"] = cluster - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.SPIDER + urlParam - - pbytes, _ := json.Marshal(clusterReqInfo) - - resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - - nameSpaceID := clusterReqInfo.NameSpace - taskKey := nameSpaceID + "||" + "pmks" + "||" + cluster - - if err != nil { - fmt.Println(err) - errMsg := err.Error() - //StoreWebsocketMessage(util.TASK_TYPE_PMKS, taskKey, util.PMKS_LIFECYCLE_DELETE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - StoreWebsocketMessageDetail(util.TASK_TYPE_PMKS, taskKey, util.PMKS_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, errMsg, c) - - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("DelPmksByAsync ", failResultInfo) - StoreWebsocketMessage(util.TASK_TYPE_PMKS, taskKey, util.PMKS_LIFECYCLE_DELETE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - - } else { - log.Println("DelPmksByAsync respBody : ", respBody) - StoreWebsocketMessage(util.TASK_TYPE_PMKS, taskKey, util.PMKS_LIFECYCLE_DELETE, util.TASK_STATUS_COMPLETE, c) // session에 작업내용 저장 - } -} - -// NodeGroup 생성 -func RegPmksNodeGroup(clusterID string, nodeGroupReqInfo *spider.NodeGroupReqInfo) (*spider.NodeGroupInfo, fwmodels.WebStatus) { - - var originalUrl = "/cluster/{cluster}/nodegroup" - - var paramMapper = make(map[string]string) - paramMapper["{cluster}"] = clusterID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.SPIDER + urlParam - - pbytes, _ := json.Marshal(nodeGroupReqInfo) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnNodeGroupInfo := spider.NodeGroupInfo{} - returnStatus := fwmodels.WebStatus{} - - respBody := resp.Body - respStatus := resp.StatusCode - - if err != nil { - fmt.Println(err) - return &returnNodeGroupInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&returnNodeGroupInfo) - fmt.Println(returnNodeGroupInfo) - } - returnStatus.StatusCode = respStatus - - return &returnNodeGroupInfo, returnStatus -} - -// NodeGroup 삭제 -func DelPmksNodeGroup(clusterID string, nodeGroupID string, nodeGroupReqInfo *spider.NodeGroupReqInfo) (bool, fwmodels.WebStatus) { - var originalUrl = "/cluster/{cluster}/nodegroup/{nodegroup}" - - var paramMapper = make(map[string]string) - paramMapper["{cluster}"] = clusterID - paramMapper["{nodegroup}"] = nodeGroupID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.SPIDER + urlParam - - if clusterID == "" { - return false, fwmodels.WebStatus{StatusCode: 500, Message: "cluster is required"} - } - if nodeGroupID == "" { - return false, fwmodels.WebStatus{StatusCode: 500, Message: "nodeGroup is required"} - } - - pbytes, _ := json.Marshal(nodeGroupReqInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - if err != nil { - fmt.Println(err) - return false, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - util.DisplayResponse(resp) // 수신내용 확인 - - //respBody := resp.Body - respStatus := resp.StatusCode - - return true, fwmodels.WebStatus{StatusCode: respStatus} -} - -// NodeGroup 수정 : onAutoScaling -func UpdatePmksNodeGroupAutoScaling(clusterID string, nodeGroupID string, nodeGroupReqInfo *spider.NodeGroupReqInfo) (spider.SpClusterInfo, fwmodels.WebStatus) { - var originalUrl = "/cluster/{cluster}/nodegroup/{nodegroup}/onautoscaling" - - var paramMapper = make(map[string]string) - paramMapper["{cluster}"] = clusterID - paramMapper["{nodegroup}"] = nodeGroupID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.SPIDER + urlParam - - pbytes, _ := json.Marshal(nodeGroupReqInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - util.DisplayResponse(resp) // 수신내용 확인 - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - - resultClusterInfo := spider.SpClusterInfo{} - if err != nil { - fmt.Println(err) - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return resultClusterInfo, fwmodels.WebStatus{StatusCode: 500, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&resultClusterInfo) - - return resultClusterInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// NodeGroup 수정 : node Size -func UpdatePmksNodeGroupAutoscaleSize(clusterID string, nodeGroupID string, nodeGroupReqInfo *spider.NodeGroupReqInfo) (spider.SpClusterInfo, fwmodels.WebStatus) { - var originalUrl = "/cluster/{cluster}/nodegroup/{nodegroup}/autoscalesize" - - var paramMapper = make(map[string]string) - paramMapper["{cluster}"] = clusterID - paramMapper["{nodegroup}"] = nodeGroupID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.SPIDER + urlParam - - pbytes, _ := json.Marshal(nodeGroupReqInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - util.DisplayResponse(resp) // 수신내용 확인 - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - - resultClusterInfo := spider.SpClusterInfo{} - if err != nil { - fmt.Println(err) - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return resultClusterInfo, fwmodels.WebStatus{StatusCode: 500, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&resultClusterInfo) - - return resultClusterInfo, fwmodels.WebStatus{StatusCode: respStatus} -} diff --git a/mc_web_console_api/handler/README.md b/mc_web_console_api/handler/README.md deleted file mode 100644 index 3bc39684..00000000 --- a/mc_web_console_api/handler/README.md +++ /dev/null @@ -1,35 +0,0 @@ -API 호출기준 CRUD 에 따른 명명규칙 - -1. 조회(목록) : GetXXXList -2. 조회(항목) : GetXXXData -3. 등록 : RegXXX -4. 삭제 : DelXXX - -CommonHandler - -NameSpaceHandler - -- GetNameSpaceList -- RegNameSpace -- CreateDefaultNameSpace : Namespace가 없는경우 기본으로 1개의 namespace를 자동으로 생성 -- DelNameSpace - -CloudConnectionHandler -ResourceHandler -McisHandler - ---- - -handler의 return 값중 두번째 인자는 model.WebStatus 로 한다. -WebStatus.Status 는 code를, Message에는 message를 -error가 났을 때 Status = 500, Message에는 error의 값을 - -정상적으로 호출했으나 해당 내용이 Error일 때는 최종 수신단(UI)에서 StatusCode에 따라 결정한다. - ---- - -TODO - -1. TB : lookup, search 등 method 호출 테스트 필요(UI등 에서 어떻게 사용될 지) -2. TB : lifecycle 변경의 경우 TB API명세에 없는데 호출 됨. -3. TB : lifecycle 호출하는 handlerMethod 명 변경해야하나?? Get, Reg, Del 외에... diff --git a/mc_web_console_api/handler/ResourceHandler.go b/mc_web_console_api/handler/ResourceHandler.go deleted file mode 100644 index 4684e5d0..00000000 --- a/mc_web_console_api/handler/ResourceHandler.go +++ /dev/null @@ -1,2338 +0,0 @@ -package handler - -import ( - "encoding/json" - "fmt" - "log" - - // "math" - "net/http" - // "strconv" - // "sync" - - //"github.com/davecgh/go-spew/spew" - - // "mc_web_console_api/fwmodels/spider" - // "mc_web_console_api/fwmodels/tumblebug" - "mc_web_console_api/fwmodels" - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - tbmcis "mc_web_console_api/fwmodels/tumblebug/mcis" - - util "mc_web_console_api/util" - - "github.com/gobuffalo/buffalo" -) - -func RegFirewallRules(nameSpaceID string, securityGroupID string, firewallRuleReq *tbmcir.TbFirewallRulesWrapper) (*tbmcir.TbSecurityGroupInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/securityGroup/{securityGroupId}/rules" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{securityGroupId}"] = securityGroupID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(firewallRuleReq) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - securityGroupInfo := tbmcir.TbSecurityGroupInfo{} - if err != nil { - fmt.Println(err) - return &securityGroupInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - log.Println("respStatusCode = ", resp.StatusCode) - log.Println("respStatus = ", resp.Status) - if respStatus != 200 && respStatus != 201 { - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println(errorInfo) - return &securityGroupInfo, fwmodels.WebStatus{StatusCode: 500, Message: errorInfo.Message} - } - - // 응답에 생성한 객체값이 옴 - json.NewDecoder(respBody).Decode(&securityGroupInfo) - fmt.Println(securityGroupInfo) - // return respBody, respStatusCode - return &securityGroupInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func DelFirewallRules(nameSpaceID string, securityGroupID string, firewallRuleReq *tbmcir.TbFirewallRulesWrapper) (*tbmcir.TbSecurityGroupInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/securityGroup/{securityGroupId}/rules" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{securityGroupId}"] = securityGroupID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(firewallRuleReq) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - - securityGroupInfo := tbmcir.TbSecurityGroupInfo{} - if err != nil { - fmt.Println(err) - return &securityGroupInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return &securityGroupInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - json.NewDecoder(respBody).Decode(&securityGroupInfo) - fmt.Println(securityGroupInfo) - return &securityGroupInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 해당 namespace의 vpc 목록 조회 -// func GetVnetList(nameSpaceID string) (io.ReadCloser, error) { -func GetVnetList(nameSpaceID string) ([]tbmcir.TbVNetInfo, fwmodels.WebStatus) { - fmt.Println("GetVnetList ************ : ") - var originalUrl = "/ns/{nsId}/resources/vNet" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/vNet" - - pbytes, _ := json.Marshal(nameSpaceID) - // body, err := util.CommonHttpGet(url) - resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - log.Println(respBody) - vNetInfoList := map[string][]tbmcir.TbVNetInfo{} - json.NewDecoder(respBody).Decode(&vNetInfoList) - //spew.Dump(body) - fmt.Println(vNetInfoList["vNet"]) - - return vNetInfoList["vNet"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// ID목록만 조회 -func GetVnetListByID(nameSpaceID string, filterKeyParam string, filterValParam string) ([]string, fwmodels.WebStatus) { - fmt.Println("GetVnetList ************ : ") - var originalUrl = "/ns/{nsId}/resources/vNet" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - //if optionParam != ""{ - // urlParam += "?option=" + optionParam - //} - urlParam += "?option=id" - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/vNet" - - //pbytes, _ := json.Marshal(nameSpaceID) - // body, err := util.CommonHttpGet(url) - //resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - log.Println(respBody) - //vNetInfoList := map[string][]string{} - vNetInfoList := tbcommon.TbIdList{} - json.NewDecoder(respBody).Decode(&vNetInfoList) - //spew.Dump(body) - //fmt.Println(vNetInfoList["idList"]) - - //return vNetInfoList["idList"], fwmodels.WebStatus{StatusCode: respStatus} - return vNetInfoList.IDList, fwmodels.WebStatus{StatusCode: respStatus} -} - -// List 조회시 optionParam 추가 -func GetVnetListByOption(nameSpaceID string, optionParam string, filterKeyParam string, filterValParam string) ([]tbmcir.TbVNetInfo, fwmodels.WebStatus) { - fmt.Println("GetVnetListByOption ************ : ") - var originalUrl = "/ns/{nsId}/resources/vNet" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - if optionParam != "" { - urlParam += "?option=" + optionParam - } else { - urlParam += "?option=" - } - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/vNet" - - //pbytes, _ := json.Marshal(nameSpaceID) - // body, err := util.CommonHttpGet(url) - //resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - log.Println(respBody) - vNetInfoList := map[string][]tbmcir.TbVNetInfo{} - json.NewDecoder(respBody).Decode(&vNetInfoList) - //spew.Dump(body) - fmt.Println(vNetInfoList["vNet"]) - - return vNetInfoList["vNet"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// vpc 상세 조회-> ResourceHandler로 이동 -func GetVpcData(nameSpaceID string, vNetID string) (*tbmcir.TbVNetInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/vNet/{vNetId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{vNetId}"] = vNetID - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/vNet/" + vNetID - - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - vNetInfo := tbmcir.TbVNetInfo{} - if err != nil { - fmt.Println(err) - return &vNetInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - // json.NewDecoder(body).Decode(&vNetInfo) - json.NewDecoder(respBody).Decode(&vNetInfo) - fmt.Println(vNetInfo) - - // return vNetInfo, err - return &vNetInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// vpc 등록 -// option=register 항목은 TB에서 자동으로 넣을 때 사용하는 param으로 webtool에서 사용하지 않음. -func RegVpc(nameSpaceID string, vnetRegInfo *tbmcir.TbVNetReq) (*tbmcir.TbVNetInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/vNet" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/vNet" - - fmt.Println("vnetRegInfo : ", vnetRegInfo) - - pbytes, _ := json.Marshal(vnetRegInfo) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - vNetInfo := tbmcir.TbVNetInfo{} - if err != nil { - fmt.Println(err) - return &vNetInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - fmt.Println("respStatus ", respStatus) - - if respStatus == 500 { - webStatus := fwmodels.WebStatus{} - json.NewDecoder(respBody).Decode(&webStatus) - fmt.Println(webStatus) - webStatus.StatusCode = respStatus - return &vNetInfo, webStatus - } - // 응답에 생성한 객체값이 옴 - json.NewDecoder(respBody).Decode(&vNetInfo) - fmt.Println(vNetInfo) - - return &vNetInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// vpc 삭제 -func DelVpc(nameSpaceID string, vNetID string) (fwmodels.WebStatus, fwmodels.WebStatus) { - webStatus := fwmodels.WebStatus{} - // if ValidateString(vNetID) != nil { - if len(vNetID) == 0 { - log.Println("vNetID 가 없으면 해당 namespace의 모든 vpc가 삭제되므로 처리할 수 없습니다.") - return webStatus, fwmodels.WebStatus{StatusCode: 4040, Message: "vNetID 가 없으면 해당 namespace의 모든 vpc가 삭제되므로 처리할 수 없습니다."} - } - var originalUrl = "/ns/{nsId}/resources/vNet/{vNetId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{vNetId}"] = vNetID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/vNet/" + vNetID - - fmt.Println("vNetID : ", vNetID) - - pbytes, _ := json.Marshal(vNetID) - resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - - if err != nil { - fmt.Println(err) - return webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return webStatus, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 전체 vpc 삭제 -func DelAllVpc(nameSpaceID string) (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/vNet" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - resp, err := util.CommonHttpWithoutParam(url, http.MethodDelete) - - resultInfo := tbcommon.TbSimpleMsg{} - - if err != nil { - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} - -} - -// Create Subnet -func RegSubnet(nameSpaceID string, vnetId string, subnetReqInfo *tbmcir.TbSubnetReq) (*tbmcir.TbSubnetInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/vNet/{vNetId}/subnet" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{vNetId}"] = vnetId - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/vNet" - - fmt.Println("subnetReqInfo : ", subnetReqInfo) - - pbytes, _ := json.Marshal(subnetReqInfo) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - subnetInfo := tbmcir.TbSubnetInfo{} - if err != nil { - fmt.Println(err) - return &subnetInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - fmt.Println("respStatus ", respStatus) - - if respStatus == 500 { - webStatus := fwmodels.WebStatus{} - json.NewDecoder(respBody).Decode(&webStatus) - fmt.Println(webStatus) - webStatus.StatusCode = respStatus - return &subnetInfo, webStatus - } - // 응답에 생성한 객체값이 옴 - json.NewDecoder(respBody).Decode(&subnetInfo) - fmt.Println(subnetInfo) - - return &subnetInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Delete Subnet -func DelSubnet(nameSpaceID string, vNetID string, subnetID string) (fwmodels.WebStatus, fwmodels.WebStatus) { - webStatus := fwmodels.WebStatus{} - - var originalUrl = "/ns/{nsId}/resources/vNet/{vNetId}/subnet/{subnetId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{vNetId}"] = vNetID - paramMapper["{subnetId}"] = subnetID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - - fmt.Println("vNetID : ", vNetID) - fmt.Println("subnetID : ", subnetID) - - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - - if err != nil { - fmt.Println(err) - return webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return webStatus, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 해당 namespace의 SecurityGroup 목록 조회 -func GetSecurityGroupList(nameSpaceID string) ([]tbmcir.TbSecurityGroupInfo, fwmodels.WebStatus) { - fmt.Println("GetSecurityGroupList ************ : ") - var originalUrl = "/ns/{nsId}/resources/securityGroup" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/securityGroup" - - pbytes, _ := json.Marshal(nameSpaceID) - resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - log.Println(respBody) - securityGroupList := map[string][]tbmcir.TbSecurityGroupInfo{} - - json.NewDecoder(respBody).Decode(&securityGroupList) - //spew.Dump(body) - fmt.Println(securityGroupList["securityGroup"]) - - return securityGroupList["securityGroup"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// ID만 조회 -func GetSecurityGroupListByOptionID(nameSpaceID string, optionParam string, filterKeyParam string, filterValParam string) ([]string, fwmodels.WebStatus) { - fmt.Println("GetSecurityGroupListByOptionID ************ : ") - var originalUrl = "/ns/{nsId}/resources/securityGroup" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - if optionParam != "" { - urlParam += "?option=" + optionParam - } else { - urlParam += "?option=" - } - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/securityGroup" - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - //resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - - if err != nil { - // // Tumblebug 접속 확인하라고 - // fmt.Println(err) - // panic(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - //securityGroupList := map[string][]string{} - securityGroupList := tbcommon.TbIdList{} - // defer body.Close() - json.NewDecoder(respBody).Decode(&securityGroupList) - //spew.Dump(body) - //fmt.Println(securityGroupList["idList"]) - fmt.Println(securityGroupList.IDList) - - //return securityGroupList["idList"], fwmodels.WebStatus{StatusCode: respStatus} - return securityGroupList.IDList, fwmodels.WebStatus{StatusCode: respStatus} -} - -// SecurityGroupList 조회 시 Option에 해당하는 값만 조회. GetSecurityGroupList와 TB 호출은 동일하나 option 사용으로 받아오는 param이 다름 -func GetSecurityGroupListByOption(nameSpaceID string, optionParam string, filterKeyParam string, filterValParam string) ([]tbmcir.TbSecurityGroupInfo, fwmodels.WebStatus) { - fmt.Println("GetSecurityGroupListByOption ************ : ") - var originalUrl = "/ns/{nsId}/resources/securityGroup" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - if optionParam != "" { - urlParam += "?option=" + optionParam - } else { - urlParam += "?option=" - } - if filterKeyParam != "" { - if filterKeyParam == "vpcId" { - filterKeyParam = "vNetId" // tb는 vNetId로 지칭하고 mcon에서는 vpc로 지칭함 - } - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/securityGroup" - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - //resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - - if err != nil { - // // Tumblebug 접속 확인하라고 - // fmt.Println(err) - // panic(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - securityGroupList := map[string][]tbmcir.TbSecurityGroupInfo{} - - json.NewDecoder(respBody).Decode(&securityGroupList) - //spew.Dump(body) - fmt.Println(securityGroupList["securityGroup"]) - - return securityGroupList["securityGroup"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// SecurityGroup 상세 조회 -func GetSecurityGroupData(nameSpaceID string, securityGroupID string) (*tbmcir.TbSecurityGroupInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/securityGroup/{securityGroupId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{securityGroupId}"] = securityGroupID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/securityGroup/" + securityGroupID - - fmt.Println("nameSpaceID : ", nameSpaceID) - - // pbytes, _ := json.Marshal(nameSpaceID) - // body, err := util.CommonHttpGet(url) - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - securityGroupInfo := tbmcir.TbSecurityGroupInfo{} - if err != nil { - fmt.Println(err) - return &securityGroupInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&securityGroupInfo) - fmt.Println(securityGroupInfo) - - return &securityGroupInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// SecurityGroup 등록 -// option=register 항목은 TB에서 자동으로 넣을 때 사용하는 param으로 webtool에서 사용하지 않음. -func RegSecurityGroup(nameSpaceID string, securityGroupRegInfo *tbmcir.TbSecurityGroupReq) (*tbmcir.TbSecurityGroupInfo, fwmodels.WebStatus) { - fmt.Println("RegSecurityGroup : ") - - var originalUrl = "/ns/{nsId}/resources/securityGroup" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/securityGroup" - - pbytes, _ := json.Marshal(securityGroupRegInfo) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - securityGroupInfo := tbmcir.TbSecurityGroupInfo{} - if err != nil { - log.Println("-----") - fmt.Println(err) - log.Println("-----1111") - fmt.Println(err.Error()) - log.Println("-----222") - return &securityGroupInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - log.Println("respStatusCode = ", resp.StatusCode) - log.Println("respStatus = ", resp.Status) - if respStatus != 200 && respStatus != 201 { - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println(errorInfo) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: errorInfo.Message} - } - - // 응답에 생성한 객체값이 옴 - json.NewDecoder(respBody).Decode(&securityGroupInfo) - fmt.Println(securityGroupInfo) - // return respBody, respStatusCode - return &securityGroupInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 해당 Namespace의 모든 SecurityGroup 삭제 -func DelAllSecurityGroup(nameSpaceID string) (fwmodels.WebStatus, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/securityGroup" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/securityGroup/" - - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - webStatus := fwmodels.WebStatus{} - if err != nil { - fmt.Println(err) - return webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return webStatus, fwmodels.WebStatus{StatusCode: respStatus} - - //return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// SecurityGroup 삭제 -func DelSecurityGroup(nameSpaceID string, securityGroupID string) (fwmodels.WebStatus, fwmodels.WebStatus) { - webStatus := fwmodels.WebStatus{} - // if ValidateString(vNetID) != nil { - if len(securityGroupID) == 0 { - log.Println("securityGroupID 가 없으면 해당 namespace의 모든 securityGroup이 삭제되므로 처리할 수 없습니다.") - return webStatus, fwmodels.WebStatus{StatusCode: 4040, Message: "securityGroupID 가 없으면 해당 namespace의 모든 securityGroup이 삭제되므로 처리할 수 없습니다."} - } - - var originalUrl = "/ns/{nsId}/resources/securityGroup/{securityGroupId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{securityGroupId}"] = securityGroupID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/securityGroup/" + securityGroupID - - fmt.Println("securityGroupID : ", securityGroupID) - - pbytes, _ := json.Marshal(securityGroupID) - resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - - if err != nil { - fmt.Println(err) - return webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return webStatus, fwmodels.WebStatus{StatusCode: respStatus} - // respStatus := resp.Status - // log.Println("respStatusCode = ", respStatusCode) - // log.Println("respStatus = ", respStatus) - - // return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// SSHKey 목록 조회 : /ns/{nsId}/resources/sshKey -func GetSshKeyInfoList(nameSpaceID string) ([]tbmcir.TbSshKeyInfo, fwmodels.WebStatus) { - fmt.Println("GetSshKeyInfoList ************ : ") - var originalUrl = "/ns/{nsId}/resources/sshKey" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/sshKey" - - pbytes, _ := json.Marshal(nameSpaceID) - resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - log.Println(respBody) - sshKeyList := map[string][]tbmcir.TbSshKeyInfo{} - - json.NewDecoder(respBody).Decode(&sshKeyList) - //spew.Dump(body) - fmt.Println(sshKeyList["sshKey"]) - - return sshKeyList["sshKey"], fwmodels.WebStatus{StatusCode: respStatus} - -} - -func GetSshKeyInfoListByID(nameSpaceID string, filterKeyParam string, filterValParam string) ([]string, fwmodels.WebStatus) { - log.Println("GetSshKeyInfoListByID ************ : ") - log.Println("namespaceID : ", nameSpaceID) - var originalUrl = "/ns/{nsId}/resources/sshKey" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - //url := util.TUMBLEBUG + urlParam - urlParam += "?option=id" - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/sshKey" - - //resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - log.Println("*************** respBody : ", respBody) - - //sshKeyList := map[string][]string{} - sshKeyList := tbcommon.TbIdList{} - // defer body.Close() - json.NewDecoder(respBody).Decode(&sshKeyList) - //spew.Dump(body) - //log.Println(sshKeyList["idList"]) - log.Println(sshKeyList.IDList) - - //return sshKeyList["idList"], fwmodels.WebStatus{StatusCode: respStatus} - return sshKeyList.IDList, fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetSshKeyInfoListByOption(nameSpaceID string, optionParam string, filterKeyParam string, filterValParam string) ([]tbmcir.TbSshKeyInfo, fwmodels.WebStatus) { - fmt.Println("GetSshKeyInfoList ************ : ") - var originalUrl = "/ns/{nsId}/resources/sshKey" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - if optionParam != "" { - urlParam += "?option=" + optionParam - } else { - urlParam += "?option=" - } - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/sshKey" - - //resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - log.Println(respBody) - sshKeyList := map[string][]tbmcir.TbSshKeyInfo{} - - json.NewDecoder(respBody).Decode(&sshKeyList) - //spew.Dump(body) - fmt.Println(sshKeyList["sshKey"]) - - return sshKeyList["sshKey"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// sshKey 상세 조회 -func GetSshKeyData(nameSpaceID string, sshKeyID string) (*tbmcir.TbSshKeyInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/sshKey/{sshKeyId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{sshKeyId}"] = sshKeyID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/sshKey/" + sshKeyID - - fmt.Println("nameSpaceID : ", nameSpaceID) - - // pbytes, _ := json.Marshal(nameSpaceID) - // body, err := util.CommonHttpGet(url) - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - sshKeyInfo := tbmcir.TbSshKeyInfo{} - if err != nil { - fmt.Println(err) - return &sshKeyInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&sshKeyInfo) - fmt.Println(sshKeyInfo) - - return &sshKeyInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// sshKey 등록 -// option=register 항목은 TB에서 자동으로 넣을 때 사용하는 param으로 webtool에서 사용하지 않음. -func RegSshKey(nameSpaceID string, sshKeyRegInfo *tbmcir.TbSshKeyReq) (*tbmcir.TbSshKeyInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/sshKey" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/sshKey" - - // fmt.Println("vnetInfo : ", vnetInfo) - - pbytes, _ := json.Marshal(sshKeyRegInfo) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - sshKeyInfo := tbmcir.TbSshKeyInfo{} - if err != nil { - fmt.Println(err) - return &sshKeyInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - log.Println("resp = ", resp) - respBody := resp.Body - respStatus := resp.StatusCode - log.Println("respBody = ", respBody) - // respStatus := resp.Status - // log.Println("respStatusCode = ", respStatusCode) - // log.Println("respStatus = ", respStatus) - - // 응답에 생성한 객체값이 옴 - - json.NewDecoder(respBody).Decode(&sshKeyInfo) - fmt.Println(sshKeyInfo) - // return respBody, respStatusCode - return &sshKeyInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func UpdateSshKey(nameSpaceID string, sshKeyId string, sshKeyInfo *tbmcir.TbSshKeyInfo) (*tbmcir.TbSshKeyInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/sshKey/{sshKeyId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{sshKeyId}"] = sshKeyId - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/sshKey" - - // fmt.Println("vnetInfo : ", vnetInfo) - - pbytes, _ := json.Marshal(sshKeyInfo) - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - sshKeyInfoResponse := tbmcir.TbSshKeyInfo{} - if err != nil { - fmt.Println(err) - return &sshKeyInfoResponse, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - log.Println("resp = ", resp) - respBody := resp.Body - respStatus := resp.StatusCode - log.Println("respBody = ", respBody) - - json.NewDecoder(respBody).Decode(&sshKeyInfoResponse) - fmt.Println(sshKeyInfoResponse) - - return &sshKeyInfoResponse, fwmodels.WebStatus{StatusCode: respStatus} -} - -// sshKey 삭제 -func DelSshKey(nameSpaceID string, sshKeyID string) (fwmodels.WebStatus, fwmodels.WebStatus) { - webStatus := fwmodels.WebStatus{} - // if ValidateString(sshKeyID) != nil { - if len(sshKeyID) == 0 { - log.Println("sshKeyID 가 없으면 해당 namespace의 모든 sshKeyID 삭제되므로 처리할 수 없습니다.") - return webStatus, fwmodels.WebStatus{StatusCode: 4040, Message: "sshKeyID 가 없으면 해당 namespace의 모든 sshKeyID 삭제되므로 처리할 수 없습니다."} - } - - var originalUrl = "/ns/{nsId}/resources/sshKey/{sshKeyId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{sshKeyId}"] = sshKeyID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/sshKey/" + sshKeyID - - fmt.Println("sshKeyID : ", sshKeyID) - - pbytes, _ := json.Marshal(sshKeyID) - resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - - if err != nil { - fmt.Println(err) - return webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - fmt.Println("resp : ", resp) - - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return webStatus, fwmodels.WebStatus{StatusCode: respStatus} - // return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 전체 sshKey 삭제 -func DelAllSshKey(nameSpaceID string) (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/sshKey" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - - resp, err := util.CommonHttpWithoutParam(url, http.MethodDelete) - - resultInfo := tbcommon.TbSimpleMsg{} - - if err != nil { - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} - -} - -// VirtualMachineImage 목록 조회 -func GetVirtualMachineImageInfoList(nameSpaceID string) ([]tbmcir.TbImageInfo, fwmodels.WebStatus) { - fmt.Println("GetVirtualMachineImageInfoList ************ : ") - // var originalUrl = "/ns/{nsId}/resources/image" - var originalUrl = "/ns/{nsId}/resources/image" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/image" - - pbytes, _ := json.Marshal(nameSpaceID) - resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // TODO : defer를 넣어줘야 할 듯. defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - virtualMachineImageList := map[string][]tbmcir.TbImageInfo{} - - json.NewDecoder(respBody).Decode(&virtualMachineImageList) - fmt.Println(virtualMachineImageList["image"]) - - // robots, err := ioutil.ReadAll(resp.Body) - // if err != nil { - // log.Fatal(err) - // } - // fmt.Printf("%s", robots) - - return virtualMachineImageList["image"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// VirtualMachineImage 목록에서 Option으로 ID 목록만 가져오는 function -func GetVirtualMachineImageInfoListByID(nameSpaceID string, filterKeyParam string, filterValParam string) ([]string, fwmodels.WebStatus) { - fmt.Println("GetVirtualMachineImageInfoListByID ************ : ") - // var originalUrl = "/ns/{nsId}/resources/image" - var originalUrl = "/ns/{nsId}/resources/image" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - - // url := util.TUMBLEBUG + urlParam - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - //if optionParam != ""{ - // urlParam += "?option=" + optionParam - //} - urlParam += "?option=id" - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - url := util.TUMBLEBUG + urlParam - //url := util.TUMBLEBUG + urlParam + optionParamVal - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/image" - - pbytes, _ := json.Marshal(nameSpaceID) - resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // TODO : defer를 넣어줘야 할 듯. defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // virtualMachineImageIdList := map[string][]tbcommon.TbIdList{} - virtualMachineImageIdList := tbcommon.TbIdList{} - - json.NewDecoder(respBody).Decode(&virtualMachineImageIdList) - //fmt.Println(virtualMachineImageIdList.IDList) - - // robots, err := ioutil.ReadAll(resp.Body) - // if err != nil { - // log.Fatal(err) - // } - // fmt.Printf("%s", robots) - - return virtualMachineImageIdList.IDList, fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetVirtualMachineImageInfoListByOption(nameSpaceID string, optionParam string, filterKeyParam string, filterValParam string) ([]tbmcir.TbImageInfo, fwmodels.WebStatus) { - fmt.Println("GetVirtualMachineImageInfoListByOption ************ : ") - // var originalUrl = "/ns/{nsId}/resources/image" - var originalUrl = "/ns/{nsId}/resources/image" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - - // url := util.TUMBLEBUG + urlParam - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - if optionParam != "" { - urlParam += "?option=" + optionParam - } else { - urlParam += "?option=" - } - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - url := util.TUMBLEBUG + urlParam - //url := util.TUMBLEBUG + urlParam + optionParamVal - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/image" - - pbytes, _ := json.Marshal(nameSpaceID) - resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // TODO : defer를 넣어줘야 할 듯. defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - virtualMachineImageList := map[string][]tbmcir.TbImageInfo{} - - json.NewDecoder(respBody).Decode(&virtualMachineImageList) - fmt.Println(virtualMachineImageList["image"]) - - // robots, err := ioutil.ReadAll(resp.Body) - // if err != nil { - // log.Fatal(err) - // } - // fmt.Printf("%s", robots) - - return virtualMachineImageList["image"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// VirtualMachineImage 상세 조회 -func GetVirtualMachineImageData(nameSpaceID string, virtualMachineImageID string) (*tbmcir.TbImageInfo, fwmodels.WebStatus) { - fmt.Println("GetVirtualMachineImageData ************ : ") - var originalUrl = "/ns/{nsId}/resources/image/{imageId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{imageId}"] = virtualMachineImageID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/image/" + virtualMachineImageID - - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - virtualMachineImageInfo := tbmcir.TbImageInfo{} - if err != nil { - fmt.Println(err) - return &virtualMachineImageInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&virtualMachineImageInfo) - fmt.Println(virtualMachineImageInfo) - - return &virtualMachineImageInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func UpdateVirtualMachineImage(nameSpaceID string, virtualMachineImageID string, imageInfo *tbmcir.TbImageInfo) (*tbmcir.TbImageInfo, fwmodels.WebStatus) { - fmt.Println("UpdateVirtualMachineImageData ************ : ") - var originalUrl = "/ns/{nsId}/resources/image/{imageId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{imageId}"] = virtualMachineImageID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/image/" + virtualMachineImageID - - pbytes, _ := json.Marshal(imageInfo) // action=registerWithInfo, registerWithId param이 regInfo안에 모두 있으므로 별도로 나누어 호출하지않고 그냥 사용 - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - virtualMachineImageInfo := tbmcir.TbImageInfo{} - if err != nil { - fmt.Println(err) - return &virtualMachineImageInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&virtualMachineImageInfo) - fmt.Println(virtualMachineImageInfo) - - return &virtualMachineImageInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// VirtualMachineImage 등록 registeringMethod = imageID -func RegVirtualMachineImage(nameSpaceID string, registType string, virtualMachineImageRegInfo *tbmcir.TbImageReq) (*tbmcir.TbImageInfo, fwmodels.WebStatus) { - fmt.Println("RegVirtualMachineImage ************ : ") - log.Println("*********************** virtualMachineImageRegInfo :") - log.Println(virtualMachineImageRegInfo) - log.Println("***********************") - if registType == "" { - registType = "registerWithId" // registerWithId 또는 registerWithInfo - } - - // API에는 registeringMethod로 표현되어있으나 실제로는 action임. - var originalUrl = "/ns/{nsId}/resources/image?action=registerWithId" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{registType}"] = registType - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/image?action=registerWithInfo" // - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/image?action=registerWithId"// - - pbytes, _ := json.Marshal(virtualMachineImageRegInfo) // action=registerWithInfo, registerWithId param이 regInfo안에 모두 있으므로 별도로 나누어 호출하지않고 그냥 사용 - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - virtualMachineImageInfo := tbmcir.TbImageInfo{} - if err != nil { - fmt.Println(err) - return &virtualMachineImageInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - // data, err := ioutil.ReadAll(resp.Body) - // if err != nil { - // panic(err) - // } - // fmt.Printf("%s\n", string(data)) - - respBody := resp.Body - respStatus := resp.StatusCode - // respStatus := resp.Status - // log.Println("respStatusCode = ", respStatusCode) - // log.Println("respStatus = ", respStatus) - - // 응답에 생성한 객체값이 옴 - - json.NewDecoder(respBody).Decode(&virtualMachineImageInfo) - fmt.Println(virtualMachineImageInfo) - // return respBody, respStatusCode - return &virtualMachineImageInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// VirtualMachineImage 등록 registeringMethod = imageID -// 생성시 action에 regist -func RegVirtualMachineImageWithInfo(nameSpaceID string, registType string, virtualMachineImageRegInfo *tbmcir.TbImageInfo) (*tbmcir.TbImageInfo, fwmodels.WebStatus) { - fmt.Println("RegVirtualMachineImage ************ : ") - if registType == "" { - registType = "registerWithId" // registerWithId 또는 registerWithInfo - } - - var originalUrl = "/ns/{nsId}/resources/image?registeringMethod=registerWithInfo" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{registType}"] = registType - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/image?action=registerWithInfo" // - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/image?action=registerWithId"// - - pbytes, _ := json.Marshal(virtualMachineImageRegInfo) // action=registerWithInfo, registerWithId param이 regInfo안에 모두 있으므로 별도로 나누어 호출하지않고 그냥 사용 - fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - virtualMachineImageInfo := tbmcir.TbImageInfo{} - if err != nil { - fmt.Println(err) - return &virtualMachineImageInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - // data, err := ioutil.ReadAll(resp.Body) - // if err != nil { - // panic(err) - // } - // fmt.Printf("%s\n", string(data)) - - respBody := resp.Body - respStatus := resp.StatusCode - // respStatus := resp.Status - // log.Println("respStatusCode = ", respStatusCode) - // log.Println("respStatus = ", respStatus) - - // 응답에 생성한 객체값이 옴 - - json.NewDecoder(respBody).Decode(&virtualMachineImageInfo) - fmt.Println(virtualMachineImageInfo) - // return respBody, respStatusCode - return &virtualMachineImageInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 해당 namespace의 모든 VirtualMachineImage 삭제 -func DelAllVirtualMachineImage(nameSpaceID string) (fwmodels.WebStatus, fwmodels.WebStatus) { - // if ValidateString(VirtualMachineImageID) != nil { - var originalUrl = "/ns/{nsId}/resources/image" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/image" - - // resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - resp, err := util.CommonHttpWithoutParam(url, http.MethodDelete) - webStatus := fwmodels.WebStatus{} - if err != nil { - fmt.Println(err) - return webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return webStatus, fwmodels.WebStatus{StatusCode: respStatus} - // return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 해당 namespace의 특정 VirtualMachineImage 삭제 -func DelVirtualMachineImage(nameSpaceID string, virtualMachineImageID string) (fwmodels.WebStatus, fwmodels.WebStatus) { - webStatus := fwmodels.WebStatus{} - // if ValidateString(VirtualMachineImageID) != nil { - if len(virtualMachineImageID) == 0 { - log.Println("ImageID 가 없으면 해당 namespace의 모든 image가 삭제되므로 처리할 수 없습니다.") - return webStatus, fwmodels.WebStatus{StatusCode: 4040, Message: "ImageID 가 없으면 해당 namespace의 모든 image가 삭제되므로 처리할 수 없습니다."} - } - - var originalUrl = "/ns/{nsId}/resources/image/{imageId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{imageId}"] = virtualMachineImageID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/image/" + virtualMachineImageID - - pbytes, _ := json.Marshal(virtualMachineImageID) - resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - - if err != nil { - fmt.Println(err) - return webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return webStatus, fwmodels.WebStatus{StatusCode: respStatus} - // return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 자신의 provider에 등록된 resource 조회 -func GetInspectResourceList(inspectResource *tbcommon.RestInspectResourcesRequest) (*tbmcis.InspectResource, fwmodels.WebStatus) { - fmt.Println("GetInspectResourceList ************ : ") - //https://www.javaer101.com/ko/article/5704925.html 참조 : 값이 있는 것만 넘기기 - var originalUrl = "/inspectResources" - urlParam := util.MappingUrlParameter(originalUrl, nil) - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(inspectResource) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - respBody := resp.Body - respStatus := resp.StatusCode - - inspectResourcesResponse := tbmcis.InspectResource{} - if err != nil { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println(failResultInfo) - //return &inspectResourcesResponse, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - return &inspectResourcesResponse, fwmodels.WebStatus{StatusCode: 500, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&inspectResourcesResponse) - fmt.Println(inspectResourcesResponse) - - return &inspectResourcesResponse, fwmodels.WebStatus{StatusCode: respStatus} - -} - -/* -CSP와 Tumblebug에 등록된 모든 리소스 비교 -전체이므로 별도의 parameter 없음. -*/ -func GetInspectResourcesOverview() (*tbmcis.InspectResourceAllResult, fwmodels.WebStatus) { - fmt.Println("Inspect Resources Overview (vNet, securityGroup, sshKey, vm) registered in CB-Tumblebug and CSP for all connections") - var originalUrl = "/inspectResourcesOverview" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns" - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - respBody := resp.Body - respStatus := resp.StatusCode - - inspectResourceAllResult := tbmcis.InspectResourceAllResult{} - if err != nil { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println(failResultInfo) - //return &inspectResourcesResponse, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - return &inspectResourceAllResult, fwmodels.WebStatus{StatusCode: 500, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&inspectResourceAllResult) - fmt.Println(inspectResourceAllResult) - - return &inspectResourceAllResult, fwmodels.WebStatus{StatusCode: respStatus} -} - -func RegCspResources(resourcesRequest *tbcommon.RestRegisterCspNativeResourcesRequest, optionParam string) (*tbmcis.RegisterResourceResult, fwmodels.WebStatus) { - var originalUrl = "/registerCspResources" - urlParam := util.MappingUrlParameter(originalUrl, nil) - if optionParam != "" { - urlParam += "?option=" + optionParam - } - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(resourcesRequest) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - respBody := resp.Body - respStatus := resp.StatusCode - - registerResourceResult := tbmcis.RegisterResourceResult{} - if err != nil { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println(failResultInfo) - //return &inspectResourcesResponse, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - return ®isterResourceResult, fwmodels.WebStatus{StatusCode: 500, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(registerResourceResult) - fmt.Println(registerResourceResult) - - return ®isterResourceResult, fwmodels.WebStatus{StatusCode: respStatus} - -} - -func RegCspResourcesAll(resourcesRequest *tbcommon.RestRegisterCspNativeResourcesRequestAll, optionParam string) (*tbmcis.RegisterResourceAllResult, fwmodels.WebStatus) { - var originalUrl = "/registerCspResourcesAll" - urlParam := util.MappingUrlParameter(originalUrl, nil) - if optionParam != "" { - urlParam += "?option=" + optionParam - } - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(resourcesRequest) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - respBody := resp.Body - respStatus := resp.StatusCode - - registerResourceResult := tbmcis.RegisterResourceAllResult{} - if err != nil { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println(failResultInfo) - //return &inspectResourcesResponse, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - return ®isterResourceResult, fwmodels.WebStatus{StatusCode: 500, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(registerResourceResult) - fmt.Println(registerResourceResult) - - return ®isterResourceResult, fwmodels.WebStatus{StatusCode: respStatus} - -} - -func GetLoadCommonResource() (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - fmt.Println("Load Common Resources from internal asset files (Spec, Image)") - var originalUrl = "/loadCommonResource" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns" - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - - resultInfo := tbcommon.TbSimpleMsg{} - - if err != nil { - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// VM Image 조회 -func LookupVirtualMachineImageList(connectionName string) (tbmcir.SpiderImageInfos, fwmodels.WebStatus) { - fmt.Println("LookupVirtualMachineImageList ************ : ", connectionName) - var originalUrl = "/lookupImages" - urlParam := util.MappingUrlParameter(originalUrl, nil) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/lookupImage" - - // body, err := util.CommonHttpGet(url) - // resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - //common.TbConnectionName - paramMap := map[string]string{"connectionName": connectionName} - - pbytes, _ := json.Marshal(paramMap) - log.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - log.Println("LookupVirtualMachineImageList called 1 ") - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - log.Println("LookupVirtualMachineImageList called 2 ", respStatus) - // return respBody, respStatus - // log.Println(respBody) - lookupImageList := map[string]tbmcir.SpiderImageInfos{} - - json.NewDecoder(respBody).Decode(&lookupImageList) - log.Println("LookupVirtualMachineImageList called 3 ") - - return lookupImageList["image"], fwmodels.WebStatus{StatusCode: respStatus} -} - -// deprecated : imageId 받는 것에서 connection 받는 것 까지로 변경 됨 -// func LookupVirtualMachineImageData(virtualMachineImageID string) (*tbmcir.TbImageInfo, fwmodels.WebStatus) { -// var originalUrl = "/lookupImage/{imageId}" -// var paramMapper = make(map[string]string) -// paramMapper["{imageId}"] = virtualMachineImageID -// urlParam := util.MappingUrlParameter(originalUrl, paramMapper) -// url := util.TUMBLEBUG + urlParam -// // url := util.TUMBLEBUG + "/lookupImage/" + virtualMachineImageID - -// // pbytes, _ := json.Marshal(nameSpaceID) -// resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) -// virtualMachineImageInfo := tbmcir.TbImageInfo{} -// if err != nil { -// fmt.Println(err) -// return &virtualMachineImageInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} -// } - -// respBody := resp.Body -// respStatus := resp.StatusCode - -// json.NewDecoder(respBody).Decode(virtualMachineImageInfo) -// fmt.Println(virtualMachineImageInfo) - -// return &virtualMachineImageInfo, fwmodels.WebStatus{StatusCode: respStatus} -// } - -// 특정 provider의 특정 image정보 조회 -func LookupVirtualMachineImageData(restLookupImageRequest *tbmcir.RestLookupImageRequest) (*tbmcir.SpiderImageInfo, fwmodels.WebStatus) { - var originalUrl = "/lookupImage" - var paramMapper = make(map[string]string) - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(restLookupImageRequest) - //resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - virtualMachineImageInfo := tbmcir.SpiderImageInfo{} - if err != nil { - fmt.Println(err) - return &virtualMachineImageInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(virtualMachineImageInfo) - fmt.Println(virtualMachineImageInfo) - - return &virtualMachineImageInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// csp에 등록된 정보조회. -func FetchVirtualMachineImageList(nameSpaceID string) ([]tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - fmt.Println("FetchVirtualMachineImageList ************ : ", nameSpaceID) - var originalUrl = "/ns/{nsId}/resources/fetchImages" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/fetchImages" - - resp, err := util.CommonHttp(url, nil, http.MethodPost) - // resp, err := util.CommonHttpWithoutParam(url, http.MethodPost) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - fetchImageList := map[string]tbmcir.SpiderImageInfos{} - - json.NewDecoder(respBody).Decode(&fetchImageList) - log.Println("FetchVirtualMachineImageList called ") - - // return fetchImageList["image"], fwmodels.WebStatus{StatusCode: respStatus} - return nil, fwmodels.WebStatus{StatusCode: respStatus} // TODO : simpleMsg return 하도록 변경할 것 -} - -// VirtualMachineImage 상세 조회 -func SearchVirtualMachineImageList(nameSpaceID string, restSearchImageRequest *tbmcir.RestSearchImageRequest) ([]tbmcir.TbImageInfo, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/resources/searchImage" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/searchImage/" - - // pbytes, _ := json.Marshal(nameSpaceID) - pbytes, _ := json.Marshal(restSearchImageRequest) - // resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - virtualMachineImageInfo := tbmcir.RestGetAllImageResponse{} - if err != nil { - fmt.Println(err) - return virtualMachineImageInfo.Image, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&virtualMachineImageInfo) - fmt.Println(virtualMachineImageInfo) - - return virtualMachineImageInfo.Image, fwmodels.WebStatus{StatusCode: respStatus} -} - -// VMSpec 목록 조회 -func GetVmSpecInfoList(nameSpaceID string) ([]tbmcir.TbSpecInfo, fwmodels.WebStatus) { - fmt.Println("GetVMSpecInfoList ************ : ") - var originalUrl = "/ns/{nsId}/resources/spec" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/spec" - - // pbytes, _ := json.Marshal(nameSpaceID) - // resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // TODO : defer를 넣어줘야 할 듯. defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - log.Println(respBody) - vmSpecList := tbmcir.RestGetAllSpecResponse{} - - json.NewDecoder(respBody).Decode(&vmSpecList) - //spew.Dump(body) - fmt.Println(vmSpecList.Spec) - - return vmSpecList.Spec, fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetVmSpecInfoListByID(nameSpaceID string, filterKeyParam string, filterValParam string) ([]string, fwmodels.WebStatus) { - fmt.Println("GetVMSpecInfoList ************ : ") - var originalUrl = "/ns/{nsId}/resources/spec" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - // url := util.TUMBLEBUG + urlParam - - //if optionParam != ""{ - // urlParam += "?option=" + optionParam - //} - urlParam += "?option=id" - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/spec" - - // pbytes, _ := json.Marshal(nameSpaceID) - // resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // TODO : defer를 넣어줘야 할 듯. defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - log.Println(respBody) - vmSpecList := tbcommon.TbIdList{} - - json.NewDecoder(respBody).Decode(&vmSpecList) - //spew.Dump(body) - fmt.Println(vmSpecList.IDList) - - return vmSpecList.IDList, fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetVmSpecInfoListByOption(nameSpaceID string, optionParam string, filterKeyParam string, filterValParam string) ([]tbmcir.TbSpecInfo, fwmodels.WebStatus) { - log.Println("GetVMSpecInfoList ************ : ") - var originalUrl = "/ns/{nsId}/resources/spec" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - if optionParam != "" { - urlParam += "?option=" + optionParam - } else { - urlParam += "?option=" - } - if filterKeyParam != "" { - urlParam += "&filterKey=" + filterKeyParam - urlParam += "&filterVal=" + filterValParam - } - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/spec" - - // pbytes, _ := json.Marshal(nameSpaceID) - // resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // TODO : defer를 넣어줘야 할 듯. defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - // return respBody, respStatus - log.Println(respBody) - vmSpecList := tbmcir.RestGetAllSpecResponse{} - - json.NewDecoder(respBody).Decode(&vmSpecList) - //spew.Dump(body) - fmt.Println(vmSpecList.Spec) - - return vmSpecList.Spec, fwmodels.WebStatus{StatusCode: respStatus} -} - -// VMSpec 상세 조회 -func GetVmSpecInfoData(nameSpaceID string, vmSpecID string) (*tbmcir.TbSpecInfo, fwmodels.WebStatus) { - fmt.Println("GetVMSpecInfoData ************ : ") - var originalUrl = "/ns/{nsId}/resources/spec/{specId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{specId}"] = vmSpecID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/spec/" + vmSpecID - - // pbytes, _ := json.Marshal(nameSpaceID) - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - vmSpecInfo := tbmcir.TbSpecInfo{} - if err != nil { - fmt.Println(err) - return &vmSpecInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&vmSpecInfo) - fmt.Println(vmSpecInfo) - - return &vmSpecInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// VMSpecInfo 등록 -func RegVmSpec(nameSpaceID string, specregisteringMethod string, vmSpecRegInfo *tbmcir.TbSpecReq) (*tbmcir.TbSpecInfo, fwmodels.WebStatus) { - fmt.Println("RegVMSpec ************ : ") - log.Println("**********namespace ID : ", nameSpaceID) - log.Println("**************************************") - if specregisteringMethod == "" { - specregisteringMethod = "registerWithInfo" // registerWithInfo or Else 이므로 registerWithInfo 를 넣거나 아니거나. - } - - // else인 경우에는 4개의 parameter만 있음{ - // "connectionName": "string", - // "cspSpecName": "string", - // "description": "string", - // "name": "string" - // } - var originalUrl = "/ns/{nsId}/resources/spec?registeringMethod={specregisteringMethod}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{specregisteringMethod}"] = specregisteringMethod - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // "https://localhost:1323/tumblebug/ns/ns01/resources/spec?registeringMethod=registerWithInfo" - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/spec?action=registerWithInfo"// parameter를 모두 받지않기 때문에 param의 data type이 틀려 오류남. - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/spec" // 그래서 action 인자없이 전송 - - pbytes, _ := json.Marshal(vmSpecRegInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - vmSpecInfo := tbmcir.TbSpecInfo{} - if err != nil { - fmt.Println(err) - return &vmSpecInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - // 응답에 생성한 객체값이 옴 - returnStatus := fwmodels.WebStatus{} - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&vmSpecInfo) - fmt.Println(vmSpecInfo) - } - returnStatus.StatusCode = respStatus - - // return respBody, respStatusCode - return &vmSpecInfo, returnStatus -} - -// specRegisteringMethod에 따라 requestMethod가 다르므로 function 분리 함 -func RegVmSpecWithInfo(nameSpaceID string, specregisteringMethod string, vmSpecRegInfo *tbmcir.TbSpecInfo) (*tbmcir.TbSpecInfo, fwmodels.WebStatus) { - fmt.Println("RegVMSpec ************ : ") - if specregisteringMethod == "" { - specregisteringMethod = "registerWithInfo" // registerWithInfo or Else 이므로 registerWithInfo 를 넣거나 아니거나. - } - - // else인 경우에는 4개의 parameter만 있음{ - // "connectionName": "string", - // "cspSpecName": "string", - // "description": "string", - // "name": "string" - // } - //var originalUrl = "/ns/{nsId}/resources/spec?registeringMethod={specregisteringMethod}" - var originalUrl = "/ns/{nsId}/resources/spec?registeringMethod={specregisteringMethod}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{specregisteringMethod}"] = specregisteringMethod - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // "https://localhost:1323/tumblebug/ns/ns01/resources/spec?registeringMethod=registerWithInfo" - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/spec?action=registerWithInfo"// parameter를 모두 받지않기 때문에 param의 data type이 틀려 오류남. - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/spec" // 그래서 action 인자없이 전송 - - pbytes, _ := json.Marshal(vmSpecRegInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - vmSpecInfo := tbmcir.TbSpecInfo{} - if err != nil { - fmt.Println(err) - return &vmSpecInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - // 응답에 생성한 객체값이 옴 - returnStatus := fwmodels.WebStatus{} - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - errorInfo := fwmodels.ErrorInfo{} - json.NewDecoder(respBody).Decode(&errorInfo) - fmt.Println("respStatus != 200 reason ", errorInfo) - returnStatus.Message = errorInfo.Message - } else { - json.NewDecoder(respBody).Decode(&vmSpecInfo) - fmt.Println(vmSpecInfo) - } - returnStatus.StatusCode = respStatus - - // return respBody, respStatusCode - return &vmSpecInfo, returnStatus -} - -func UpdateVMSpec(nameSpaceID string, vmSpecRegInfo *tbmcir.TbSpecInfo) (*tbmcir.TbSpecInfo, fwmodels.WebStatus) { - fmt.Println("UpdateVMSpec ************ : ") - vmSpecID := vmSpecRegInfo.ID - var originalUrl = "/ns/{nsId}/resources/spec/{specId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{specId}"] = vmSpecID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/spec" - - pbytes, _ := json.Marshal(vmSpecRegInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodPut) - vmSpecInfo := tbmcir.TbSpecInfo{} - if err != nil { - fmt.Println(err) - return &vmSpecInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&vmSpecInfo) - fmt.Println(vmSpecInfo) - - return &vmSpecInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 해당 namespace의 모든 VMSpec 삭제 : TODO : 로그인 유저의 동일 namespace일 때만 삭제가능하도록 -func DelAllVMSpec(nameSpaceID string) (fwmodels.WebStatus, fwmodels.WebStatus) { - fmt.Println("DelAllVMSpec ************ : ") - var originalUrl = "/ns/{nsId}/resources/spec" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/spec" - - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - webStatus := fwmodels.WebStatus{} - if err != nil { - fmt.Println(err) - return webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return webStatus, fwmodels.WebStatus{StatusCode: respStatus} - - // return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -// VMSpec 삭제 -func DelVMSpec(nameSpaceID string, vmSpecID string) (fwmodels.WebStatus, fwmodels.WebStatus) { - webStatus := fwmodels.WebStatus{} - // if ValidateString(VMSpecID) != nil { - if len(vmSpecID) == 0 { - log.Println("specID 가 없으면 해당 namespace의 모든 image가 삭제되므로 처리할 수 없습니다.") - return webStatus, fwmodels.WebStatus{StatusCode: 4040, Message: "specID 가 없으면 해당 namespace의 모든 image가 삭제되므로 처리할 수 없습니다."} - } - - var originalUrl = "/ns/{nsId}/resources/spec/{specId}" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{specId}"] = vmSpecID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/spec/" + vmSpecID - - pbytes, _ := json.Marshal(vmSpecID) - resp, err := util.CommonHttp(url, pbytes, http.MethodDelete) - - if err != nil { - fmt.Println(err) - return webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return webStatus, fwmodels.WebStatus{StatusCode: respStatus} - // return respBody, fwmodels.WebStatus{StatusCode: respStatus} -} - -func LookupVmSpecInfoList(connectionName *tbcommon.TbConnectionName) (tbmcir.SpiderSpecInfos, fwmodels.WebStatus) { - fmt.Println("LookupVmSpecInfoList ************ : ") - var originalUrl = "/lookupSpecs" - urlParam := util.MappingUrlParameter(originalUrl, nil) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/lookupSpec" - - pbytes, _ := json.Marshal(connectionName) - // fmt.Println(string(pbytes)) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - // resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - // return respBody, respStatus - // log.Println(respBody) - vmSpecList := map[string]tbmcir.SpiderSpecInfos{} - - json.NewDecoder(respBody).Decode(&vmSpecList) - // fmt.Println(vmSpecList["vmspec"]) - - return vmSpecList["vmspec"], fwmodels.WebStatus{StatusCode: respStatus} - -} - -// deprecated 호출경로 변경 -// func LookupVmSpecInfoData(vmSpecName string) (*tbmcir.RestGetAllSpecResponse, fwmodels.WebStatus) { -// var originalUrl = "/lookupSpec/{specName}" -// var paramMapper = make(map[string]string) -// paramMapper["{specName}"] = vmSpecName -// urlParam := util.MappingUrlParameter(originalUrl, paramMapper) -// url := util.TUMBLEBUG + urlParam -// // url := util.TUMBLEBUG + "/lookupSpec/" + vmSpecName - -// resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) -// vmSpecInfo := tbmcir.RestGetAllSpecResponse{} -// if err != nil { -// fmt.Println(err) -// return &vmSpecInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} -// } - -// respBody := resp.Body -// respStatus := resp.StatusCode - -// json.NewDecoder(respBody).Decode(&vmSpecInfo) -// fmt.Println(vmSpecInfo) - -// return &vmSpecInfo, fwmodels.WebStatus{StatusCode: respStatus} -// } - -func LookupVmSpecInfoData(restLookupSpecRequest *tbmcir.RestLookupSpecRequest) (*tbmcir.SpiderSpecInfo, fwmodels.WebStatus) { - var originalUrl = "/lookupSpec" - - urlParam := util.MappingUrlParameter(originalUrl, nil) - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(restLookupSpecRequest) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - vmSpecInfo := tbmcir.SpiderSpecInfo{} - if err != nil { - fmt.Println(err) - return &vmSpecInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&vmSpecInfo) - fmt.Println(vmSpecInfo) - - return &vmSpecInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Fetch는 결과만 return -func FetchVmSpecInfoList(nameSpaceID string) (*tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - fmt.Println("FetchVmSpecInfoList ************ : ", nameSpaceID) - var originalUrl = "/ns/{nsId}/resources/fetchSpecs" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/fetchSpecs" - - resultInfo := tbcommon.TbSimpleMsg{} - // resp, err := util.CommonHttp(url, nil, http.MethodGet) - resp, err := util.CommonHttpWithoutParam(url, http.MethodPost) - if err != nil { - fmt.Println(err) - return &resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - // fetchSpecList := map[string][]tbmcir.RestGetAllSpecResponse{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println("FetchVmSpecList called ") - - return &resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// 오래걸리므로 비동기로 처리 -func FetchVmSpecInfoListByAsync(nameSpaceID string, c buffalo.Context) { - log.Println("FetchVmSpecInfoListByAsync ************ : ", nameSpaceID) - var originalUrl = "/ns/{nsId}/resources/fetchSpecs" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/fetchSpecs" - - // resultInfo := tbcommon.TbSimpleMsg{} - - taskKey := nameSpaceID + "||" + "VMSpec" + "||" + "Fetch" - - // resp, err := util.CommonHttp(url, nil, http.MethodGet) - // resp, err := util.CommonHttpWithoutParam(url, http.MethodPost) - _, err := util.CommonHttpWithoutParam(url, http.MethodPost) - if err != nil { - fmt.Println(err) - StoreWebsocketMessage(util.TASK_TYPE_VMSPEC, taskKey, util.VMSPEC_LIFECYCLE_CREATE, util.TASK_STATUS_FAIL, c) // session에 작업내용 저장 - } - // defer body.Close() - // respBody := resp.Body - // respStatus := resp.StatusCode - // // fetchSpecList := map[string][]tbmcir.RestGetAllSpecResponse{} - - // json.NewDecoder(respBody).Decode(&resultInfo) - - log.Println("FetchVmSpecList called ") - StoreWebsocketMessage(util.TASK_TYPE_VMSPEC, taskKey, util.VMSPEC_LIFECYCLE_CREATE, util.TASK_STATUS_COMPLETE, c) // session에 작업내용 저장 -} - -// resourcesGroup.PUT("/vmspec/put/:specID", controller.VmSpecPutProc) // RegProc _ SshKey 같이 앞으로 넘길까 -// resourcesGroup.POST("/vmspec/filterspecs", controller.FilterVmSpecList) - -// spec들을 filterling -func FilterVmSpecInfoList(nameSpaceID string, vmSpecRegInfo *tbmcir.TbSpecInfo) ([]tbmcir.TbSpecInfo, fwmodels.WebStatus) { - fmt.Println("FilterVmSpecInfoList ************ : ", nameSpaceID) - var originalUrl = "/ns/{nsId}/resources/filterSpecs" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/filterSpecs" - // /ns/{nsId}/resources/filterSpecs - // resp, err := util.CommonHttp(url, nil, http.MethodGet) - // resp, err := util.CommonHttpWithoutParam(url, http.MethodPost) - - pbytes, _ := json.Marshal(vmSpecRegInfo) - resp, err := util.CommonHttp(url, pbytes, http.MethodGet) - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - filterSpecList := tbmcir.RestFilterSpecsResponse{} - - json.NewDecoder(respBody).Decode(&filterSpecList) - log.Println("FilterVmSpecInfoList called ") - - return filterSpecList.SpaceInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -// resourcesGroup.POST("/vmspec/filterspecsbyrange", controller.FilterVmSpecListByRange) -// namespace의 spec 조회 -// 기본값은 system-purpose-common-ns 이며 spec load를 해야 사용가능 -// 특정 namespace를 주면 해당 ns에 있는 spec을 filter -func FilterVmSpecInfoListByRange(nameSpaceID string, vmSpecRangeMinMax *tbmcir.FilterSpecsByRangeRequest) ([]tbmcir.TbSpecInfo, fwmodels.WebStatus) { - webStatus := fwmodels.WebStatus{} - resultInfo := tbmcir.RestFilterSpecsResponse{} - - fmt.Println("FilterVmSpecInfoListByRange ************ : ", nameSpaceID) - var originalUrl = "/ns/{nsId}/resources/filterSpecsByRange" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/resources/filterSpecsByRange" - // /ns/{nsId}/resources/filterSpecsByRange - - pbytes, _ := json.Marshal(vmSpecRangeMinMax) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - if err != nil { - fmt.Println(err) - return resultInfo.SpaceInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // defer body.Close() - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + failResultInfo.Message) - return resultInfo.SpaceInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - webStatus.StatusCode = respStatus - - return resultInfo.SpaceInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func DelDefaultResources(nameSpaceID string) (*tbcommon.TbIdList, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/defaultResources" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - url := util.TUMBLEBUG + urlParam - - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - idList := tbcommon.TbIdList{} - - if err != nil { - fmt.Println(err) - return &idList, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - // return body, err - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("ResultMessage : " + failResultInfo.Message) - return &idList, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&idList) - fmt.Println(idList) - - return &idList, fwmodels.WebStatus{StatusCode: respStatus} -} - -func LoadDefaultResources(nameSpaceID string, optionParam string, connectionName string) (fwmodels.WebStatus, fwmodels.WebStatus) { - var originalUrl = "/ns/{nsId}/loadDefaultResource" - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - urlParam += "?option=" + optionParam - if connectionName != "" { - urlParam += "&connectionName=" + connectionName - } - url := util.TUMBLEBUG + urlParam - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - webStatus := fwmodels.WebStatus{} - if err != nil { - fmt.Println(err) - return webStatus, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - resultInfo := fwmodels.ResultInfo{} - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return fwmodels.WebStatus{}, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - webStatus.StatusCode = respStatus - webStatus.Message = resultInfo.Message - return webStatus, fwmodels.WebStatus{StatusCode: respStatus} -} - -// Recommend MCIS plan (filter and priority) -// 실제로는 추천 vmspec 목록 -func GetRecommendVmSpecList(mcisDeploymentPlan *tbmcis.DeploymentPlan) ([]tbmcir.TbSpecInfo, fwmodels.WebStatus) { - var originalUrl = "/mcisRecommendVm" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(mcisDeploymentPlan) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - returnVmSpecs := []tbmcir.TbSpecInfo{} - returnStatus := fwmodels.WebStatus{} - - if err != nil { - fmt.Println(err) - return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - returnStatus.StatusCode = respStatus - - if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - log.Println("RegMcisDynamic ", failResultInfo) - return returnVmSpecs, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&returnVmSpecs) - fmt.Println(returnVmSpecs) - - return returnVmSpecs, returnStatus -} diff --git a/mc_web_console_api/handler/StoreHandler.go b/mc_web_console_api/handler/StoreHandler.go deleted file mode 100644 index aaea4741..00000000 --- a/mc_web_console_api/handler/StoreHandler.go +++ /dev/null @@ -1,189 +0,0 @@ -package handler - -import ( - // "encoding/base64" - "fmt" - "log" - - // "log" - // "io" - // "net/http" - - "github.com/gobuffalo/buffalo" - - "mc_web_console_api/fwmodels" - "mc_web_console_api/fwmodels/spider" - - // "mc_web_console_api/fwmodels/tumblebug" - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - // tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - // tbmcis "mc_web_console_api/fwmodels/tumblebug/mcis" - - util "mc_web_console_api/util" -) - -// 로그인할 때, NameSpace 저장(Create, Delete, Update) 외에는 이 funtion 사용 -// 없으면 tb 조회 -func GetStoredNameSpaceList(c buffalo.Context) ([]tbcommon.TbNsInfo, fwmodels.WebStatus) { - fmt.Println("====== GET STORED NAME SPACE ========") - nameSpaceList := []tbcommon.TbNsInfo{} - nameSpaceErr := fwmodels.WebStatus{} - - if storedNameSpaceList := c.Session().Get(util.STORE_NAMESPACELIST); storedNameSpaceList != nil { // 존재하지 않으면 TB 조회 - log.Println(storedNameSpaceList) - nameSpaceList = storedNameSpaceList.([]tbcommon.TbNsInfo) - nameSpaceErr.StatusCode = 200 - } else { - nameSpaceList, nameSpaceErr = GetNameSpaceList() - setError := SetStoreNameSpaceList(c, nameSpaceList) - if setError != nil { - log.Println("Set Namespace failed") - nameSpaceErr.StatusCode = 4000 - } - } - return nameSpaceList, nameSpaceErr -} - -func SetStoreNameSpaceList(c buffalo.Context, nameSpaceList []tbcommon.TbNsInfo) error { - fmt.Println("====== SET NAME SPACE ========") - c.Session().Set(util.STORE_NAMESPACELIST, nameSpaceList) - err := c.Session().Save() - return err -} - -// GetCloudOSList -func GetStoredCloudOSList(c buffalo.Context) ([]string, fwmodels.WebStatus) { - fmt.Println("====== GET STORED CloudOS ========") - cloudOSList := []string{} - cloudOsErr := fwmodels.WebStatus{} - - if storedCloudOSList := c.Session().Get(util.STORE_CLOUDOSLIST); storedCloudOSList != nil { // 존재하지 않으면 TB 조회 - log.Println(storedCloudOSList) - cloudOSList = storedCloudOSList.([]string) - cloudOsErr.StatusCode = 200 - } else { - cloudOSList, cloudOsErr = GetCloudOSList() - setError := SetStoreCloudOSList(c, cloudOSList) - if setError != nil { - log.Println("Set cloudOS failed") - } - - } - return cloudOSList, cloudOsErr -} - -func SetStoreCloudOSList(c buffalo.Context, cloudOSList []string) error { - fmt.Println("====== SET cloudOS ========") - c.Session().Set(util.STORE_CLOUDOSLIST, cloudOSList) - err := c.Session().Save() - return err -} - -// GetRegionList -func GetStoredRegionList(c buffalo.Context) ([]spider.RegionInfo, fwmodels.WebStatus) { - fmt.Println("====== GET STORED Region ========") - regionList := []spider.RegionInfo{} - regionErr := fwmodels.WebStatus{} - - if storedRegionList := c.Session().Get(util.STORE_REGIONLIST); storedRegionList != nil { // 존재하지 않으면 TB 조회 - log.Println(storedRegionList) - regionList = storedRegionList.([]spider.RegionInfo) - regionErr.StatusCode = 200 - } else { - regionList, regionErr = GetRegionList() - setError := SetStoreRegionList(c, regionList) - if setError != nil { - log.Println("Set Region failed") - } - } - return regionList, regionErr -} - -func SetStoreRegionList(c buffalo.Context, regionList []spider.RegionInfo) error { - fmt.Println("====== SET Region ========") - c.Session().Set(util.STORE_REGIONLIST, regionList) - err := c.Session().Save() - return err -} - -// GetCredentialList -func GetStoredCredentialList(c buffalo.Context) ([]spider.CredentialInfo, fwmodels.WebStatus) { - fmt.Println("====== GET STORED Region ========") - credentialList := []spider.CredentialInfo{} - credentialErr := fwmodels.WebStatus{} - - if storedCredentialList := c.Session().Get(util.STORE_CREDENTIALLIST); storedCredentialList != nil { // 존재하지 않으면 TB 조회 - log.Println(storedCredentialList) - credentialList = storedCredentialList.([]spider.CredentialInfo) - credentialErr.StatusCode = 200 - } else { - credentialList, credentialErr = GetCredentialList() - setError := SetStoreCredentialList(c, credentialList) - if setError != nil { - log.Println("Set Credential failed") - } - } - return credentialList, credentialErr -} - -func SetStoreCredentialList(c buffalo.Context, credentialList []spider.CredentialInfo) error { - fmt.Println("====== SET Credential ========") - c.Session().Set(util.STORE_CREDENTIALLIST, credentialList) - err := c.Session().Save() - return err -} - -// GetDriverList -func GetStoredDriverList(c buffalo.Context) ([]spider.DriverInfo, fwmodels.WebStatus) { - fmt.Println("====== GET STORED Driver ========") - driverList := []spider.DriverInfo{} - driverErr := fwmodels.WebStatus{} - - if storedDriverList := c.Session().Get(util.STORE_DRIVERLIST); storedDriverList != nil { // 존재하지 않으면 TB 조회 - log.Println(storedDriverList) - driverList = storedDriverList.([]spider.DriverInfo) - driverErr.StatusCode = 200 - } else { - driverList, driverErr = GetDriverList() - setError := SetStoreDriverList(c, driverList) - if setError != nil { - log.Println("Set Driver failed") - } - - } - return driverList, driverErr -} - -func SetStoreDriverList(c buffalo.Context, driverList []spider.DriverInfo) error { - fmt.Println("====== SET Driver ========") - c.Session().Set(util.STORE_DRIVERLIST, driverList) - err := c.Session().Save() - return err -} - -// GetCloudConnectionConfigList -func GetStoredCloudConnectionConfigList(c buffalo.Context) ([]spider.CloudConnectionConfigInfo, fwmodels.WebStatus) { - fmt.Println("====== GET STORED CloudConnectionConfigList ========") - connectionConfigList := []spider.CloudConnectionConfigInfo{} - connectionConfigErr := fwmodels.WebStatus{} - - if storedConnectionConfigList := c.Session().Get(util.STORE_CLOUDCONNECTIONCONFIGLIST); storedConnectionConfigList != nil { // 존재하지 않으면 TB 조회 - log.Println(storedConnectionConfigList) - connectionConfigList = storedConnectionConfigList.([]spider.CloudConnectionConfigInfo) - connectionConfigErr.StatusCode = 200 - } else { - connectionConfigList, connectionConfigErr = GetCloudConnectionConfigList() - setError := SetStoreCloudConnectionConfigList(c, connectionConfigList) - if setError != nil { - log.Println("Set ConnectionConfigList failed") - } - } - return connectionConfigList, connectionConfigErr -} - -func SetStoreCloudConnectionConfigList(c buffalo.Context, connectionConfigList []spider.CloudConnectionConfigInfo) error { - fmt.Println("====== SET CloudConnectionConfigList ========") - c.Session().Set(util.STORE_CLOUDCONNECTIONCONFIGLIST, connectionConfigList) - err := c.Session().Save() - return err -} diff --git a/mc_web_console_api/handler/SystemEnvironmentHandler.go b/mc_web_console_api/handler/SystemEnvironmentHandler.go deleted file mode 100644 index d573d650..00000000 --- a/mc_web_console_api/handler/SystemEnvironmentHandler.go +++ /dev/null @@ -1,174 +0,0 @@ -package handler - -import ( - "encoding/json" - "fmt" - "log" - - // "math" - "net/http" - // "strconv" - // "sync" - "mc_web_console_api/fwmodels" - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - util "mc_web_console_api/util" -) - -func DelAllTbConfig() (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - fmt.Println("Delete all configs start") - var originalUrl = "/config" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns" - - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - //body := HttpGetHandler(url) - - resultInfo := tbcommon.TbSimpleMsg{} - - if err != nil { - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetAllTbConfig() (tbcommon.TbRestGetAllConfigResponse, fwmodels.WebStatus) { - fmt.Println("Get all configs list start") - var originalUrl = "/config" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns" - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - //body := HttpGetHandler(url) - - resultAllConfigInfo := tbcommon.TbRestGetAllConfigResponse{} - - if err != nil { - return resultAllConfigInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - // log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return resultAllConfigInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&resultAllConfigInfo) - log.Println(resultAllConfigInfo) - - return resultAllConfigInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func RegOrUpdateConfig(configReg tbcommon.TbConfigReq) (tbcommon.TbConfigInfo, fwmodels.WebStatus) { - fmt.Println("Create or Update config ") - //https://www.javaer101.com/ko/article/5704925.html 참조 : 값이 있는 것만 넘기기 - var originalUrl = "​/config" - urlParam := util.MappingUrlParameter(originalUrl, nil) - url := util.TUMBLEBUG + urlParam - - pbytes, _ := json.Marshal(configReg) - resp, err := util.CommonHttp(url, pbytes, http.MethodPost) - - resultConfigInfo := tbcommon.TbConfigInfo{} - - if err != nil { - return resultConfigInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return resultConfigInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&resultConfigInfo) - fmt.Println(resultConfigInfo) - - return resultConfigInfo, fwmodels.WebStatus{StatusCode: respStatus} - -} - -func DelTbConfig(configID string) (tbcommon.TbConfigInfo, fwmodels.WebStatus) { - var originalUrl = "/config/{configId}" - - var paramMapper = make(map[string]string) - paramMapper["{configId}"] = configID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - resp, err := util.CommonHttpWithoutParam(url, http.MethodDelete) - - resultConfigInfo := tbcommon.TbConfigInfo{} - - if err != nil { - return resultConfigInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return resultConfigInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&resultConfigInfo) - fmt.Println(resultConfigInfo) - - return resultConfigInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetTbConfig(configID string) (tbcommon.TbConfigInfo, fwmodels.WebStatus) { - var originalUrl = "/config/{configId}" - - var paramMapper = make(map[string]string) - paramMapper["{configId}"] = configID - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - resultConfigInfo := tbcommon.TbConfigInfo{} - - if err != nil { - return resultConfigInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - if respStatus != 200 && respStatus != 201 { - failResultInfo := tbcommon.TbSimpleMsg{} - json.NewDecoder(respBody).Decode(&failResultInfo) - return resultConfigInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} - } - - json.NewDecoder(respBody).Decode(&resultConfigInfo) - fmt.Println(resultConfigInfo) - - return resultConfigInfo, fwmodels.WebStatus{StatusCode: respStatus} -} diff --git a/mc_web_console_api/handler/SystemManagementHandler.go b/mc_web_console_api/handler/SystemManagementHandler.go deleted file mode 100644 index e9d20d4a..00000000 --- a/mc_web_console_api/handler/SystemManagementHandler.go +++ /dev/null @@ -1,267 +0,0 @@ -package handler - -import ( - "encoding/json" - "fmt" - "log" - - // "math" - "net/http" - // "strconv" - // "sync" - - //"github.com/davecgh/go-spew/spew" - - // "mc_web_console_api/fwmodels/spider" - // "mc_web_console_api/fwmodels/tumblebug" - "mc_web_console_api/fwmodels" - tbcommon "mc_web_console_api/fwmodels/tumblebug/common" - - // tbmcir "mc_web_console_api/fwmodels/tumblebug/mcir" - // tbmcis "mc_web_console_api/fwmodels/tumblebug/mcis" - - util "mc_web_console_api/util" - // "github.com/labstack/echo" -) - -func GetCheckResourceExistence(nameSpaceID string, resourceType string, resourceId string) (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - var originalUrl = "/{nsId}/checkResource/{resourceType}/{resourceId}" - - var paramMapper = make(map[string]string) - paramMapper["{nsId}"] = nameSpaceID - paramMapper["{resourceType}"] = resourceType - paramMapper["{resourceId}"] = resourceId - urlParam := util.MappingUrlParameter(originalUrl, paramMapper) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns/" + nameSpaceID + "/mcis/" + mcisID + "/vm/" + vmID - - // resp, err := util.CommonHttp(url, nil, http.MethodGet) - resp, err := util.CommonHttpWithoutParam(url, http.MethodGet) - - resultInfo := tbcommon.TbSimpleMsg{} - - if err != nil { - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetHealth() (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - fmt.Println("Check Tumblebug alive start") - var originalUrl = "/health" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns" - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - //body := HttpGetHandler(url) - - resultInfo := tbcommon.TbSimpleMsg{} - - if err != nil { - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func DelObject(optionParam string) (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - fmt.Println("Delete object start") - var originalUrl = "/object" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.TUMBLEBUG + urlParam + "?option=" + optionParam - // url := util.TUMBLEBUG + "/ns" - - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - //body := HttpGetHandler(url) - - resultInfo := tbcommon.TbSimpleMsg{} - - if err != nil { - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetObject(optionParam string) (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - fmt.Println("Get object start") - var originalUrl = "/object" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - //"?key=" + key - optionParamVal := "" - // install, init, cpus, cpum, memR, memW, fioR, fioW, dbR, dbW, rtt, mrtt, clean - if optionParam != "" { - optionParamVal = "?key=" + optionParam - } - - url := util.TUMBLEBUG + urlParam + optionParamVal - // url := util.TUMBLEBUG + "/ns" - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - //body := HttpGetHandler(url) - - resultInfo := tbcommon.TbSimpleMsg{} - - if err != nil { - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func DelObjects(optionParam string) (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - fmt.Println("Delete objects start") - var originalUrl = "/objects" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - //"?key=" + key - optionParamVal := "" - // install, init, cpus, cpum, memR, memW, fioR, fioW, dbR, dbW, rtt, mrtt, clean - if optionParam != "" { - optionParamVal = "?key=" + optionParam - } - - url := util.TUMBLEBUG + urlParam + optionParamVal - // url := util.TUMBLEBUG + "/ns" - - resp, err := util.CommonHttp(url, nil, http.MethodDelete) - //body := HttpGetHandler(url) - - resultInfo := tbcommon.TbSimpleMsg{} - - if err != nil { - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetObjectList(optionParam string) (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - fmt.Println("Get object list start") - var originalUrl = "/objects" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - //"?key=" + key - optionParamVal := "" - // install, init, cpus, cpum, memR, memW, fioR, fioW, dbR, dbW, rtt, mrtt, clean - if optionParam != "" { - optionParamVal = "?key=" + optionParam - } - - url := util.TUMBLEBUG + urlParam + optionParamVal - // url := util.TUMBLEBUG + "/ns" - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - //body := HttpGetHandler(url) - - resultInfo := tbcommon.TbSimpleMsg{} - - if err != nil { - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} - -func GetAPIDocument(optionParam string) (tbcommon.TbSimpleMsg, fwmodels.WebStatus) { - fmt.Println("Get API document start") - var originalUrl = "/swaggerActive" - urlParam := util.MappingUrlParameter(originalUrl, nil) - - url := util.TUMBLEBUG + urlParam - // url := util.TUMBLEBUG + "/ns" - - resp, err := util.CommonHttp(url, nil, http.MethodGet) - //body := HttpGetHandler(url) - - resultInfo := tbcommon.TbSimpleMsg{} - - if err != nil { - return resultInfo, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} - } - - respBody := resp.Body - respStatus := resp.StatusCode - - json.NewDecoder(respBody).Decode(&resultInfo) - log.Println(resultInfo) - log.Println("ResultMessage : " + resultInfo.Message) - - if respStatus != 200 && respStatus != 201 { - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus, Message: resultInfo.Message} - } - - return resultInfo, fwmodels.WebStatus{StatusCode: respStatus} -} diff --git a/mc_web_console_api/handler/WebSocketHandler.go b/mc_web_console_api/handler/WebSocketHandler.go deleted file mode 100644 index fae52907..00000000 --- a/mc_web_console_api/handler/WebSocketHandler.go +++ /dev/null @@ -1,194 +0,0 @@ -package handler - -import ( - //"mc_web_console_api/fwmodels" - //tbmcis "mc_web_console_api/fwmodels/tumblebug/mcis" - "encoding/gob" - "log" - "time" - - "github.com/gobuffalo/buffalo" - - modelsocket "mc_web_console_api/fwmodels/websocket" -) - -func init() { - gob.Register(map[int64]modelsocket.WebSocketMessage{}) -} - -// WebSocket에 전달할 Message Set -func SetWebsocketMessage(taskType string, taskKey string, lifeCycle string, status string, c buffalo.Context) { - socketDataMap := map[int64]modelsocket.WebSocketMessage{} - if socketDataStore := c.Session().Get("socketdata"); socketDataStore != nil { // 존재하지 않으면 TB 조회 - socketDataMap = socketDataStore.(map[int64]modelsocket.WebSocketMessage) - - } else { - log.Println("SetWebsocketMessageBySend is not Ok ") - } - - websocketMessage := modelsocket.WebSocketMessage{} - - websocketMessage.TaskType = taskType - websocketMessage.TaskKey = taskKey - websocketMessage.LifeCycle = lifeCycle - websocketMessage.Status = status - websocketMessage.ProcessTime = time.Now() - - nanoTime := time.Now().UnixNano() - socketDataMap[nanoTime] = websocketMessage - c.Session().Set("socketdata", socketDataMap) - log.Println("SetWebsocketMessage. setsocketdata" + taskKey + " : " + lifeCycle + " " + status) - log.Println("SetWebsocketMessage. socketDataMap", socketDataMap) -} - -// TaskKey에 해당하는 값 조회 : 요청, 완료 값이 return -func GetWebsocketMessageByTaskKey(taskType string, taskKey string, c buffalo.Context) map[int64]modelsocket.WebSocketMessage { - returnSocketDataMap := map[int64]modelsocket.WebSocketMessage{} - // returnWebsocketMessage := modelsocket.WebSocketMessage{} - - if socketDataStore := c.Session().Get("socketdata"); socketDataStore != nil { // 존재하지 않으면 TB 조회 - socketDataMap := socketDataStore.(map[int64]modelsocket.WebSocketMessage) - for key, val := range socketDataMap { - log.Println("show socketData with key : getsocketdata ", key, val) - if val.TaskKey == taskKey { - returnSocketDataMap[key] = val - log.Println("show socketData with key by send : getsocketdata ", key, val) - } - } - // } - } else { - log.Println("socketDataStore is not Ok1 ") - } - return returnSocketDataMap -} - -// 전송 상태에 따른 값 목록 조회. sendMessage==false 이면 전송 전 data목록만 :: 시간을 param으로 하므로 필요 없을 것. deprecated. -// func GetWebsocketMessageBySend(send bool, c buffalo.Context) map[int64]modelsocket.WebSocketMessage { -func GetWebsocketMessageBySend(send bool, c buffalo.Context) []modelsocket.WebSocketMessage { - socketResultList := []modelsocket.WebSocketMessage{} - if socketDataStore := c.Session().Get("socketdata"); socketDataStore != nil { // 존재하지 않으면 TB 조회 - socketDataMap := socketDataStore.(map[int64]modelsocket.WebSocketMessage) - for key, val := range socketDataMap { - log.Println("show socketData with key : getsocketdata ", key, val) - socketMessage := socketDataMap[key] - socketResultList = append(socketResultList, socketMessage) - } - } else { - log.Println("socketDataStore is not Ok2 ") - } - - return socketResultList -} - -// 특정 시점 이후의 data만 추출 : -// func GetWebsocketMessageByProcessTime(beginTime time.Time, c buffalo.Context) map[int64]modelsocket.WebSocketMessage { -func GetWebsocketMessageByProcessTime(beginTime int64, c buffalo.Context) []modelsocket.WebSocketMessage { - socketResultList := []modelsocket.WebSocketMessage{} - - if socketDataStore := c.Session().Get("socketdata"); socketDataStore != nil { - log.Println("GetWebsocketMessageByProcessTime socketdata is not nil") - log.Println("socketDataStore ", socketDataStore) - socketDataMap := socketDataStore.(map[int64]modelsocket.WebSocketMessage) - log.Println("socketDataMap ", socketDataMap) - for key, val := range socketDataMap { - log.Println("show socketData with key : getsocketdata ", key, val) - websocketMessage := socketDataMap[key] - processTime := websocketMessage.ProcessTime.UnixNano() - log.Println(" key ", key) - log.Println(" beginTime ", beginTime) - log.Println(" processTime", processTime) - log.Println(" key > beginTime ", processTime > beginTime) - if processTime > beginTime { - //websocketMessageMap[key] = websocketMessage - log.Println("show socketData with key by ProcessTime : getsocketdata ", key, val) - socketResultList = append(socketResultList, websocketMessage) - } - } - } else { - log.Println("socketDataStore is not Ok3 ") - socketDataMap := map[int64]modelsocket.WebSocketMessage{} - c.Session().Set("socketdata", socketDataMap) - } - - return socketResultList -} - -// taskType : mcis/vm/mcks ... -// lifecycle : create, suspend, resume. .... -// taskKey : -// status : requested, processing, failed, completed -// eccossion에 socketdata 에 추가. key는 timestamp인데 unixNanoTime(int64) 사용 -func StoreWebsocketMessage(taskType string, taskKey string, lifeCycle string, requestStatus string, c buffalo.Context) { - websocketMessage := modelsocket.WebSocketMessage{} - - websocketMessage.TaskType = taskType - websocketMessage.TaskKey = taskKey - websocketMessage.LifeCycle = lifeCycle - websocketMessage.Status = requestStatus - websocketMessage.ProcessTime = time.Now() - - log.Println("StoreWebsocketMessage... begin " + taskKey + " : " + lifeCycle + " " + requestStatus) - socketDataMap := map[int64]modelsocket.WebSocketMessage{} - session := c.Session() - - if socketDataStore := session.Get("socketdata"); socketDataStore == nil { - log.Println("StoreWebsocketMessage... socketDataStore is nil") - } else { - log.Println("StoreWebsocketMessage... socketDataStore is not nil") - socketDataMap = socketDataStore.(map[int64]modelsocket.WebSocketMessage) - log.Println("StoreWebsocketMessage... socketDataStore is not nil 222") - } - nanoTime := time.Now().UnixNano() - socketDataMap[nanoTime] = websocketMessage - session.Set("socketdata", socketDataMap) - err := session.Save() - if err != nil { - log.Println("session save err", err) - } - - log.Println("StoreWebsocketMessage... setsocketdata" + taskKey + " : " + lifeCycle + " " + requestStatus) - log.Println("StoreWebsocketMessage... socketDataMap", socketDataMap) -} - -func StoreWebsocketMessageDetail(taskType string, taskKey string, lifeCycle string, requestStatus string, desc string, c buffalo.Context) { - socketDataMap := map[int64]modelsocket.WebSocketMessage{} - if socketDataStore := c.Session().Get("socketdata"); socketDataStore == nil { - log.Println("StoreWebsocketMessageDetail... socketDataStore is nil") - socketDataMap = socketDataStore.(map[int64]modelsocket.WebSocketMessage) // 없으면 생성 - log.Println("StoreWebsocketMessageDetail... socketDataStore is nil 222") - } - - websocketMessage := modelsocket.WebSocketMessage{} - - websocketMessage.TaskType = taskType - websocketMessage.TaskKey = taskKey - websocketMessage.LifeCycle = lifeCycle - websocketMessage.Status = requestStatus + ", " + desc - websocketMessage.ProcessTime = time.Now() - - nanoTime := time.Now().UnixNano() - socketDataMap[nanoTime] = websocketMessage - c.Session().Set("socketdata", socketDataMap) - - log.Println("StoreWebsocketMessageDetail : setsocketdata" + taskKey + " : " + lifeCycle + " " + requestStatus) - log.Println("StoreWebsocketMessageDetail : socketDataMap", socketDataMap) -} - -// 일정 시간이 지난 data는 제거. : 0이면 기본값(24), 0보다 크면 음수로 바꾸어 계산. -func ClearWebsocketMessage(expireHour int, c buffalo.Context) { - - if expireHour == 0 { - expireHour = 24 - } else if expireHour > 0 { - expireHour = -1 * expireHour - } - t := time.Now() - d2 := t.Add(time.Hour * time.Duration(expireHour)) // expire 시간이 지난 것들은 삭제 - - renewSocketDataMap := GetWebsocketMessageByProcessTime(d2.UnixNano(), c) - //renewSocketDataMap := GetWebsocketMessageByProcessTime(d2, c) - - c.Session().Set("socketdata", renewSocketDataMap) - - log.Println("renew setsocketdata before :", d2) -} diff --git a/mc_web_console_api/handler/http-util.go b/mc_web_console_api/handler/http-util.go new file mode 100644 index 00000000..2b8e226c --- /dev/null +++ b/mc_web_console_api/handler/http-util.go @@ -0,0 +1,183 @@ +package handler + +import ( + "bytes" + "encoding/json" + "io" + "log" + "net/http" + "net/http/httputil" + "net/url" + "strings" +) + +type CommonRequest struct { + PathParams map[string]string `json:"pathParams"` + QueryParams map[string]string `json:"queryParams"` + Request interface{} `json:"request"` +} + +// 모든 응답을 CommonResponse로 한다. +type CommonResponse struct { + ResponseData interface{} `json:"responseData"` + Status WebStatus `json:"status"` +} + +type WebStatus struct { + StatusCode int `json:"code"` + Message string `json:"message"` +} + +func CommonResponseStatusOK(responseData interface{}) *CommonResponse { + webStatus := WebStatus{ + StatusCode: http.StatusOK, + Message: http.StatusText(http.StatusOK), + } + return &CommonResponse{ + ResponseData: responseData, + Status: webStatus, + } +} + +func CommonResponseStatusNotFound(responseData interface{}) *CommonResponse { + webStatus := WebStatus{ + StatusCode: http.StatusNotFound, + Message: http.StatusText(http.StatusNotFound), + } + return &CommonResponse{ + ResponseData: responseData, + Status: webStatus, + } +} + +func CommonResponseStatusStatusUnauthorized(responseData interface{}) *CommonResponse { + webStatus := WebStatus{ + StatusCode: http.StatusUnauthorized, + Message: http.StatusText(http.StatusUnauthorized), + } + return &CommonResponse{ + ResponseData: responseData, + Status: webStatus, + } +} + +func CommonResponseStatusBadRequest(responseData interface{}) *CommonResponse { + webStatus := WebStatus{ + StatusCode: http.StatusBadRequest, + Message: http.StatusText(http.StatusBadRequest), + } + return &CommonResponse{ + ResponseData: responseData, + Status: webStatus, + } +} + +func CommonResponseStatusInternalServerError(responseData interface{}) *CommonResponse { + webStatus := WebStatus{ + StatusCode: http.StatusInternalServerError, + Message: http.StatusText(http.StatusInternalServerError), + } + return &CommonResponse{ + ResponseData: responseData, + Status: webStatus, + } +} + +func CommonCaller(callMethod string, targetFwUrl string, endPoint string, commonRequest *CommonRequest, auth string) (*CommonResponse, error) { + pathParamsUrl := mappingUrlPathParams(endPoint, commonRequest) + queryParamsUrl := mappingQueryParams(pathParamsUrl, commonRequest) + requestUrl := targetFwUrl + queryParamsUrl + commonResponse, err := CommonHttpToCommonResponse(requestUrl, commonRequest.Request, callMethod, auth) + return commonResponse, err +} + +func CommonCallerWithoutToken(callMethod string, targetFwUrl string, endPoint string, commonRequest *CommonRequest) (*CommonResponse, error) { + pathParamsUrl := mappingUrlPathParams(endPoint, commonRequest) + queryParamsUrl := mappingQueryParams(pathParamsUrl, commonRequest) + requestUrl := targetFwUrl + queryParamsUrl + commonResponse, err := CommonHttpToCommonResponse(requestUrl, commonRequest.Request, callMethod, "") + return commonResponse, err +} + +func mappingUrlPathParams(endPoint string, commonRequest *CommonRequest) string { + u := endPoint + for k, r := range commonRequest.PathParams { + u = strings.Replace(u, "{"+k+"}", r, -1) + } + return u +} + +func mappingQueryParams(targeturl string, commonRequest *CommonRequest) string { + u, err := url.Parse(targeturl) + if err != nil { + return "" + } + q := u.Query() + for k, v := range commonRequest.QueryParams { + q.Set(string(k), v) + } + u.RawQuery = q.Encode() + return u.String() +} + +func CommonHttpToCommonResponse(url string, s interface{}, httpMethod string, auth string) (*CommonResponse, error) { + log.Println("CommonHttp - METHOD:" + httpMethod + " => url:" + url) + log.Println("isauth:", auth) + + jsonData, err := json.Marshal(s) + if err != nil { + log.Println("commonPostERR : json.Marshal : ", err.Error()) + return nil, err + } + + req, err := http.NewRequest(httpMethod, url, bytes.NewBuffer(jsonData)) + if err != nil { + log.Println("Error CommonHttp creating request:", err) + return nil, err + } + req.Header.Set("Content-Type", "application/json") + if auth != "" { + req.Header.Add("Authorization", auth) + } + + requestDump, err := httputil.DumpRequest(req, true) + if err != nil { + log.Println("Error CommonHttp creating httputil.DumpRequest:", err) + } + log.Println("\n", string(requestDump)) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + log.Println("Error CommonHttp request:", err) + return CommonResponseStatusInternalServerError(err), err + } + defer resp.Body.Close() + + respBody, ioerr := io.ReadAll(resp.Body) + if ioerr != nil { + log.Println("Error CommonHttp reading response:", ioerr) + } + + commonResponse := &CommonResponse{} + commonResponse.Status.Message = resp.Status + commonResponse.Status.StatusCode = resp.StatusCode + if len(respBody) > 0 { + if isJSONResponse(respBody) { + jsonerr := json.Unmarshal(respBody, &commonResponse.ResponseData) + if jsonerr != nil { + log.Println("Error CommonHttp Unmarshal response:", jsonerr.Error()) + return commonResponse, jsonerr + } + } else { + commonResponse.ResponseData = strings.TrimSpace(string(respBody)) + return commonResponse, nil + } + } + return commonResponse, nil +} + +func isJSONResponse(body []byte) bool { + var js map[string]interface{} + return json.Unmarshal(body, &js) == nil +} diff --git a/mc_web_console_api/handler/mciammanager/const.go b/mc_web_console_api/handler/mciammanager/const.go new file mode 100644 index 00000000..6654f1de --- /dev/null +++ b/mc_web_console_api/handler/mciammanager/const.go @@ -0,0 +1,45 @@ +package mciammanager + +var ( + Alive = "/alive" + AliveAdmin = "/alive/admin" + AliveOperator = "/alive/operator" + AliveViewer = "/alive/viewer" + Getcerts = "/api/auth/certs" + Login = "/api/auth/login" + Loginrefresh = "/api/auth/login/refresh" + Logout = "/api/auth/logout" + Getuserinfo = "/api/auth/userinfo" + Getusevalidate = "/api/auth/validate" + Getprojectlist = "/api/prj" + Createproject = "/api/prj" + Deleteprojectbyid = "/api/prj/project/id/{projectId}" + Getprojectbyid = "/api/prj/project/id/{projectId}" + Updateprojectbyid = "/api/prj/project/id/{projectId}" + Searchprojectsbyname = "/api/prj/project/{projectName}" + Getrolelist = "/api/role" + Createrole = "/api/role" + Deleterolebyid = "/api/role/role/id/{roleId}" + Getrolebyid = "/api/role/role/id/{roleId}" + Updaterolebyid = "/api/role/role/id/{roleId}" + Searchrolesbyname = "/api/role/role/{roleName}" + Securitykey = "/api/sts/securitykey" + Syncprojectlistwithmcinfra = "/api/tool/mcinfra/sync" + Getworkspacelist = "/api/ws" + Createworkspace = "/api/ws" + Deleteworkspacebyid = "/api/ws/workspace/id/{workspaceId}" + Getworkspacebyid = "/api/ws/workspace/id/{workspaceId}" + Updateworkspacebyid = "/api/ws/workspace/id/{workspaceId}" + Searchworkspacesbyname = "/api/ws/workspace/{workspaceName}" + Getwpmappinglistorderbyworkspace = "/api/wsprj" + Createwpmapping = "/api/wsprj" + Updatewpmappings = "/api/wsprj" + Getwpmappinglistbyworkspaceid = "/api/wsprj/workspace/id/{workspaceId}" + Deleteworkspaceprojectmappingbyid = "/api/wsprj/workspace/id/{workspaceId}/project/id/{projectId}" + Getworkspaceuserrolemappinglistorderbyworkspace = "/api/wsuserrole" + Createworkspaceuserrolemappingbyname = "/api/wsuserrole" + Getworkspaceuserrolemappinglistbyuserid = "/api/wsuserrole/user/id/{userId}" + Getworkspaceuserrolemappinglistbyworkspaceid = "/api/wsuserrole/workspace/id/{workspaceId}" + Deleteworkspaceuserrolemapping = "/api/wsuserrole/workspace/id/{workspaceId}/user/id/{userId}" + Getworkspaceuserrolemappingbyid = "/api/wsuserrole/workspace/id/{workspaceId}/user/id/{userId}" +) diff --git a/mc_web_console_api/handler/mciammanager/mciamanager.go b/mc_web_console_api/handler/mciammanager/mciamanager.go new file mode 100644 index 00000000..e70f1f4f --- /dev/null +++ b/mc_web_console_api/handler/mciammanager/mciamanager.go @@ -0,0 +1,264 @@ +package mciammanager + +import ( + "log" + "mc_web_console_api/handler" + "net/http" + "os" + + "github.com/gobuffalo/buffalo" +) + +var MCIAMMANAGER = os.Getenv("MCIAMMANAGER") + +// alive +func McIamAlive(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCallerWithoutToken(http.MethodGet, MCIAMMANAGER, Alive, commonRequest) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +// auth +func McIamLogin(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCallerWithoutToken(http.MethodPost, MCIAMMANAGER, Login, commonRequest) + if err != nil { + log.Println("CommonCallerWithoutToken", err) + return commonResponse + } + return commonResponse +} + +func McIamLoginRefresh(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodPost, MCIAMMANAGER, Loginrefresh, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamLogout(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodPost, MCIAMMANAGER, Logout, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamGetUserInfo(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCIAMMANAGER, Getuserinfo, commonRequest, c.Request().Header.Get("Authorization")) + return commonResponse +} + +func McIamGetUserValidate(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCIAMMANAGER, Getusevalidate, commonRequest, c.Request().Header.Get("Authorization")) + return commonResponse +} + +// project +func McIamGetprojectlist(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodGet, MCIAMMANAGER, Getprojectlist, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamCreateproject(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodPost, MCIAMMANAGER, Createproject, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamDeleteproject(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodDelete, MCIAMMANAGER, Deleteprojectbyid, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamGetproject(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodGet, MCIAMMANAGER, Getprojectbyid, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamUpdateproject(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodPut, MCIAMMANAGER, Updateprojectbyid, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +// workspace +func McIamGetworkspacelist(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodGet, MCIAMMANAGER, Getworkspacelist, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamGetworkspace(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodGet, MCIAMMANAGER, Getworkspacebyid, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamCreateworkspace(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodPost, MCIAMMANAGER, Createworkspace, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamDeleteworkspace(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodDelete, MCIAMMANAGER, Deleteworkspacebyid, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamUpdateworkspace(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodPut, MCIAMMANAGER, Updateworkspacebyid, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +// role +func McIamGetrolelist(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodGet, MCIAMMANAGER, Getrolelist, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamGetrole(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodGet, MCIAMMANAGER, Getrolebyid, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamCreaterole(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodPost, MCIAMMANAGER, Createrole, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamDeleterole(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodDelete, MCIAMMANAGER, Deleterolebyid, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +// workspace - project Mapping +func McIamGetworkspaceprojectmapping(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodGet, MCIAMMANAGER, Getwpmappinglistorderbyworkspace, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamGetworkspaceprojectmappingbyworkspace(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodGet, MCIAMMANAGER, Getwpmappinglistbyworkspaceid, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamCreateworkspaceprojectmapping(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodPost, MCIAMMANAGER, Createwpmapping, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamUpdateworkspaceprojectmapping(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodPut, MCIAMMANAGER, Updatewpmappings, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamDeleteworkspaceprojectmapping(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodDelete, MCIAMMANAGER, Deleteworkspaceprojectmappingbyid, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +// workspace - user - role Mapping +func McIamGetworkspaceuserrolemapping(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodGet, MCIAMMANAGER, Getworkspaceuserrolemappinglistorderbyworkspace, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamGetworkspaceuserrolemappingbyworkspaceuser(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodGet, MCIAMMANAGER, Getworkspaceuserrolemappinglistbyuserid, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + log.Print(" err ", err) + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + log.Print(" commonResponse ", commonResponse) + return commonResponse +} + +func McIamGetworkspaceuserrolemappingbyworkspace(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodGet, MCIAMMANAGER, Getworkspaceuserrolemappinglistbyworkspaceid, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamCreateworkspaceuserrolemapping(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodPost, MCIAMMANAGER, Createworkspaceuserrolemappingbyname, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamDeleteworkspaceuserrolemapping(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodDelete, MCIAMMANAGER, Deleteworkspaceuserrolemapping, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} + +func McIamGetworkspaceuserrolemappingbyuser(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, err := handler.CommonCaller(http.MethodGet, MCIAMMANAGER, Getworkspaceuserrolemappingbyid, commonRequest, c.Request().Header.Get("Authorization")) + if err != nil { + return handler.CommonResponseStatusInternalServerError(err.Error()) + } + return commonResponse +} diff --git a/mc_web_console_api/handler/mciammanager/models.go b/mc_web_console_api/handler/mciammanager/models.go new file mode 100644 index 00000000..3e93b375 --- /dev/null +++ b/mc_web_console_api/handler/mciammanager/models.go @@ -0,0 +1 @@ +package mciammanager diff --git a/mc_web_console_api/handler/mciammanager/sess.go b/mc_web_console_api/handler/mciammanager/sess.go new file mode 100644 index 00000000..9ad45f82 --- /dev/null +++ b/mc_web_console_api/handler/mciammanager/sess.go @@ -0,0 +1,127 @@ +package mciammanager + +import ( + "context" + "fmt" + "log" + "net/http" + "strings" + + "github.com/gobuffalo/buffalo" + "github.com/gobuffalo/buffalo/render" + "github.com/golang-jwt/jwt" + "github.com/lestrrat-go/jwx/jwk" +) + +var ( + jwkSet jwk.Set +) + +type CustomClaims struct { + *jwt.StandardClaims + Exp int `json:"exp"` + // Iat int `json:"iat"` + // Jti string `json:"jti"` + // Iss string `json:"iss"` + // Aud string `json:"aud"` + Sub string `json:"sub"` + // Typ string `json:"typ"` + // Azp string `json:"azp"` + // SessionState string `json:"session_state"` + // Acr string `json:"acr"` + // AllowedOrigins []string `json:"allowed-origins"` + // + RealmAccess struct { + Roles []string `json:"roles"` + } `json:"realm_access"` + // + // Scope string `json:"scope"` + // Sid string `json:"sid"` + Upn string `json:"upn"` + // EmailVerified bool `json:"email_verified"` + // Name string `json:"name"` + // Groups []string `json:"groups"` + PreferredUsername string `json:"preferred_username"` + // RealmRole []string `json:"realmRole"` + // GivenName string `json:"given_name"` + // FamilyName string `json:"family_name"` + // Email string `json:"email"` +} + +func init() { + var err error + jwkSet, err = jwk.Fetch(context.Background(), MCIAMMANAGER+"/api/auth/certs") + if err != nil { + panic("failed to fetch JWK: " + err.Error()) + } +} + +func Middleware(role string) buffalo.MiddlewareFunc { + return func(next buffalo.Handler) buffalo.Handler { + return func(c buffalo.Context) error { + accessToken := strings.TrimPrefix(c.Request().Header.Get("Authorization"), "Bearer ") + isvalid, err := IsTokenValid(c, accessToken) + if err != nil { + log.Println(err.Error()) + return c.Render(http.StatusInternalServerError, render.JSON(map[string]interface{}{"error": err.Error()})) + } + if !isvalid { + return c.Render(http.StatusUnauthorized, render.JSON(map[string]interface{}{"error": "token is invalid"})) + } + if !IsTokenHasRole(c, role) { + return c.Render(http.StatusUnauthorized, render.JSON(map[string]interface{}{"error": "role is invalid"})) + } + return next(c) + } + } +} + +func IsTokenValid(c buffalo.Context, tokenString string) (bool, error) { + token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, keyfunction) + if err != nil { + return false, fmt.Errorf("failed to parse token: %s", err.Error()) + } + + if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid { + c.Set("Sub", claims.Sub) + c.Set("PreferredUsername", claims.PreferredUsername) + c.Set("RealmAccessRoles", claims.RealmAccess.Roles) + c.Set("Upn", claims.Upn) + return true, nil + } else { + return false, nil + } +} + +func IsTokenHasRole(c buffalo.Context, role string) bool { + if role == "" { + return true + } + realmAccess := c.Value("RealmAccessRoles").([]string) + return contains(realmAccess, role) +} + +func keyfunction(token *jwt.Token) (interface{}, error) { + if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + } + kid := token.Header["kid"].(string) + keys, nokey := jwkSet.LookupKeyID(kid) + if !nokey { + return nil, fmt.Errorf("no keys found for kid: %s", kid) + } + var raw interface{} + if err := keys.Raw(&raw); err != nil { + return nil, fmt.Errorf("failed to get key: %s", err) + } + return raw, nil +} + +func contains(slice []string, item string) bool { + for _, v := range slice { + if v == item { + return true + } + } + return false +} diff --git a/mc_web_console_api/handler/mcinframanager/const.go b/mc_web_console_api/handler/mcinframanager/const.go new file mode 100644 index 00000000..4d28c9eb --- /dev/null +++ b/mc_web_console_api/handler/mcinframanager/const.go @@ -0,0 +1,100 @@ +package mcinframanager + +var ( + // getMcisList = "/ns/{nsId}/mcis" + // getMcis = "/ns/{nsId}/mcis/{mcisId}" + // delMcis = "/ns/{nsId}/mcis/{mcisId}" + // createMcis = "/ns/{nsId}/mcis" + // createDynamicMcis = "/ns/{nsId}/mcisDynamic" + // getLoadDefaultResource = "/ns/{nsId}/loadDefaultResource" + // delDefaultResource = "/ns/{nsId}/defaultResources" + // mcisRecommendVm = "/mcisRecommendVm" + // mcisDynamicCheckRequest = "/mcisDynamicCheckRequest" + // sendCommandToMcis = "/ns/{nsId}/cmd/mcis/{mcisId}" + // controlLifecycle = "/ns/{nsId}/control/mcis/{mcisId}" + // getImageId = "/ns/system-purpose-common-ns/resources/image/{imageId}" + // createVMDynamic = "/ns/{nsId}/mcis/{mcisId}/vmDynamic" + + // 퍼블릭 VM Image + getPublicImage = "/ns/system-purpose-common-ns/resources/image/{imageId}" + /////////////////// + GetObjects = "/object" + DeleteObjects = "/object" + GetProviderList = "/provider" + GetRegion = "/provider/{providerName}/region/{regionName}" + RegisterCredential = "/credential" + ForwardAnyReqToAny = "/forward/{path}" + CheckHTTPVersion = "/httpVersion" + GetConfig = "/config/{configId}" + InitConfig = "/config/{configId}" + GetConnConfigList = "/connConfig" + PostMcisVmDynamic = "/ns/{nsId}/mcis/{mcisId}/vmDynamic" + PostImage = "/ns/{nsId}/resources/image" + DelAllImage = "/ns/{nsId}/resources/image" + GetImage = "/ns/{nsId}/resources/image/{imageId}" + GetMcisPolicy = "/ns/{nsId}/policies/mcis/{mcisId}" + PostMcisPolicy = "/ns/{nsId}/policies/mcis/{mcisId}" + DelMcisPolicy = "/ns/{nsId}/policies/mcis/{mcisId}" + GetLoadDefaultResource = "/ns/{nsId}/loadDefaultResource" + DelDefaultResource = "/ns/{nsId}/defaultResources" + McisRecommendVm = "/mcisRecommendVm" + PostCmdMcis = "/ns/{nsId}/cmd/mcis/{mcisId}" + GetControlMcis = "/ns/{nsId}/control/mcis/{mcisId}" + PostMcisDynamicCheckRequest = "/mcisDynamicCheckRequest" + InspectResourcesOverview = "/inspectResourcesOverview" + GetCloudOSList = "/cloudOS" + GetConnConfig = "/connConfig/{connConfigName}" + PostConnConfig = "/connConfig" + DeleteConnConfig = "/connConfig/{connConfigName}" + GetSshKeyList = "/ns/{nsId}/resources/sshKey" + GetSshKey = "/ns/{nsId}/resources/sshKey/{sshKeyId}" + CreateSshKey = "/ns/{nsId}/resources/sshKey" + DeleteSshKey = "/ns/{nsId}/resources/sshKey/{sshKeyId}" + DeleteAllSshKey = "/ns/{nsId}/resources/sshKey" + RegisterImageWithId = "/ns/{nsId}/resources/image/registerWithId" + RegisterImageWithInfo = "/ns/{nsId}/resources/image/registerWithInfo" + GetAllResources = "/inspectAllResources" + CheckResource = "/checkResource/{resourceType}" + RegisterNS = "/ns" + GetNSList = "/ns" + GetNS = "/ns/{nsId}" + DeleteNS = "/ns/{nsId}" + DeleteAllNS = "/ns" + RegisterMCISPolicy = "/ns/{nsId}/policies/mcis" + GetAllMcisPolicy = "/ns/{nsId}/policies/mcis" + GetVPCList = "/ns/{nsId}/resources/vpc" + GetVPC = "/ns/{nsId}/resources/vpc/{vpcId}" + CreateVPC = "/ns/{nsId}/resources/vpc" + DeleteVPC = "/ns/{nsId}/resources/vpc/{vpcId}" + DeleteAllVPC = "/ns/{nsId}/resources/vpc" + GetSGList = "/ns/{nsId}/resources/securityGroup" + GetSG = "/ns/{nsId}/resources/securityGroup/{securityGroupId}" + CreateSG = "/ns/{nsId}/resources/securityGroup" + DeleteSG = "/ns/{nsId}/resources/securityGroup/{securityGroupId}" + DeleteAllSG = "/ns/{nsId}/resources/securityGroup" + GetSpecList = "/ns/{nsId}/resources/spec" + GetSpec = "/ns/{nsId}/resources/spec/{specId}" + CreateSpec = "/ns/{nsId}/resources/spec" + DeleteSpec = "/ns/{nsId}/resources/spec/{specId}" + DeleteAllSpec = "/ns/{nsId}/resources/spec" + GetCommonSpecList = "/spec" + GetCommonSpec = "/spec/{specId}" + GetResourceCommonSpec = "/spec/{resourceType}/{specId}" + GetConnConfigListByType = "/connConfig/type/{connType}" + GetResourceList = "/resource" + GetResource = "/resource/{resourceId}" + GetMcisList = "/ns/{nsId}/mcis" + GetMcis = "/ns/{nsId}/mcis/{mcisId}" + CreateMcis = "/ns/{nsId}/mcis" + DeleteMcis = "/ns/{nsId}/mcis/{mcisId}" + DeleteAllMcis = "/ns/{nsId}/mcis" + CreateDynamicMcis = "/ns/{nsId}/mcisDynamic" + GetVm = "/ns/{nsId}/mcis/{mcisId}/vm/{vmId}" + GetVmList = "/ns/{nsId}/mcis/{mcisId}/vm" + CreateVm = "/ns/{nsId}/mcis/{mcisId}/vm" + DeleteVm = "/ns/{nsId}/mcis/{mcisId}/vm/{vmId}" + DeleteAllVm = "/ns/{nsId}/mcis/{mcisId}/vm" + GetResourceByConn = "/conn/{connConfigName}/resource/{resourceType}" + GetAllResourcesByType = "/resources/{resourceType}" + GetAllResourcesByConn = "/conn/{connConfigName}/resources" +) diff --git a/mc_web_console_api/handler/mcinframanager/mcinframanager.go b/mc_web_console_api/handler/mcinframanager/mcinframanager.go new file mode 100644 index 00000000..0ab708d9 --- /dev/null +++ b/mc_web_console_api/handler/mcinframanager/mcinframanager.go @@ -0,0 +1,227 @@ +package mcinframanager + +import ( + "encoding/base64" + "mc_web_console_api/handler" + "net/http" + "os" + + "github.com/gobuffalo/buffalo" +) + +var MCINFRAMANAGER = os.Getenv("MCINFRAMANAGER") + +func InfraGetMcisList(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetMcisList, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraGetMcis(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetMcis, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraDeleteMcis(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodDelete, MCINFRAMANAGER, DeleteMcis, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraCreateMcis(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodPost, MCINFRAMANAGER, CreateMcis, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraCreateDynamicMcis(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodPost, MCINFRAMANAGER, CreateDynamicMcis, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraGetLoadDefaultResouce(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetLoadDefaultResource, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraDeleteDefaultResouce(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodDelete, MCINFRAMANAGER, DelDefaultResource, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraMcisRecommendVm(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodPost, MCINFRAMANAGER, McisRecommendVm, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraMcisDynamicCheckRequest(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodPost, MCINFRAMANAGER, PostMcisDynamicCheckRequest, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraCmdMCIS(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodPost, MCINFRAMANAGER, PostCmdMcis, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +// MCIS의 lifecycle 제어(suspend, resume, terminate) +func InfraControlMcis(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetControlMcis, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +// system-purpose-common-ns 에 import 된 public image 단건조회 +func InfraGetPublicImage(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + // endPoint := "/ns/{nsId}/resources/image/{imageId}" + // common에 있는 이미지 사용 + // TODO: custom 일 때 처리 + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, getPublicImage, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraMcisVmDynamic(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + // endPoint := "/ns/{nsId}/resources/image/{imageId}" + // common에 있는 이미지 사용 + // TODO: custom 일 때 처리 + // endPoint := "/ns/{nsId}/mcis/{mcisId}/vmDynamic" + commonResponse, _ := handler.CommonCaller(http.MethodPost, MCINFRAMANAGER, PostMcisVmDynamic, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +/////////////////Settings Resources Area ////////////////////// + +func InfraGetVPCList(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetVPCList, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraGetVPC(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetVPC, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraCreateVPC(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodPost, MCINFRAMANAGER, CreateVPC, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraDeleteVPC(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodDelete, MCINFRAMANAGER, DeleteVPC, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +// Admin only : Delete all vpc +func InfraDeleteAllVPC(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodDelete, MCINFRAMANAGER, DeleteAllVPC, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +// // +func InfraGetSecurityGroupList(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetSGList, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraGetSecurityGroup(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetSG, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraCreateSecurityGroup(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodPost, MCINFRAMANAGER, CreateVPC, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraDeleteSecurityGroup(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodDelete, MCINFRAMANAGER, DeleteSG, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +// Admin only : Delete all security group +func InfraDeleteAllSecurityGroup(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodDelete, MCINFRAMANAGER, DeleteAllSG, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +// // +func InfraGetVmSpecList(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetSpecList, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraGetVmSpec(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetSpec, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraCreateVmSpec(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodPost, MCINFRAMANAGER, CreateSpec, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraDeleteVmSpec(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodDelete, MCINFRAMANAGER, DeleteSpec, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +// Admin only : Delete all vm spec +func InfraDeleteAllVmSpec(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodDelete, MCINFRAMANAGER, DeleteAllSpec, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +// // +func InfraGetCommonVmSpecList(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetCommonSpecList, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraGetCommonVmSpec(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetCommonSpec, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraGetResourceCommonSpec(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetResourceCommonSpec, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraGetConnConfigListByType(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetConnConfigListByType, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +// GetResourceList +func InfraGetResourceList(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetResourceList, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +// GetResource +func InfraGetResource(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetResource, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +// InfraGetResourceByConn +func InfraGetResourceByConn(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetResource, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraGetAllResourcesByType(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetAllResourcesByType, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +func InfraGetAllResourcesByConn(c buffalo.Context, commonRequest *handler.CommonRequest) *handler.CommonResponse { + commonResponse, _ := handler.CommonCaller(http.MethodGet, MCINFRAMANAGER, GetAllResourcesByConn, commonRequest, mcinframanagerAuthentication()) + return commonResponse +} + +// ///////////////Settings Resources Area End ////////////////////// +// auth fot mcinframanager +func mcinframanagerAuthentication() string { + apiusername := os.Getenv("API_USERNAME") + apipassword := os.Getenv("API_PASSWORD") + apiUserInfo := apiusername + ":" + apipassword + encA := base64.StdEncoding.EncodeToString([]byte(apiUserInfo)) + return "Basic " + encA +} diff --git a/mc_web_console_api/handler/mcinframanager/models.go b/mc_web_console_api/handler/mcinframanager/models.go new file mode 100644 index 00000000..6f9172db --- /dev/null +++ b/mc_web_console_api/handler/mcinframanager/models.go @@ -0,0 +1 @@ +package mcinframanager diff --git a/mc_web_console_api/handler/self/const.go b/mc_web_console_api/handler/self/const.go new file mode 100644 index 00000000..51e34e22 --- /dev/null +++ b/mc_web_console_api/handler/self/const.go @@ -0,0 +1 @@ +package self diff --git a/mc_web_console_api/handler/self/models.go b/mc_web_console_api/handler/self/models.go new file mode 100644 index 00000000..3c0b06e7 --- /dev/null +++ b/mc_web_console_api/handler/self/models.go @@ -0,0 +1,27 @@ +package self + +type LookupDiskInfo struct { + // create disk list + ProviderID string `json:"providerId"` + + RootDiskType []string `json:"rootdisktype"` + + // + DataDiskType []string `json:"datadisktype"` + + // disk size range by diskType + DiskSize []string `json:"disksize"` +} + +type AvailableDiskType struct { + // create disk list + ProviderID string `json:"providerId"` + + RootDiskType []string `json:"rootdisktype"` + + // + DataDiskType []string `json:"datadisktype"` + + // disk size range by diskType + DiskSize []string `json:"disksize"` +} diff --git a/mc_web_console_api/handler/self/self.go b/mc_web_console_api/handler/self/self.go new file mode 100644 index 00000000..165f642d --- /dev/null +++ b/mc_web_console_api/handler/self/self.go @@ -0,0 +1,154 @@ +package self + +import ( + "mc_web_console_api/handler" + "strings" + + "github.com/gobuffalo/buffalo" +) + +// Disk 정보 조회 +// Provider, connection 에서 사용가능한 DiskType 조회 +// 현재 : spider의 cloudos_meta.yaml 값 사용 +// func DiskLookup(providerId string, connectionName string) ([]handler.LookupDiskInfo, error) { +func DiskLookup(c buffalo.Context, commonRequest *handler.CommonRequest) (*handler.CommonResponse, error) { + + providerId := strings.ToUpper(commonRequest.QueryParams["provider"]) + connectionName := commonRequest.QueryParams["connectionName"] + + //defaultNameSpaceID := loginInfo.DefaultNameSpaceID + diskInfoMap := map[string]LookupDiskInfo{} + + // 변환 : 구분자만 빼서 공백 빼고 array로 + awsRootdiskType := "standard / gp2 / gp3" + awsDiskType := "standard / gp2 / gp3 / io1 / io2 / st1 / sc1" + awsDiskSize := "standard|1|1024|GB / gp2|1|16384|GB / gp3|1|16384|GB / io1|4|16384|GB / io2|4|16384|GB / st1|125|16384|GB / sc1|125|16384|GB" + + awsDiskInfo := LookupDiskInfo{} + awsDiskInfo.ProviderID = "AWS" + awsDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(awsRootdiskType, " ", ""), "/") + awsDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(awsDiskType, " ", ""), "/") + awsDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(awsDiskSize, " ", ""), "/") + diskInfoMap["AWS"] = awsDiskInfo + + gcpRootdiskType := "pd-standard / pd-balanced / pd-ssd / pd-extreme" + gcpDiskType := "pd-standard / pd-balanced / pd-ssd / pd-extreme" + gcpDiskSize := "pd-standard|10|65536|GB / pd-balanced|10|65536|GB / pd-ssd|10|65536|GB / pd-extreme|500|65536|GB" + + gcpDiskInfo := LookupDiskInfo{} + gcpDiskInfo.ProviderID = "GCP" + gcpDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(gcpRootdiskType, " ", ""), "/") + gcpDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(gcpDiskType, " ", ""), "/") + gcpDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(gcpDiskSize, " ", ""), "/") + diskInfoMap["GCP"] = gcpDiskInfo + + aliRootdiskType := "cloud_essd / cloud_efficiency / cloud / cloud_ssd" + aliDiskType := "cloud / cloud_efficiency / cloud_ssd / cloud_essd" + aliDiskSize := "cloud|5|2000|GB / cloud_efficiency|20|32768|GB / cloud_ssd|20|32768|GB / cloud_essd_PL0|40|32768|GB / cloud_essd_PL1|20|32768|GB / cloud_essd_PL2|461|32768|GB / cloud_essd_PL3|1261|32768|GB" + + aliDiskInfo := LookupDiskInfo{} + aliDiskInfo.ProviderID = "ALIBABA" + aliDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(aliRootdiskType, " ", ""), "/") + aliDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(aliDiskType, " ", ""), "/") + aliDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(aliDiskSize, " ", ""), "/") + diskInfoMap["ALIBABA"] = aliDiskInfo + + tencentRootdiskType := "CLOUD_PREMIUM / CLOUD_SSD" + tencentDiskType := "CLOUD_PREMIUM / CLOUD_SSD / CLOUD_HSSD / CLOUD_BASIC / CLOUD_TSSD" + tencentDiskSize := "CLOUD_PREMIUM|10|32000|GB / CLOUD_SSD|20|32000|GB / CLOUD_HSSD|20|32000|GB / CLOUD_BASIC|10|32000|GB / CLOUD_TSSD|10|32000|GB" + + tencentDiskInfo := LookupDiskInfo{} + tencentDiskInfo.ProviderID = "TENCENT" + tencentDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(tencentRootdiskType, " ", ""), "/") + tencentDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(tencentDiskType, " ", ""), "/") + tencentDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(tencentDiskSize, " ", ""), "/") + diskInfoMap["TENCENT"] = tencentDiskInfo + + dataDiskInfoList := []LookupDiskInfo{} + if providerId != "" { + // TODO : 해당 connection으로 사용가능한 DISK 정보 조회 + if connectionName != "" { // 현재는 connection으로 filter 하지 않음 + + } + //providerDisk := LookupDiskInfo{} + providerDisk := diskInfoMap[providerId] + dataDiskInfoList = append(dataDiskInfoList, providerDisk) + } else if connectionName != "" { + // 모든 provider의 datadisk 정보 조회... + // getConnection 에서 Provider 가져옴 + + } + + commonResponse := &handler.CommonResponse{} + commonResponse.Status.Message = "success" + commonResponse.Status.StatusCode = 200 + commonResponse.ResponseData = dataDiskInfoList + return commonResponse, nil +} + +// Provider, Region 에서 사용가능한 DiskType 조회 +// 현재 : spider의 cloudos_meta.yaml 값 사용 +// Region 값에 따라 달라지는게 있으면 추가할 것.c buffalo.Context, commonRequest *handler.CommonRequest +func AvailableDiskTypeByProviderRegion(c buffalo.Context, commonRequest *handler.CommonRequest) ([]AvailableDiskType, error) { + + providerId := strings.ToUpper(commonRequest.QueryParams["provider"]) + regionName := commonRequest.QueryParams["regionName"] + + diskInfoMap := map[string]AvailableDiskType{} + + // 변환 : 구분자만 빼서 공백 빼고 array로 + awsRootdiskType := "standard / gp2 / gp3" + awsDiskType := "standard / gp2 / gp3 / io1 / io2 / st1 / sc1" + awsDiskSize := "standard|1|1024|GB / gp2|1|16384|GB / gp3|1|16384|GB / io1|4|16384|GB / io2|4|16384|GB / st1|125|16384|GB / sc1|125|16384|GB" + + awsDiskInfo := AvailableDiskType{} + awsDiskInfo.ProviderID = "AWS" + awsDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(awsRootdiskType, " ", ""), "/") + awsDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(awsDiskType, " ", ""), "/") + awsDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(awsDiskSize, " ", ""), "/") + diskInfoMap["AWS"] = awsDiskInfo + + gcpRootdiskType := "pd-standard / pd-balanced / pd-ssd / pd-extreme" + gcpDiskType := "pd-standard / pd-balanced / pd-ssd / pd-extreme" + gcpDiskSize := "pd-standard|10|65536|GB / pd-balanced|10|65536|GB / pd-ssd|10|65536|GB / pd-extreme|500|65536|GB" + + gcpDiskInfo := AvailableDiskType{} + gcpDiskInfo.ProviderID = "GCP" + gcpDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(gcpRootdiskType, " ", ""), "/") + gcpDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(gcpDiskType, " ", ""), "/") + gcpDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(gcpDiskSize, " ", ""), "/") + diskInfoMap["GCP"] = gcpDiskInfo + + aliRootdiskType := "cloud_essd / cloud_efficiency / cloud / cloud_ssd" + aliDiskType := "cloud / cloud_efficiency / cloud_ssd / cloud_essd" + aliDiskSize := "cloud|5|2000|GB / cloud_efficiency|20|32768|GB / cloud_ssd|20|32768|GB / cloud_essd_PL0|40|32768|GB / cloud_essd_PL1|20|32768|GB / cloud_essd_PL2|461|32768|GB / cloud_essd_PL3|1261|32768|GB" + + aliDiskInfo := AvailableDiskType{} + aliDiskInfo.ProviderID = "ALIBABA" + aliDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(aliRootdiskType, " ", ""), "/") + aliDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(aliDiskType, " ", ""), "/") + aliDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(aliDiskSize, " ", ""), "/") + diskInfoMap["ALIBABA"] = aliDiskInfo + + tencentRootdiskType := "CLOUD_PREMIUM / CLOUD_SSD" + tencentDiskType := "CLOUD_PREMIUM / CLOUD_SSD / CLOUD_HSSD / CLOUD_BASIC / CLOUD_TSSD" + tencentDiskSize := "CLOUD_PREMIUM|10|32000|GB / CLOUD_SSD|20|32000|GB / CLOUD_HSSD|20|32000|GB / CLOUD_BASIC|10|32000|GB / CLOUD_TSSD|10|32000|GB" + + tencentDiskInfo := AvailableDiskType{} + tencentDiskInfo.ProviderID = "TENCENT" + tencentDiskInfo.RootDiskType = strings.Split(strings.ReplaceAll(tencentRootdiskType, " ", ""), "/") + tencentDiskInfo.DataDiskType = strings.Split(strings.ReplaceAll(tencentDiskType, " ", ""), "/") + tencentDiskInfo.DiskSize = strings.Split(strings.ReplaceAll(tencentDiskSize, " ", ""), "/") + diskInfoMap["TENCENT"] = tencentDiskInfo + + dataDiskInfoList := []AvailableDiskType{} + if providerId != "" { + if regionName != "" { // TODO : Region에 따라 달라지면 보완할 것 + + } + providerDisk := diskInfoMap[strings.ToUpper(providerId)] + dataDiskInfoList = append(dataDiskInfoList, providerDisk) + } + + return dataDiskInfoList, nil +} diff --git a/mc_web_console_api/handler/self/sess.go b/mc_web_console_api/handler/self/sess.go new file mode 100644 index 00000000..ea8f3521 --- /dev/null +++ b/mc_web_console_api/handler/self/sess.go @@ -0,0 +1,120 @@ +package self + +import ( + "mc_web_console_api/handler" + "mc_web_console_api/models" + + "github.com/gobuffalo/pop/v6" + "github.com/opentracing/opentracing-go/log" +) + +// buffalo db generate model usersess user_id:text access_token:text expires_in:float64 refresh_token:text refresh_expires_in:float64 + +func CreateUserSessFromResponseData(tx *pop.Connection, r *handler.CommonResponse, userId string) (*models.Usersess, error) { + t := r.ResponseData.(map[string]interface{}) + var s models.Usersess + s.UserID = userId + if accessToken, ok := t["access_token"]; ok { + s.AccessToken = accessToken.(string) + } + if expiresIn, ok := t["expires_in"]; ok { + s.ExpiresIn = expiresIn.(float64) + } + if refreshToken, ok := t["refresh_token"]; ok { + s.RefreshToken = refreshToken.(string) + } + if refreshExpiresIn, ok := t["refresh_expires_in"]; ok { + s.RefreshExpiresIn = refreshExpiresIn.(float64) + } + sess, err := CreateUserSess(tx, &s) + if err != nil { + return nil, err + } + return sess, nil +} + +func CreateUserSess(tx *pop.Connection, s *models.Usersess) (*models.Usersess, error) { + userExist, err := IsUserSessExistByUserId(tx, s.UserID) + if err != nil { + log.Error(err) + return nil, err + } + if userExist { + orgs, err := GetUserByUserId(tx, s.UserID) + if err != nil { + log.Error(err) + return nil, err + } + s.ID = orgs.ID + update, err := UpdateUserSess(tx, s) + if err != nil { + log.Error(err) + return nil, err + } + return update, nil + } else { + err := tx.Create(s) + if err != nil { + log.Error(err) + return nil, err + } + return s, nil + } +} + +func IsUserSessExistByUserId(tx *pop.Connection, userId string) (bool, error) { + var cnt int + err := tx.RawQuery("SELECT COUNT(*) FROM usersesses WHERE user_id = ?;", userId).First(&cnt) + if err != nil { + log.Error(err) + return false, err + } + if cnt != 0 { + return true, nil + } + return false, nil +} + +func GetUserByUserId(tx *pop.Connection, userId string) (*models.Usersess, error) { + var s models.Usersess + err := tx.Where("user_id = ?", userId).First(&s) + if err != nil { + log.Error(err) + return nil, err + } + return &s, nil +} + +func UpdateUserSess(tx *pop.Connection, s *models.Usersess) (*models.Usersess, error) { + err := tx.Update(s) + if err != nil { + log.Error(err) + return nil, err + } + return s, nil +} + +func DestroyUserSessByAccesstokenforLogout(tx *pop.Connection, t string) (string, error) { + var s models.Usersess + err := tx.Where("access_token = ?", t).First(&s) + if err != nil { + log.Error(err) + return "", err + } + refreshToken := s.RefreshToken + err = DestroyUserSess(tx, &s) + if err != nil { + log.Error(err) + return "", err + } + return refreshToken, nil +} + +func DestroyUserSess(tx *pop.Connection, s *models.Usersess) error { + err := tx.Destroy(s) + if err != nil { + log.Error(err) + return err + } + return nil +} diff --git a/mc_web_console_api/handler/tbhandler/McisHandler.go b/mc_web_console_api/handler/tbhandler/McisHandler.go deleted file mode 100644 index d5eae341..00000000 --- a/mc_web_console_api/handler/tbhandler/McisHandler.go +++ /dev/null @@ -1,100 +0,0 @@ -package tbhandler - -// func McisList(request *webconsole.CommonRequest) ([]tbmcis.TbMcisInfo, fwmodels.WebStatus) { -// //var originalUrl = "/ns/{nsId}/mcis" -// returnMcisList := map[string][]tbmcis.TbMcisInfo{} -// returnStatus := fwmodels.WebStatus{} - -// resp, err := GetFrameworkCall(request) -// if err != nil { -// fmt.Println(err) -// return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} -// } - -// respBody := resp.Body -// respStatus := resp.StatusCode - -// if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set -// failResultInfo := tbcommon.TbSimpleMsg{} -// json.NewDecoder(respBody).Decode(&failResultInfo) -// return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} -// } -// json.NewDecoder(respBody).Decode(&returnMcisList) -// fmt.Println(returnMcisList["mcis"]) - -// returnStatus.StatusCode = respStatus -// log.Println(respBody) - -// return returnMcisList["mcis"], returnStatus -// } - -// func GetFrameworkCall(request *webconsole.CommonRequest) (*http.Response, error) { -// var targetUrl = "" - -// if request.PathParam != nil { -// targetUrl = request.OriginalUrl -// for key, value := range request.PathParam { -// placeholder := "{" + key + "}" -// targetUrl = strings.Replace(targetUrl, placeholder, fmt.Sprint(value), -1) -// } -// } - -// if request.QueryParam != nil { -// query := "?" -// for key, value := range request.QueryParam { -// query += key + "=" + fmt.Sprint(value) + "&" -// } -// targetUrl += query -// } - -// url := request.TargetFramework + targetUrl -// resp, err := util.CommonHttp(url, nil, http.MethodGet) - -// return resp, err -// } - -// func McisList(pathParam map[string]interface{}, queryParam map[string]interface{})([]tbmcis.TbMcisInfo, fwmodels.WebStatus){ -// var originalUrl = "/ns/{nsId}/mcis" -// var targetUrl = "" -// returnMcisList := map[string][]tbmcis.TbMcisInfo{} -// returnStatus := fwmodels.WebStatus{} - -// if pathParam != nil { -// for key, value := range pathParam { -// placeholder := "{" + key + "}" -// targetUrl = strings.Replace(originalUrl, placeholder, fmt.Sprint(value), -1) -// } -// } - -// if queryParam != nil { -// query := "?" -// for key, value := range queryParam { -// query += key + "=" + fmt.Sprint(value) + "&" -// } -// targetUrl += query -// } - -// url := util.TUMBLEBUG + targetUrl -// resp, err := util.CommonHttp(url, nil, http.MethodGet) - -// if err != nil { -// fmt.Println(err) -// return nil, fwmodels.WebStatus{StatusCode: 500, Message: err.Error()} -// } - -// respBody := resp.Body -// respStatus := resp.StatusCode - -// if respStatus != 200 && respStatus != 201 { // 호출은 정상이나, 가져온 결과값이 200, 201아닌 경우 message에 담겨있는 것을 WebStatus에 set -// failResultInfo := tbcommon.TbSimpleMsg{} -// json.NewDecoder(respBody).Decode(&failResultInfo) -// return nil, fwmodels.WebStatus{StatusCode: respStatus, Message: failResultInfo.Message} -// } -// json.NewDecoder(respBody).Decode(&returnMcisList) -// fmt.Println(returnMcisList["mcis"]) - -// returnStatus.StatusCode = respStatus -// log.Println(respBody) - -// return returnMcisList["mcis"], returnStatus -// } diff --git a/mc_web_console_api/locales/all.en-us.yaml b/mc_web_console_api/locales/all.en-us.yaml deleted file mode 100644 index 6514e210..00000000 --- a/mc_web_console_api/locales/all.en-us.yaml +++ /dev/null @@ -1,3 +0,0 @@ -# For more information on using i18n see: https://github.com/nicksnyder/go-i18n -- id: welcome_greeting - translation: "Welcome to Buffalo (EN)" diff --git a/mc_web_console_api/locales/embed.go b/mc_web_console_api/locales/embed.go deleted file mode 100644 index 165d92f3..00000000 --- a/mc_web_console_api/locales/embed.go +++ /dev/null @@ -1,15 +0,0 @@ -package locales - -import ( - "embed" - "io/fs" - - "github.com/gobuffalo/buffalo" -) - -//go:embed *.yaml -var files embed.FS - -func FS() fs.FS { - return buffalo.NewFS(files, "locales") -} diff --git a/mc_web_console_api/migrations/20240412082006_create_usersessions.down.fizz b/mc_web_console_api/migrations/20240412082006_create_usersessions.down.fizz deleted file mode 100644 index f29d870d..00000000 --- a/mc_web_console_api/migrations/20240412082006_create_usersessions.down.fizz +++ /dev/null @@ -1 +0,0 @@ -drop_table("usersessions") \ No newline at end of file diff --git a/mc_web_console_api/migrations/20240412082006_create_usersessions.up.fizz b/mc_web_console_api/migrations/20240412082006_create_usersessions.up.fizz deleted file mode 100644 index 59cf6698..00000000 --- a/mc_web_console_api/migrations/20240412082006_create_usersessions.up.fizz +++ /dev/null @@ -1,8 +0,0 @@ -create_table("usersessions") { - t.Column("id", "uuid", {primary: true}) - t.Column("access_token", "text", {}) - t.Column("expires_in", "integer", {}) - t.Column("refresh_token", "text", {}) - t.Column("refresh_expires_in", "integer", {}) - t.Timestamps() -} \ No newline at end of file diff --git a/mc_web_console_api/migrations/20240619051108_create_usersesses.down.fizz b/mc_web_console_api/migrations/20240619051108_create_usersesses.down.fizz new file mode 100644 index 00000000..0b675155 --- /dev/null +++ b/mc_web_console_api/migrations/20240619051108_create_usersesses.down.fizz @@ -0,0 +1 @@ +drop_table("usersesses") \ No newline at end of file diff --git a/mc_web_console_api/migrations/20240619051108_create_usersesses.up.fizz b/mc_web_console_api/migrations/20240619051108_create_usersesses.up.fizz new file mode 100644 index 00000000..f19d24cc --- /dev/null +++ b/mc_web_console_api/migrations/20240619051108_create_usersesses.up.fizz @@ -0,0 +1,11 @@ +create_table("usersesses") { + t.Column("id", "uuid", {primary: true}) + t.Column("user_id", "text", {}) + t.Column("access_token", "text", {}) + t.Column("expires_in", "decimal", {}) + t.Column("refresh_token", "text", {}) + t.Column("refresh_expires_in", "decimal", {}) + t.Timestamps() +} + +add_index("usersesses", "user_id", {"unique": true}) diff --git a/mc_web_console_api/models/RouteInfo.go b/mc_web_console_api/models/RouteInfo.go deleted file mode 100644 index 2eb4f610..00000000 --- a/mc_web_console_api/models/RouteInfo.go +++ /dev/null @@ -1,65 +0,0 @@ -package models - -import ( - "encoding/json" - "time" - - "github.com/gobuffalo/nulls" - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" - "github.com/gobuffalo/validate/v3/validators" - "github.com/gofrs/uuid" -) - -// RouteInfo is used by pop to map your route_infoes database table to your go code. -type RouteInfo struct { - ID uuid.UUID `json:"id" db:"id"` - Method string `json:"method" db:"method"` - Path string `json:"path" db:"path"` - HandlerName string `json:"handler_name" db:"handler_name"` - ResourceName nulls.String `json:"resource_name" db:"resource_name"` - PathName string `json:"path_name" db:"path_name"` - Aliases nulls.String `json:"aliases" db:"aliases"` - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` -} - -// String is not required by pop and may be deleted -func (r RouteInfo) String() string { - jr, _ := json.Marshal(r) - return string(jr) -} - -// RouteInfoes is not required by pop and may be deleted -type RouteInfoes []RouteInfo - -// String is not required by pop and may be deleted -func (r RouteInfoes) String() string { - jr, _ := json.Marshal(r) - return string(jr) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (r *RouteInfo) Validate(tx *pop.Connection) (*validate.Errors, error) { - return validate.Validate( - &validators.StringIsPresent{Field: r.Method, Name: "Method"}, - &validators.StringIsPresent{Field: r.Path, Name: "Path"}, - &validators.StringIsPresent{Field: r.HandlerName, Name: "HandlerName"}, - //&validators.StringIsPresent{Field: r.ResourceName, Name: "ResourceName"}, - &validators.StringIsPresent{Field: r.PathName, Name: "PathName"}, - //&validators.StringIsPresent{Field: r.Aliases, Name: "Aliases"}, - ), nil -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (r *RouteInfo) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (r *RouteInfo) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} diff --git a/mc_web_console_api/models/RouteInfo_test.go b/mc_web_console_api/models/RouteInfo_test.go deleted file mode 100644 index 5f6d4c43..00000000 --- a/mc_web_console_api/models/RouteInfo_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_RouteInfo() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/category.go b/mc_web_console_api/models/category.go deleted file mode 100644 index 0dd035de..00000000 --- a/mc_web_console_api/models/category.go +++ /dev/null @@ -1,55 +0,0 @@ -package models - -import ( - "encoding/json" - "time" - - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" -) - -// Category is used by pop to map your categories database table to your go code. -type Category struct { - ID string `json:"id" db:"id"` - - CategoryName string `json:"category_name" db:"category_name"` - ParentCategoryID string `json:"parent_category_id" db:"parent_category_id"` - Description string `json:"description" db:"description"` - Sort int `json:"sort" db:"sort"` - - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` -} - -// String is not required by pop and may be deleted -func (c Category) String() string { - jc, _ := json.Marshal(c) - return string(jc) -} - -// Categories is not required by pop and may be deleted -type Categories []Category - -// String is not required by pop and may be deleted -func (c Categories) String() string { - jc, _ := json.Marshal(c) - return string(jc) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (c *Category) Validate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (c *Category) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (c *Category) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} diff --git a/mc_web_console_api/models/category_test.go b/mc_web_console_api/models/category_test.go deleted file mode 100644 index bd626fd9..00000000 --- a/mc_web_console_api/models/category_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_Category() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/cloud_connection.go b/mc_web_console_api/models/cloud_connection.go deleted file mode 100644 index 172a76d2..00000000 --- a/mc_web_console_api/models/cloud_connection.go +++ /dev/null @@ -1,76 +0,0 @@ -package models - -import ( - "encoding/json" - "time" - - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" - "github.com/gofrs/uuid" -) - -// CloudConnection is used by pop to map your cloud_connections database table to your go code. -type CloudConnection struct { - ID uuid.UUID `json:"connection_id" db:"id"` - ConnectionName string `db:"connection_name"` - - // 사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함. - ProviderID string `json:"provider_id" db:"provider_id"` - Provider *CloudProvider `belongs_to:"cloud_provider"` - - CredentialID uuid.UUID `json:"credential_id" db:"credential_id"` - Credential *Credential `belongs_to:"cloud_credential"` - - DriverID uuid.UUID `json:"driver_id" db:"driver_id"` - Driver *Driver `belongs_to:"driver"` - - RegionID uuid.UUID `json:"region_id" db:"region_id"` - Region *Region `belongs_to:"region"` - - // 사용 될 참조 - //CloudConnections CloudConnections `has_many:"cloud_connection"` - //CredentialKeyValues CredentialKeyvalues `has_many:"credential_keyvalue"` // 여러개는 객체 - - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` -} - -// String is not required by pop and may be deleted -func (c CloudConnection) String() string { - jc, _ := json.Marshal(c) - return string(jc) -} - -// CloudConnections is not required by pop and may be deleted -type CloudConnections []CloudConnection - -// String is not required by pop and may be deleted -func (c CloudConnections) String() string { - jc, _ := json.Marshal(c) - return string(jc) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (c *CloudConnection) Validate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (c *CloudConnection) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (c *CloudConnection) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -func (c *CloudConnection) Create(tx *pop.Connection) (*validate.Errors, error) { - return tx.ValidateAndCreate(c) -} -func (c *CloudConnection) Update(tx *pop.Connection) (*validate.Errors, error) { - return tx.ValidateAndUpdate(c) -} diff --git a/mc_web_console_api/models/cloud_connection_mapping.go b/mc_web_console_api/models/cloud_connection_mapping.go deleted file mode 100644 index 7e3ac7c4..00000000 --- a/mc_web_console_api/models/cloud_connection_mapping.go +++ /dev/null @@ -1,102 +0,0 @@ -package models - -import ( - "encoding/json" - "time" - - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" - "github.com/gobuffalo/validate/v3/validators" - "github.com/gofrs/uuid" -) - -// CloudConnectionMapping is used by pop to map your cloud_connection_mappings database table to your go code. -type CloudConnectionMapping struct { - ID uuid.UUID `json:"id" db:"id"` - - CredentialID uuid.UUID `json:"credential_id" db:"credential_id"` - Credential *Credential `belongs_to:"credential"` - - CloudConnectionID uuid.UUID `json:"connection_id" db:"connection_id"` - CloudConnection *CloudConnection `belongs_to:"cloud_connection"` - - Status string `json:"status" db:"status"` // C:Create, D:Delete, U:Update - ResourceType string `json:"resource_type" db:"resource_type"` // vpc, securitygroup, sshkey, vmimage, vmspec, nlb, vm, mckscontrolplane, mcksworkernode, pmks - ResourceID string `json:"resource_id" db:"resource_id"` // 해당 resource의 ID를 string으로 - ResourceName string `json:"resource_name" db:"resource_name"` // 해당 resource의 ID를 string으로 - - NamespaceID string `json:"namespace_id" db:"namespace_id"` - NamespaceName string `json:"namespace_name" db:"namespace_name"` - - // 1안 connection , csp, region, zone, credential ? - - // 쿼리로 csp, region 을 받아 user의 credential로 connection 조회 - // 생성의 경우 선행 작업에서 사용한 connection 사용 - // 선행작업이 없는 경우 credential random가능 - // - - // 2안 resourceType, resourceId, connection, credential - // 사용되는 connection은 mapping 테이블에 저장 - // 생성의 경우 csp, region으로 credential과 함께 connection 조회 - // 선행작업이 있는 경우 이전 connection 사용 - // -> 이전 리소스 ID 가 넘어올 것이므로 해당 connection return - // 선행작업이 없는 경우 credential random 가능 - - // mapping table : connection으로 mapping table 넣는다?? - // resource 생성할 때, - // ex) vnet 생성 시. mapping테이블에 credential, connection, resource_type="vpc", resource_id = "vpcID" 로 insert - // -> sg 생성시 vnet 선택하면 mapping table에 resource_type = "vpc", resource_id = "vpcID" 로 조회하여 connection 과 credential 가져온다. - // -> 사용할 credential 과 vpc 생성한 credential이 다르면 validation failed - - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` -} - -// String is not required by pop and may be deleted -func (cm CloudConnectionMapping) String() string { - jc, _ := json.Marshal(cm) - return string(jc) -} - -// CloudConnectionMappings is not required by pop and may be deleted -type CloudConnectionMappings []CloudConnectionMapping - -// String is not required by pop and may be deleted -func (cm CloudConnectionMappings) String() string { - jc, _ := json.Marshal(cm) - return string(jc) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (cm *CloudConnectionMapping) Validate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (cm *CloudConnectionMapping) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - var err error - return validate.Validate( - &validators.StringIsPresent{Field: cm.ResourceID, Name: "ResourceID"}, - ), err - //return validate.NewErrors(), nil -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (cm *CloudConnectionMapping) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - var err error - return validate.Validate( - &validators.StringIsPresent{Field: cm.ResourceID, Name: "ResourceID"}, - ), err - //return validate.NewErrors(), nil -} - -func (cm *CloudConnectionMapping) Create(tx *pop.Connection) (*validate.Errors, error) { - return tx.ValidateAndCreate(cm) -} - -func (cm *CloudConnectionMapping) Update(tx *pop.Connection) (*validate.Errors, error) { - return tx.ValidateAndUpdate(cm) -} diff --git a/mc_web_console_api/models/cloud_connection_mapping_test.go b/mc_web_console_api/models/cloud_connection_mapping_test.go deleted file mode 100644 index 29b91060..00000000 --- a/mc_web_console_api/models/cloud_connection_mapping_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_CloudConnectionMapping() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/cloud_connection_test.go b/mc_web_console_api/models/cloud_connection_test.go deleted file mode 100644 index e735ad30..00000000 --- a/mc_web_console_api/models/cloud_connection_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_CloudConnection() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/cloud_provider.go b/mc_web_console_api/models/cloud_provider.go deleted file mode 100644 index 146b13a6..00000000 --- a/mc_web_console_api/models/cloud_provider.go +++ /dev/null @@ -1,68 +0,0 @@ -package models - -import ( - "encoding/json" - "time" - - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" - "github.com/gobuffalo/validate/v3/validators" -) - -// CloudProvider is used by pop to map your cloud_providers database table to your go code. -type CloudProvider struct { - ProviderID string `json:"provider_id" db:"id"` - ProviderName string `json:"provider_name" db:"provider_name"` - - // CloudConnections []CloudConnection `has_many:"cloud_connection"` - // Credentials []Credential `has_many:"credential"` - // // CloudConnections []CloudConnection `json:"cloud_connections" has_many:"cloud_connections"` - // // Credentials []Credential `json:"credentials" has_many:"credentials"` - // Drivers []Driver `has_many:"driver"` - // Regions []Region `has_many:"region"` - - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` -} - -// String is not required by pop and may be deleted -func (c CloudProvider) String() string { - jc, _ := json.Marshal(c) - return string(jc) -} - -// CloudProviders is not required by pop and may be deleted -type CloudProviders []CloudProvider - -// String is not required by pop and may be deleted -func (c CloudProviders) String() string { - jc, _ := json.Marshal(c) - return string(jc) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (c *CloudProvider) Validate(tx *pop.Connection) (*validate.Errors, error) { - return validate.Validate( - &validators.StringIsPresent{Field: c.ProviderName, Name: "ProviderName"}, - ), nil -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (c *CloudProvider) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (c *CloudProvider) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -func (c *CloudProvider) Create(tx *pop.Connection) (*validate.Errors, error) { - return tx.ValidateAndCreate(c) -} -func (c *CloudProvider) Update(tx *pop.Connection) (*validate.Errors, error) { - return tx.ValidateAndUpdate(c) -} diff --git a/mc_web_console_api/models/cloud_provider_test.go b/mc_web_console_api/models/cloud_provider_test.go deleted file mode 100644 index 4e5ccbb9..00000000 --- a/mc_web_console_api/models/cloud_provider_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_CloudProvider() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/credential.go b/mc_web_console_api/models/credential.go deleted file mode 100644 index 5fbc5a44..00000000 --- a/mc_web_console_api/models/credential.go +++ /dev/null @@ -1,80 +0,0 @@ -package models - -import ( - "encoding/json" - "time" - - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" - "github.com/gobuffalo/validate/v3/validators" - "github.com/gofrs/uuid" -) - -// Credential is used by pop to map your credentials database table to your go code. -type Credential struct { - ID uuid.UUID `json:"id" db:"id"` - CredentialName string `db:"credential_name"` - UserLevel string `db:"user_level"` - - // 사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함. - ProviderID string `json:"provider_id" db:"provider_id"` - Provider *CloudProvider `belongs_to:"cloud_provider"` - - // 사용 될 참조 - CloudConnections CloudConnections `has_many:"cloud_connection"` - CredentialKeyValues CredentialKeyvalues `has_many:"credential_keyvalue"` // 여러개는 객체 - - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` -} - -// Credentials is not required by pop and may be deleted -type Credentials []Credential - -// String is not required by pop and may be deleted -func (c Credential) String() string { - jc, _ := json.Marshal(c) - return string(jc) -} - -// String is not required by pop and may be deleted -func (c Credentials) String() string { - jc, _ := json.Marshal(c) - return string(jc) -} - -func (c *Credential) Create(tx *pop.Connection) (*validate.Errors, error) { - - return tx.ValidateAndCreate(c) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (c *Credential) Validate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (c *Credential) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - var err error - return validate.Validate( - &validators.StringIsPresent{Field: c.ID.String(), Name: "credential_id"}, - ), err - //return validate.NewErrors(), err -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (c *Credential) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - - var err error - return validate.Validate( - &validators.StringIsPresent{Field: c.CredentialName, Name: "CredentialName"}, - ), err - //return validate.NewErrors(), nil -} - -func (c *Credential) Update(tx *pop.Connection) (*validate.Errors, error) { - return tx.ValidateAndUpdate(c) -} diff --git a/mc_web_console_api/models/credential_keyvalue.go b/mc_web_console_api/models/credential_keyvalue.go deleted file mode 100644 index 66e68552..00000000 --- a/mc_web_console_api/models/credential_keyvalue.go +++ /dev/null @@ -1,69 +0,0 @@ -package models - -import ( - "encoding/json" - "time" - - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" - "github.com/gofrs/uuid" -) - -// CredentialKeyvalue is used by pop to map your credential_keyvalues database table to your go code. -type CredentialKeyvalue struct { - ID uuid.UUID `json:"id" db:"id"` - - CredentialID uuid.UUID `json:"credential_id" db:"credential_id"` - Credential *Credential `belongs_to:"credential"` - - Key string `json:"key" db:"key"` - Value string `json:"value" db:"value"` - - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` -} - -func (cv *CredentialKeyvalue) Create(tx *pop.Connection) (*validate.Errors, error) { - - return tx.ValidateAndCreate(cv) -} - -func (cv *CredentialKeyvalue) Update(tx *pop.Connection) (*validate.Errors, error) { - - return tx.ValidateAndUpdate(cv) -} - -// String is not required by pop and may be deleted -func (c CredentialKeyvalue) String() string { - jc, _ := json.Marshal(c) - return string(jc) -} - -// CredentialKeyvalues is not required by pop and may be deleted -type CredentialKeyvalues []CredentialKeyvalue - -// String is not required by pop and may be deleted -func (c CredentialKeyvalues) String() string { - jc, _ := json.Marshal(c) - return string(jc) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (c *CredentialKeyvalue) Validate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (c *CredentialKeyvalue) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - //return validate.NewErrors(), nil - return nil, nil -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (c *CredentialKeyvalue) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - //return validate.NewErrors(), nil - return nil, nil -} diff --git a/mc_web_console_api/models/credential_keyvalue_test.go b/mc_web_console_api/models/credential_keyvalue_test.go deleted file mode 100644 index 89fcb653..00000000 --- a/mc_web_console_api/models/credential_keyvalue_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_CredentialKeyvalue() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/credential_test.go b/mc_web_console_api/models/credential_test.go deleted file mode 100644 index 85ed2f81..00000000 --- a/mc_web_console_api/models/credential_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_Credential() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/driver.go b/mc_web_console_api/models/driver.go deleted file mode 100644 index 284ea4c3..00000000 --- a/mc_web_console_api/models/driver.go +++ /dev/null @@ -1,80 +0,0 @@ -package models - -import ( - "encoding/json" - "log" - "time" - - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" - "github.com/gofrs/uuid" -) - -// Driver is used by pop to map your drivers database table to your go code. -type Driver struct { - ID uuid.UUID `json:"id" db:"id"` - DriverName string `json:"driver_name" db:"driver_name"` - LibFileName string `json:"lib_file_name" db:"lib_file_name"` - - ProviderID string `json:"provider_id" db:"provider_id"` - Provider *CloudProvider `belongs_to:"cloud_provider"` - - //CloudConnection *CloudConnection `belongs_to:"cloud_connection"` - CloudConnections []CloudConnection `has_many:"cloud_connection"` - - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` -} - -// Drivers is not required by pop and may be deleted -type Drivers []Driver - -func (d *Driver) Create(tx *pop.Connection) (*validate.Errors, error) { - log.Println("Create ", d) - return tx.ValidateAndCreate(d) -} - -func (d *Driver) Update(tx *pop.Connection) (*validate.Errors, error) { - log.Println("Update ", d) - return tx.ValidateAndUpdate(d) -} - -// String is not required by pop and may be deleted -func (d Driver) String() string { - jd, _ := json.Marshal(d) - return string(jd) -} - -// String is not required by pop and may be deleted -func (d Drivers) String() string { - jd, _ := json.Marshal(d) - return string(jd) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (d *Driver) Validate(tx *pop.Connection) (*validate.Errors, error) { - var err error - //return validate.NewErrors(), nil - return nil, err -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (d *Driver) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - var err error - // return validate.Validate( - // &validators.StringIsPresent{Field: d.DriverName, Name: "DriverName"}, - // ), err - //return tx.ValidateAndCreate(d) - return nil, err -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (d *Driver) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - var err error - // return validate.NewErrors(), nil - // return tx.ValidateAndUpdate(d) - return nil, err -} diff --git a/mc_web_console_api/models/driver_test.go b/mc_web_console_api/models/driver_test.go deleted file mode 100644 index cd9ffda2..00000000 --- a/mc_web_console_api/models/driver_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_Driver() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/menu.go b/mc_web_console_api/models/menu.go deleted file mode 100644 index 2e75b55b..00000000 --- a/mc_web_console_api/models/menu.go +++ /dev/null @@ -1,81 +0,0 @@ -package models - -import ( - "encoding/json" - "time" - - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" -) - -// Menu is used by pop to map your menus database table to your go code. -type Menu struct { - ID string `json:"id" db:"id"` - Name string `json:"name" db:"name"` - //Path string `json:"path" db:"path"` - //Alias string `json:"alias" db:"alias"` - Alias string `json:"alias" db:"-"` //DB 값이 NULL로 나와서 STRING 에 할당하지 못하여 우선 주석처리, TODO : Alias 기본값을 주거나, 모델에서 NULL을 허용하는 방법을 찾으면 될듯! - Visible bool `json:"visible" db:"visible"` - Description string `json:"description" db:"description"` - Sort int `json:"sort" db:"sort"` - - // 사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함. - CategoryID string `json:"category_id" db:"category_id"` - Category *Category `belongs_to:"category"` - - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` -} - -// menu 구조 표시 -type MenuItem struct { - ID string `json:"id" db:"id"` - Name string `json:"name" db:"name"` - Alias string `json:"alias" db:"alias"` - Visible bool `json:"visible" db:"visible"` - MenuSort int `json:"menu_sort" db:"menu_sort"` - - ParentCategoryID string `json:"parent_category_id" db:"parent_category_id"` - CategoryID string `json:"category_id" db:"category_id"` - CategoryName string `json:"category_name" db:"category_name"` - - Level int `json:"level" db:"level"` - Lp string `json:"lp" db:"lp"` - CategorySort int `json:"category_sort" db:"category_sort"` - UseYn bool `json:"use_yn" db:"use_yn"` -} - -type MenuTree []MenuItem - -// String is not required by pop and may be deleted -func (m Menu) String() string { - jm, _ := json.Marshal(m) - return string(jm) -} - -// Menus is not required by pop and may be deleted -type Menus []Menu - -// String is not required by pop and may be deleted -func (m Menus) String() string { - jm, _ := json.Marshal(m) - return string(jm) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (m *Menu) Validate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (m *Menu) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (m *Menu) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} diff --git a/mc_web_console_api/models/menu_test.go b/mc_web_console_api/models/menu_test.go deleted file mode 100644 index e3589426..00000000 --- a/mc_web_console_api/models/menu_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_Menu() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/models_test.go b/mc_web_console_api/models/models_test.go deleted file mode 100644 index 29b869c9..00000000 --- a/mc_web_console_api/models/models_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package models - -import ( - "os" - "testing" - - "github.com/gobuffalo/suite/v4" -) - -type ModelSuite struct { - *suite.Model -} - -func Test_ModelSuite(t *testing.T) { - model, err := suite.NewModelWithFixtures(os.DirFS("../fixtures")) - if err != nil { - t.Fatal(err) - } - - as := &ModelSuite{ - Model: model, - } - suite.Run(t, as) -} diff --git a/mc_web_console_api/models/namespace.go b/mc_web_console_api/models/namespace.go deleted file mode 100644 index d98d991a..00000000 --- a/mc_web_console_api/models/namespace.go +++ /dev/null @@ -1,71 +0,0 @@ -package models - -import ( - "encoding/json" - "time" - - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" - "github.com/gobuffalo/validate/v3/validators" - "github.com/gofrs/uuid" -) - -// Namespace is used by pop to map your namespaces database table to your go code. -type Namespace struct { - ID string `json:"id" db:"id"` - NsName string `json:"name" db:"ns_name"` - - UserID uuid.UUID `db:"user_id"` - User *User `belongs_to:"user"` - //Description sql.NullString `json:"description" db:"description"` - Description string `json:"description" db:"description"` - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` -} - -// String is not required by pop and may be deleted -func (n Namespace) String() string { - jn, _ := json.Marshal(n) - return string(jn) -} - -// Namespaces is not required by pop and may be deleted -type Namespaces []Namespace - -// String is not required by pop and may be deleted -func (n Namespaces) String() string { - jn, _ := json.Marshal(n) - return string(jn) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (n *Namespace) Validate(tx *pop.Connection) (*validate.Errors, error) { - var err error - return validate.Validate( - &validators.StringIsPresent{Field: n.NsName, Name: "NsName"}, - ), err -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (n *Namespace) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - var err error - return validate.Validate( - &validators.StringIsPresent{Field: n.NsName, Name: "NsName"}, - ), err -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (n *Namespace) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - var err error - return validate.Validate( - &validators.StringIsPresent{Field: n.NsName, Name: "NsName"}, - ), err -} - -func (n *Namespace) Create(tx *pop.Connection) (*validate.Errors, error) { - - return tx.ValidateAndCreate(n) -} diff --git a/mc_web_console_api/models/namespace_test.go b/mc_web_console_api/models/namespace_test.go deleted file mode 100644 index 1791a9bf..00000000 --- a/mc_web_console_api/models/namespace_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_Namespace() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/region.go b/mc_web_console_api/models/region.go deleted file mode 100644 index 1e8a4fe2..00000000 --- a/mc_web_console_api/models/region.go +++ /dev/null @@ -1,77 +0,0 @@ -package models - -import ( - "encoding/json" - "log" - "time" - - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" - "github.com/gofrs/uuid" -) - -// Region is used by pop to map your regions database table to your go code. -type Region struct { - ID uuid.UUID `json:"id" db:"id"` - RegionName string `db:"region_name"` - ProviderID string `json:"provider_id" db:"provider_id"` - Provider *CloudProvider `belongs_to:"cloud_provider" fk_id:"provider_id"` - - RegionKeyValue RegionKeyvalues `has_many:"region_keyvalue"` - //CloudConnections []CloudConnection `has_many:"cloud_connection"` - - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` -} - -// String is not required by pop and may be deleted -func (r Region) String() string { - jr, _ := json.Marshal(r) - return string(jr) -} - -// Regions is not required by pop and may be deleted -type Regions []Region - -// String is not required by pop and may be deleted -func (r Regions) String() string { - jr, _ := json.Marshal(r) - return string(jr) -} - -func (r *Region) Create(tx *pop.Connection) (*validate.Errors, error) { - log.Println("region ", r) - return tx.ValidateAndCreate(r) -} - -func (r *Region) Update(tx *pop.Connection) (*validate.Errors, error) { - - return tx.ValidateAndUpdate(r) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (r *Region) Validate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (r *Region) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - var err error - // return validate.Validate( - // &validators.StringIsPresent{Field: r.RegionName, Name: "RegionName"}, - // ), err - return nil, err -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (r *Region) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - var err error - // return validate.Validate( - // &validators.StringIsPresent{Field: r.RegionName, Name: "RegionName"}, - // ), err - return nil, err - //return validate.NewErrors(), nil -} diff --git a/mc_web_console_api/models/region_group.go b/mc_web_console_api/models/region_group.go deleted file mode 100644 index 69415505..00000000 --- a/mc_web_console_api/models/region_group.go +++ /dev/null @@ -1,131 +0,0 @@ -package models - -import ( - "encoding/json" - "log" - "time" - - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" - "github.com/gofrs/uuid" -) - -// RegionGroup is used by pop to map your region_groups database table to your go code. -type RegionGroup struct { - ID uuid.UUID `json:"region_group_id" db:"id"` - - RegionGroupName string `json:"region_group_name" db:"region_group_name"` - - // 사용하는 참조 : fk 설정이 해당 테이블에 되어있어야 함. transaction으로 호출해야 relation이 적용 됨. 그냥 query로 호출하면 null. - ProviderID string `json:"provider_id" db:"provider_id"` - ProviderName string `json:"provider_name" db:"provider_name"` // raw query로 호출하여 return하기위해 추가 - //Provider *CloudProvider `json:"cloud_providers,omitempty" belongs_to:"cloud_providers"` - - RegionID uuid.UUID `json:"region_id" db:"region_id"` - RegionName string `json:"region_name" db:"region_name"` // raw query로 호출하여 return하기위해 추가 - CspRegionName string `json:"csp_region_name" db:"csp_region_name"` // raw query로 호출하여 return하기위해 추가 - //Region Region `has_one:"regions" fk_id:"id"` - //Region Region `has_one:"regions" fk_id:"region_id"` - //Region Region `has_one:"regions" fk_id:"region_groups_region_id_fkey"` - //Regions []Region `json:"regions,omitempty" belongs_to:"regions"` - - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` -} - -// String is not required by pop and may be deleted -func (r RegionGroup) String() string { - jr, _ := json.Marshal(r) - return string(jr) -} - -// RegionGroups is not required by pop and may be deleted -type RegionGroups []RegionGroup - -// String is not required by pop and may be deleted -func (r RegionGroups) String() string { - jr, _ := json.Marshal(r) - return string(jr) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (r *RegionGroup) Validate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (r *RegionGroup) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - var err error - //return validate.NewErrors(), nil - return nil, err -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (r *RegionGroup) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - var err error - //return validate.NewErrors(), nil - return nil, err -} - -func (r *RegionGroup) Create(tx *pop.Connection) (*validate.Errors, error) { - return tx.ValidateAndCreate(r) -} - -func (r *RegionGroup) Destroy(tx *pop.Connection) error { - err := tx.Destroy(r) - return err -} - -// Join문으로 Query하여 Return -func RegionGroupList(paramRegionGroup RegionGroup) ([]RegionGroup, error) { - - returnRegionGroups := []RegionGroup{} - queryString := "" - queryString += "SELECT region_groups.id, region_groups.region_group_name " - queryString += ", regions.id as region_id, regions.region_name " - queryString += ", cloud_providers.id as provider_id, cloud_providers.provider_name as provider_name " - queryString += ", region_keyvalues.value as csp_region_name " - queryString += "FROM region_groups " - queryString += "JOIN cloud_providers ON cloud_providers.id = region_groups.provider_id " - queryString += "JOIN regions ON regions.id = region_groups.region_id " - queryString += "JOIN region_keyvalues ON region_groups.region_id = region_keyvalues.region_id " - queryString += "WHERE 1 = 1 " - queryString += "AND region_keyvalues.key = 'Region' " - - log.Println("rawquery ") - log.Println("paramRegionGroup.ID ", paramRegionGroup.ID) - - whereParams := []interface{}{} - if paramRegionGroup.ID != uuid.Nil { - queryString += " AND region_groups.id = ? " - whereParams = append(whereParams, paramRegionGroup.ID.String()) - } - if paramRegionGroup.ProviderID != "" { - queryString += " AND region_groups.provider_id = ? " - whereParams = append(whereParams, paramRegionGroup.ProviderID) - } - if paramRegionGroup.RegionGroupName != "" { - queryString += " AND region_groups.region_group_name = ? " - whereParams = append(whereParams, paramRegionGroup.RegionGroupName) - } - if paramRegionGroup.RegionID != uuid.Nil { - log.Println("where ") - log.Println("paramRegionGroup.RegionID ", paramRegionGroup.RegionID) - queryString += " AND regions.id = ? " - whereParams = append(whereParams, paramRegionGroup.RegionID.String()) - } - - query := DB.RawQuery(queryString, whereParams...) - //query := DB.RawQuery(queryString) - - err := query.All(&returnRegionGroups) - //err := DB.RawQuery(queryString).All(®ionGroups) - if err != nil { - log.Println(err) - return nil, err - } - return returnRegionGroups, nil -} diff --git a/mc_web_console_api/models/region_group_test.go b/mc_web_console_api/models/region_group_test.go deleted file mode 100644 index 8db9985b..00000000 --- a/mc_web_console_api/models/region_group_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_RegionGroup() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/region_keyvalue.go b/mc_web_console_api/models/region_keyvalue.go deleted file mode 100644 index a7185d81..00000000 --- a/mc_web_console_api/models/region_keyvalue.go +++ /dev/null @@ -1,77 +0,0 @@ -package models - -import ( - "encoding/json" - "time" - - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" - "github.com/gofrs/uuid" -) - -// RegionKeyvalue is used by pop to map your region_keyvalues database table to your go code. -type RegionKeyvalue struct { - ID uuid.UUID `json:"id" db:"id"` - - RegionID uuid.UUID `json:"region_id" db:"region_id"` - Region *Region `belongs_to:"region" fk_id:"region_id"` - - Key string `json:"key" db:"key"` - Value string `json:"value" db:"value"` - - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` -} - -func (rv *RegionKeyvalue) Create(tx *pop.Connection) (*validate.Errors, error) { - - return tx.ValidateAndCreate(rv) -} - -func (rv *RegionKeyvalue) Update(tx *pop.Connection) (*validate.Errors, error) { - - return tx.ValidateAndUpdate(rv) -} - -// String is not required by pop and may be deleted -func (rv RegionKeyvalue) String() string { - jr, _ := json.Marshal(rv) - return string(jr) -} - -// RegionKeyvalues is not required by pop and may be deleted -type RegionKeyvalues []RegionKeyvalue - -// String is not required by pop and may be deleted -func (rv RegionKeyvalues) String() string { - jr, _ := json.Marshal(rv) - return string(jr) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (rv *RegionKeyvalue) Validate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (rv *RegionKeyvalue) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - var err error - // return validate.Validate( - // &validators.StringIsPresent{Field: rv.Key, Name: "Key"}, - // ), err - return nil, err - //return validate.NewErrors(), nil -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (rv *RegionKeyvalue) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - var err error - // return validate.Validate( - // &validators.StringIsPresent{Field: rv.Key, Name: "Key"}, - // ), err - return nil, err - //return validate.NewErrors(), nil -} diff --git a/mc_web_console_api/models/region_keyvalue_test.go b/mc_web_console_api/models/region_keyvalue_test.go deleted file mode 100644 index 3a9d17de..00000000 --- a/mc_web_console_api/models/region_keyvalue_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_RegionKeyvalue() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/region_test.go b/mc_web_console_api/models/region_test.go deleted file mode 100644 index 3d44369f..00000000 --- a/mc_web_console_api/models/region_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_Region() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/user.go b/mc_web_console_api/models/user.go deleted file mode 100644 index bbb48868..00000000 --- a/mc_web_console_api/models/user.go +++ /dev/null @@ -1,108 +0,0 @@ -package models - -import ( - "encoding/json" - "strings" - "time" - - "github.com/davecgh/go-spew/spew" - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" - "github.com/gobuffalo/validate/v3/validators" - "github.com/gofrs/uuid" - "github.com/pkg/errors" - "golang.org/x/crypto/bcrypt" -) - -// User is a generated model from buffalo-auth, it serves as the base for username/password authentication. -type User struct { - ID uuid.UUID `json:"id" db:"id"` - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` - Email string `json:"email" db:"email"` - PasswordHash string `json:"password_hash" db:"password_hash"` - DefaultNamespace string `json:"default_namespace" db:"default_namespace"` - // DefaultNsName string `json:"default_ns_name" db:"-"` - Namespaces Namespaces `has_many:"namespace"` - UserLevel string `json:"user_level" db:"user_level"` // 사용자 등급에 따른 namespace 관리 - Password string `json:"-" db:"-"` - PasswordConfirmation string `json:"-" db:"-"` - UserNamespaces UserNamespaces `has_many:"user_namespaces"` - UserCredentials UserCredentials `has_many:"user_credential"` - DefaultCredential string `json:"default_credential" db:"default_credential"` -} - -// Create wraps up the pattern of encrypting the password and -// running validations. Useful when writing tests. -func (u *User) Create(tx *pop.Connection) (*validate.Errors, error) { - u.Email = strings.ToLower(u.Email) - ph, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost) - if err != nil { - return validate.NewErrors(), errors.WithStack(err) - } - u.PasswordHash = string(ph) - return tx.ValidateAndCreate(u) -} - -// String is not required by pop and may be deleted -func (u User) String() string { - ju, _ := json.Marshal(u) - return string(ju) -} - -// Users is not required by pop and may be deleted -type Users []User - -// String is not required by pop and may be deleted -func (u Users) String() string { - ju, _ := json.Marshal(u) - return string(ju) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (u *User) Validate(tx *pop.Connection) (*validate.Errors, error) { - var err error - spew.Dump("=====validate running====") - - return validate.Validate( - &validators.StringIsPresent{Field: u.Email, Name: "Email"}, - &validators.StringIsPresent{Field: u.PasswordHash, Name: "PasswordHash"}, - // check to see if the email address is already taken: - &validators.FuncValidator{ - Field: u.Email, - Name: "Email", - Message: "%s is already taken", - Fn: func() bool { - var b bool - - q := tx.Where("email = ?", u.Email) - if u.ID != uuid.Nil { - q = q.Where("id != ?", u.ID) - } - b, err = q.Exists(u) - if err != nil { - return false - } - return !b - }, - }, - ), err -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (u *User) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - var err error - return validate.Validate( - &validators.StringIsPresent{Field: u.Password, Name: "Password"}, - &validators.StringsMatch{Name: "Password", Field: u.Password, Field2: u.PasswordConfirmation, Message: "Password does not match confirmation"}, - ), err -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (u *User) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - spew.Dump("=====validateupdate running====") - return validate.NewErrors(), nil -} diff --git a/mc_web_console_api/models/user_credential.go b/mc_web_console_api/models/user_credential.go deleted file mode 100644 index 4ad58603..00000000 --- a/mc_web_console_api/models/user_credential.go +++ /dev/null @@ -1,69 +0,0 @@ -package models - -import ( - "encoding/json" - "time" - - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" - "github.com/gofrs/uuid" -) - -// UserCredential is used by pop to map your user_credentials database table to your go code. -type UserCredential struct { - ID uuid.UUID `json:"id" db:"id"` - - UserID uuid.UUID `json:"user_id" db:"user_id"` - User *User `belongs_to:"user"` - - ProviderID string `json:"provider_id" db:"provider_id"` - IsDefault bool `json:"is_default" db:"is_default"` - - CredentialID uuid.UUID `json:"credential_id" db:"credential_id"` - Credential Credentials `has_many:"credentials"` - - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` -} - -func (uc *UserCredential) Create(tx *pop.Connection) (*validate.Errors, error) { - return tx.ValidateAndCreate(uc) -} - -func (uc *UserCredential) Update(tx *pop.Connection) (*validate.Errors, error) { - - return tx.ValidateAndUpdate(uc) -} - -// String is not required by pop and may be deleted -func (u UserCredential) String() string { - ju, _ := json.Marshal(u) - return string(ju) -} - -// UserCredentials is not required by pop and may be deleted -type UserCredentials []UserCredential - -// String is not required by pop and may be deleted -func (u UserCredentials) String() string { - ju, _ := json.Marshal(u) - return string(ju) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (u *UserCredential) Validate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (u *UserCredential) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (u *UserCredential) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} diff --git a/mc_web_console_api/models/user_credential_test.go b/mc_web_console_api/models/user_credential_test.go deleted file mode 100644 index 5c0226b6..00000000 --- a/mc_web_console_api/models/user_credential_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_UserCredential() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/user_namespace.go b/mc_web_console_api/models/user_namespace.go deleted file mode 100644 index ebb16447..00000000 --- a/mc_web_console_api/models/user_namespace.go +++ /dev/null @@ -1,58 +0,0 @@ -package models - -import ( - "encoding/json" - "time" - - "github.com/gobuffalo/pop/v6" - "github.com/gobuffalo/validate/v3" - "github.com/gofrs/uuid" -) - -// UserNamespace is used by pop to map your user_namespaces database table to your go code. -type UserNamespace struct { - ID uuid.UUID `json:"id" db:"id"` - NamespaceID string `db:"ns_id"` - Namespace *Namespace `belongs_to:"namespaces"` - UserID uuid.UUID `json:"user_id" db:"user_id"` - User *User `belongs_to:"users"` - CreatedAt time.Time `json:"created_at" db:"created_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` -} - -// String is not required by pop and may be deleted -func (u UserNamespace) String() string { - ju, _ := json.Marshal(u) - return string(ju) -} - -// UserNamespaces is not required by pop and may be deleted -type UserNamespaces []UserNamespace - -// String is not required by pop and may be deleted -func (u UserNamespaces) String() string { - ju, _ := json.Marshal(u) - return string(ju) -} - -// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. -// This method is not required and may be deleted. -func (u *UserNamespace) Validate(tx *pop.Connection) (*validate.Errors, error) { - return validate.Validate(), nil -} - -// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. -// This method is not required and may be deleted. -func (u *UserNamespace) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { - return validate.Validate(), nil -} - -// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. -// This method is not required and may be deleted. -func (u *UserNamespace) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { - return validate.NewErrors(), nil -} - -func (u *UserNamespace) Create(tx *pop.Connection) (*validate.Errors, error) { - return tx.ValidateAndCreate(u) -} diff --git a/mc_web_console_api/models/user_namespace_test.go b/mc_web_console_api/models/user_namespace_test.go deleted file mode 100644 index 4fa26f8a..00000000 --- a/mc_web_console_api/models/user_namespace_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_UserNamespace() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/user_test.go b/mc_web_console_api/models/user_test.go deleted file mode 100644 index ae42d9cb..00000000 --- a/mc_web_console_api/models/user_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package models - -func (ms *ModelSuite) Test_User_Create() { - count, err := ms.DB.Count("users") - ms.NoError(err) - ms.Equal(0, count) - - u := &User{ - Email: "mark@example.com", - Password: "password", - PasswordConfirmation: "password", - } - - ms.Zero(u.PasswordHash) - - verrs, err := u.Create(ms.DB) - ms.NoError(err) - ms.False(verrs.HasAny()) - ms.NotZero(u.PasswordHash) - - count, err = ms.DB.Count("users") - ms.NoError(err) - ms.Equal(1, count) -} - -func (ms *ModelSuite) Test_User_Create_ValidationErrors() { - count, err := ms.DB.Count("users") - ms.NoError(err) - ms.Equal(0, count) - - u := &User{ - Password: "password", - } - - ms.Zero(u.PasswordHash) - - verrs, err := u.Create(ms.DB) - ms.NoError(err) - ms.True(verrs.HasAny()) - - count, err = ms.DB.Count("users") - ms.NoError(err) - ms.Equal(0, count) -} - -func (ms *ModelSuite) Test_User_Create_UserExists() { - count, err := ms.DB.Count("users") - ms.NoError(err) - ms.Equal(0, count) - - u := &User{ - Email: "mark@example.com", - Password: "password", - PasswordConfirmation: "password", - } - - ms.Zero(u.PasswordHash) - - verrs, err := u.Create(ms.DB) - ms.NoError(err) - ms.False(verrs.HasAny()) - ms.NotZero(u.PasswordHash) - - count, err = ms.DB.Count("users") - ms.NoError(err) - ms.Equal(1, count) - - u = &User{ - Email: "mark@example.com", - Password: "password", - } - - verrs, err = u.Create(ms.DB) - ms.NoError(err) - ms.True(verrs.HasAny()) - - count, err = ms.DB.Count("users") - ms.NoError(err) - ms.Equal(1, count) -} diff --git a/mc_web_console_api/models/usersession.go b/mc_web_console_api/models/usersess.go similarity index 57% rename from mc_web_console_api/models/usersession.go rename to mc_web_console_api/models/usersess.go index 18a727ff..f56de90b 100644 --- a/mc_web_console_api/models/usersession.go +++ b/mc_web_console_api/models/usersess.go @@ -10,53 +10,51 @@ import ( "github.com/gofrs/uuid" ) -// Usersession is used by pop to map your usersessions database table to your go code. -type Usersession struct { - ID uuid.UUID `json:"id" db:"id"` // DB idx - PK - // Subject string `json:"subject" db:"subject"` // jwt 에서 유저에 대한 UUID +// Usersess is used by pop to map your usersesses database table to your go code. +type Usersess struct { + ID uuid.UUID `json:"id" db:"id"` + UserID string `json:"user_id" db:"user_id"` AccessToken string `json:"access_token" db:"access_token"` - ExpiresIn int `json:"expires_in" db:"expires_in"` + ExpiresIn float64 `json:"expires_in" db:"expires_in"` RefreshToken string `json:"refresh_token" db:"refresh_token"` - RefreshExpiresIn int `json:"refresh_expires_in" db:"refresh_expires_in"` + RefreshExpiresIn float64 `json:"refresh_expires_in" db:"refresh_expires_in"` CreatedAt time.Time `json:"created_at" db:"created_at"` UpdatedAt time.Time `json:"updated_at" db:"updated_at"` } // String is not required by pop and may be deleted -func (u Usersession) String() string { +func (u Usersess) String() string { ju, _ := json.Marshal(u) return string(ju) } -// Usersessions is not required by pop and may be deleted -type Usersessions []Usersession +// Usersesses is not required by pop and may be deleted +type Usersesses []Usersess // String is not required by pop and may be deleted -func (u Usersessions) String() string { +func (u Usersesses) String() string { ju, _ := json.Marshal(u) return string(ju) } // Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method. // This method is not required and may be deleted. -func (u *Usersession) Validate(tx *pop.Connection) (*validate.Errors, error) { +func (u *Usersess) Validate(tx *pop.Connection) (*validate.Errors, error) { return validate.Validate( - &validators.StringIsPresent{Field: u.ID.String(), Name: "Subject"}, + &validators.StringIsPresent{Field: u.UserID, Name: "UserID"}, &validators.StringIsPresent{Field: u.AccessToken, Name: "AccessToken"}, - &validators.IntIsPresent{Field: u.ExpiresIn, Name: "ExpiresIn"}, - &validators.IntIsPresent{Field: u.RefreshExpiresIn, Name: "RefreshExpiresIn"}, &validators.StringIsPresent{Field: u.RefreshToken, Name: "RefreshToken"}, ), nil } // ValidateCreate gets run every time you call "pop.ValidateAndCreate" method. // This method is not required and may be deleted. -func (u *Usersession) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { +func (u *Usersess) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) { return validate.NewErrors(), nil } // ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method. // This method is not required and may be deleted. -func (u *Usersession) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { +func (u *Usersess) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { return validate.NewErrors(), nil } diff --git a/mc_web_console_api/models/usersession_test.go b/mc_web_console_api/models/usersession_test.go deleted file mode 100644 index 4bdc22a8..00000000 --- a/mc_web_console_api/models/usersession_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package models - -func (ms *ModelSuite) Test_Usersession() { - ms.Fail("This test needs to be implemented!") -} diff --git a/mc_web_console_api/models/views/view_cloud_connection.go b/mc_web_console_api/models/views/view_cloud_connection.go deleted file mode 100644 index 110d5a08..00000000 --- a/mc_web_console_api/models/views/view_cloud_connection.go +++ /dev/null @@ -1,46 +0,0 @@ -/* -view 를 지원하지 않아 모델에 view관련 파일만 따로 생성 -buffalo pop g model view_cloud_connection : 테이블생성이므로 사용하지 못함. -*/ - -package views - -import ( - "encoding/json" - - "github.com/gofrs/uuid" -) - -type ViewCloudConnections []ViewCloudConnection - -// CloudConnection is used by pop to map your cloud_connections database table to your go code. -type ViewCloudConnection struct { - ID uuid.UUID `json:"id" db:"id"` - ConnectionName string `json:"connectionName" db:"connection_name"` - - ProviderID string `json:"providerId" db:"provider_id"` - - CredentialName string `json:"credentialName" db:"credential_name"` - CredentialID uuid.UUID `json:"credentialId" db:"credential_id"` - - DriverName string `json:"driverName" db:"driver_name"` - DriverID uuid.UUID `json:"driverId" db:"driver_id"` - - RegionAlias string `json:"regionAlias" db:"region_id"` - RegionName string `json:"regionName" db:"region_name"` - ZoneName string `json:"zoneName" db:"zone_name"` - RegionID uuid.UUID `json:"regionId" db:"region_id"` -} - -func (c ViewCloudConnection) String() string { - jc, _ := json.Marshal(c) - return string(jc) -} - -func (vc *ViewCloudConnection) SetRegionProvider(regionName string, providerId string) *ViewCloudConnection { - - vc.ProviderID = providerId - vc.RegionName = regionName - - return vc -} diff --git a/mc_web_console_api/models/views/view_cloud_resource.go b/mc_web_console_api/models/views/view_cloud_resource.go deleted file mode 100644 index b47a5bdc..00000000 --- a/mc_web_console_api/models/views/view_cloud_resource.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -view 를 지원하지 않아 모델에 view관련 파일만 따로 생성 -buffalo pop g model view_cloud_connection 과 resource mapping 을 조합한 쿼리 대응용 -*/ - -package views - -import ( - "encoding/json" - - "github.com/gofrs/uuid" -) - -type ViewCloudResources []ViewCloudResource - -type ViewCloudResource struct { - ID uuid.UUID `json:"id" db:"id"` - ConnectionName string `json:"connectionName" db:"connection_name"` - - ProviderID string `json:"provider_id" db:"provider_id"` - - CredentialName string `json:"credential_name" db:"credential_name"` - CredentialID uuid.UUID `json:"credential_id" db:"credential_id"` - - DriverName string `json:"driver_name" db:"driver_name"` - DriverID uuid.UUID `json:"driver_id" db:"driver_id"` - - RegionAlias string `json:"region_alias" db:"region_id"` - RegionName string `json:"region_name" db:"region_name"` - ZoneName string `json:"zone_name" db:"zone_name"` - RegionID uuid.UUID `json:"region_id" db:"region_id"` - - NamespaceID string `json:"namespace_id" db:"namespace_id"` - NamespaceName string `json:"namespace_name" db:"namespace_name"` - ResourceType string `json:"resource_type" db:"resource_type"` - ResourceID string `json:"resource_id" db:"resource_id"` - ResourceName string `json:"resource_name" db:"resource_name"` -} - -func (c ViewCloudResource) String() string { - jc, _ := json.Marshal(c) - return string(jc) -} diff --git a/mc_web_console_api/util/CommonUtil.go b/mc_web_console_api/util/CommonUtil.go deleted file mode 100644 index 988bb5a4..00000000 --- a/mc_web_console_api/util/CommonUtil.go +++ /dev/null @@ -1,214 +0,0 @@ -package util - -// 공통으로 사용할 function 정의 -import ( - // "encoding/base64" - // "fmt" - // "io" - // "io/ioutil" - "log" - // "net/http" - // "net/url" - "os" - // "reflect" - // "strconv" - "strings" - // "time" - // "bytes" - "encoding/json" - // "math" - // "io/ioutil" - - "github.com/gobuffalo/buffalo" - // "mcone/fwmodels" -) - -func GetStoredUserInfo(c buffalo.Context, userID string) map[string]string { - user := os.Getenv("LoginUser") - // store := echosession.FromContext(c) // store내 param은 모두 소문자. - // result, ok := store.Get(userID) - result := c.Session().Get(userID) - if userID == user { // setup.env에서 받아온 userID와 비교 - setAdminUser(c) - result = c.Session().Get(userID) - } else { - setNomalUser(c) - result = c.Session().Get(userID) - } - return result.(map[string]string) -} - -// 관리자 정보 set. -func setAdminUser(c buffalo.Context) { - - user := os.Getenv("LoginUser") - email := os.Getenv("LoginEmail") - pass := os.Getenv("LoginPassword") - - //store := echosession.FromContext(c) // store내 param은 모두 소문자. - obj := map[string]string{ - "userid": user, - "username": user, - "email": email, - "password": pass, - "defaultnamespage": "", - "accesstoken": "", - "refreshtoken": "", - } - c.Session().Set(user, obj) - c.Session().Save() - // store.Set(user, obj) - // store.Save() // 사용자정보를 따로 저장하지 않으므로 설정파일에 유저를 set. - log.Println("Set Admin") -} -func setNomalUser(c buffalo.Context) { - - // paramUserID := c.FormValue("userID") - // paramPass := c.FormValue("password") - - paramUserID := c.Request().FormValue("userID") - paramPass := c.Request().FormValue("password") - //store := echosession.FromContext(c) // store내 param은 모두 소문자. - - obj := map[string]string{ - "userid": paramUserID, - "username": paramUserID, - "email": paramUserID, - "password": paramPass, - "defaultnamespage": "", - "accesstoken": "", - "refreshtoken": "", - } - c.Session().Set(paramUserID, obj) - c.Session().Save() // 사용자정보를 따로 저장하지 않으므로 설정파일에 유저를 set. - log.Println("Set NomalUser") -} - -func SetStore(c buffalo.Context, storeKeyName string, storeKeyValue interface{}) { - // store := echosession.FromContext(c) // store내 param은 모두 소문자. - // store.Set(storeKeyName, storeKeyValue) - // store.Save() - - c.Session().Set(storeKeyName, storeKeyValue) - c.Session().Save() -} - -// providerName 소문자로 -func GetProviderName(providerId string) string { - return strings.ToLower(providerId) -} - -// MCIS 상태값의 앞부분만 사용. 소문자로 -func GetMcisStatus(mcisStatus string) string { - statusArr := strings.Split(mcisStatus, "-") - returnStatus := strings.ToLower(statusArr[0]) - - if returnStatus == MCIS_STATUS_RUNNING { - returnStatus = "running" - } else if returnStatus == MCIS_STATUS_INCLUDE { - returnStatus = "stop" - } else if returnStatus == MCIS_STATUS_SUSPENDED { - returnStatus = "stop" - } else if returnStatus == MCIS_STATUS_TERMINATED { - returnStatus = "terminate" - } else if returnStatus == MCIS_STATUS_PARTIAL { - returnStatus = "stop" - } else if returnStatus == MCIS_STATUS_ETC { - returnStatus = "stop" - } else { - returnStatus = "stop" - } - return returnStatus -} - -// CB-MCKS status phase : Pending, Provisioning, Provisioned, Failed -func GetMcksStatus(mcksStatus string) string { - statusArr := strings.Split(mcksStatus, "-") - returnStatus := strings.ToLower(statusArr[0]) - - if returnStatus == MCKS_STATUS_RUNNING { - returnStatus = "running" - } else if returnStatus == MCKS_STATUS_INCLUDE { - returnStatus = "stop" - } else if returnStatus == MCKS_STATUS_SUSPENDED { - returnStatus = "stop" - } else if returnStatus == MCKS_STATUS_TERMINATED { - returnStatus = "terminate" - } else if returnStatus == MCKS_STATUS_PARTIAL { - returnStatus = "stop" - } else if returnStatus == MCKS_STATUS_ETC { - returnStatus = "stop" - } else { - returnStatus = "stop" - } - return returnStatus -} - -// VM 상태를 UI에서 표현하는 방식으로 변경 -func GetVmStatus(vmStatus string) string { - returnVmStatus := strings.ToLower(vmStatus) // 소문자로 변환 - - if returnVmStatus == VM_STATUS_RUNNING { - returnVmStatus = VM_STATUS_RUNNING - // }else if vmStatus == util.VM_STATUS_RESUMING { - // vmStatusResuming++ - } else if returnVmStatus == VM_STATUS_INCLUDE { - returnVmStatus = VM_STATUS_INCLUDE - } else if returnVmStatus == VM_STATUS_SUSPENDED || returnVmStatus == VM_STATUS_STOPPED { - returnVmStatus = VM_STATUS_SUSPENDED - } else if returnVmStatus == VM_STATUS_TERMINATED { - returnVmStatus = VM_STATUS_TERMINATED - // }else if returnVmStatus == util.VM_STATUS_UNDEFINED { - // vmStatusUndefined++ - // }else if returnVmStatus == util.VM_STATUS_PARTIAL { - // vmStatusPartial++ - } else { - returnVmStatus = VM_STATUS_ETC - } - return returnVmStatus -} - -func GetVmConnectionName(vmConnectionName string) string { - return strings.ToLower(vmConnectionName) -} - -// Json형태의 obj를 map으로 형 변환 -func StructToMapByJson(obj interface{}) (newMap map[string]interface{}, err error) { - data, err := json.Marshal(obj) // Convert to a json - - if err != nil { - return - } - - err = json.Unmarshal(data, &newMap) // Convert to a map - return -} - -// func StructToMap(i interface{}) (values url.Values) { -// values = map[string] -// iVal := reflect.ValueOf(i).Elem() -// typ := iVal.Type() -// for i := 0; i < iVal.NumField(); i++ { -// f := iVal.Field(i) -// // You ca use tags here... -// // tag := typ.Field(i).Tag.Get("tagname") -// // Convert each type into a string for the url.Values string map -// var v string -// switch f.Interface().(type) { -// case int, int8, int16, int32, int64: -// v = strconv.FormatInt(f.Int(), 10) -// case uint, uint8, uint16, uint32, uint64: -// v = strconv.FormatUint(f.Uint(), 10) -// case float32: -// v = strconv.FormatFloat(f.Float(), 'f', 4, 32) -// case float64: -// v = strconv.FormatFloat(f.Float(), 'f', 4, 64) -// case []byte: -// v = string(f.Bytes()) -// case string: -// v = f.String() -// } -// values.Set(typ.Field(i).Name, v) -// } -// return -// } diff --git a/mc_web_console_api/util/Const.go b/mc_web_console_api/util/Const.go deleted file mode 100644 index 15ca0888..00000000 --- a/mc_web_console_api/util/Const.go +++ /dev/null @@ -1,149 +0,0 @@ -package util - -import ( - "os" - "strconv" -) - -// 상수 정의 - -// var CloudConnectionUrl = os.Getenv("SPIDER_URL") -// var TumbleUrl = os.Getenv("TUMBLE_URL") -// var CloudConnectionUrl = os.Getenv("SPIDER_URL") -// var NameSpaceUrl = os.Getenv("TUMBLE_URL") - -func init() { - MCIAM_USE, _ = strconv.ParseBool(os.Getenv("MCIAM_USE")) -} - -var SPIDER = os.Getenv("SPIDER_URL") -var TUMBLEBUG = os.Getenv("TUMBLE_URL") -var DRAGONFLY = os.Getenv("DRAGONFLY_URL") -var LADYBUG = os.Getenv("LADYBUG_URL") -var MCKS = os.Getenv("MCKS_URL") - -var MCIAMMANAGER = os.Getenv("IAMMANAGER_URL") -var MCIAM_USE = false // MC-IAM-MANAGER 사용여부, init 에서 재정의 - -var HTTP_CALL_SUCCESS = 200 -var HTTP_POST_SUCCESS = 201 - -var PROVIDER_AWS = "aws" -var PROVIDER_AZURE = "azure" -var PROVIDER_ALIBABA = "alibaba" -var PROVIDER_GCP = "gcp" -var PROVIDER_CLOUDIT = "cloudit" -var PROVIDER_OPENSTACK = "openstack" -var PROVIDER_MOCK = "mock" - -// MCIS 의 life cycle // socket통신에서 사용 -var MCIS_LIFECYCLE_CREATE = "create" -var MCIS_LIFECYCLE_SUSPEND = "suspend" -var MCIS_LIFECYCLE_RESUME = "resume" -var MCIS_LIFECYCLE_TERMINATE = "terminate" -var MCIS_LIFECYCLE_DELETE = "delete" - -// MCIS의 상태(소문자). (기타 상태는 UNDEFINED + ETC) -var MCIS_STATUS_RUNNING = "running" -var MCIS_STATUS_INCLUDE = "include" -var MCIS_STATUS_SUSPENDED = "suspended" -var MCIS_STATUS_TERMINATED = "terminated" -var MCIS_STATUS_PARTIAL = "partial" -var MCIS_STATUS_ETC = "etc" - -// MCKA의 상태(소문자) -var MCKS_STATUS_RUNNING = "running" -var MCKS_STATUS_INCLUDE = "include" -var MCKS_STATUS_SUSPENDED = "suspended" -var MCKS_STATUS_TERMINATED = "terminated" -var MCKS_STATUS_PARTIAL = "partial" -var MCKS_STATUS_ETC = "etc" - -var MONITORING_POLICY_STATUS_REG = "regist" -var MONITORING_POLICY_STATUS_FAIL = "fail" -var MONITORING_THRESHOLD_REG = "regist" - -var STATUS_ARRAY = []string{"running", "stopped", "terminated"} - -// VM 의 life cycle // socket통신에서 사용 -var VM_LIFECYCLE_CREATE = "create" -var VM_LIFECYCLE_SUSPEND = "suspend" -var VM_LIFECYCLE_RESUME = "resume" -var VM_LIFECYCLE_TERMINATE = "terminate" -var VM_LIFECYCLE_DELETE = "delete" -var VM_LIFECYCLE_REBOOT = "reboot" - -// VM의 상태(소문자). (기타 상태는 UNDEFINED + ETC) -var VM_STATUS_RUNNING = "running" - -// var VM_STATUS_RESUMING = "Resuming" -var VM_STATUS_INCLUDE = "include" - -var VM_STATUS_SUSPENDED = "suspended" -var VM_STATUS_STOPPED = "stopped" -var VM_STATUS_TERMINATED = "terminated" - -// var VM_STATUS_UNDEFINED = "statusUndefined" -// var VM_STATUS_PARTIAL = "partial" -var VM_STATUS_ETC = "etc" - -var VM_STATUS_ARRAY = []string{"running", "suspended", "terminated", "etc"} - -// ///// Store 저장 용 Const -var STORE_NAMESPACELIST = "namespacelist" -var STORE_CLOUDOSLIST = "cloudoslist" -var STORE_REGIONLIST = "regionlist" -var STORE_CREDENTIALLIST = "credentiallist" -var STORE_DRIVERLIST = "driverlist" -var STORE_CLOUDCONNECTIONCONFIGLIST = "cloudconnectionconfiglist" - -var STORE_DEFAULT_NAMESPACENAME = "defaultnamespacename" -var STORE_DEFAULT_NAMESPACEID = "defaultnamespaceid" - -// websocket으로 전달하는 task의 종류 -var TASK_TYPE_MCIS = "mcis" -var TASK_TYPE_VM = "vm" -var TASK_TYPE_MCKS = "mcks" -var TASK_TYPE_DRIVER = "driver" -var TASK_TYPE_CREDENTIAL = "credential" -var TASK_TYPE_REGION = "region" -var TASK_TYPE_CONNECTION = "connection" -var TASK_TYPE_VNET = "vnet" -var TASK_TYPE_SECURITYGROUP = "securitygroup" -var TASK_TYPE_VMIMAGE = "vmimage" -var TASK_TYPE_VMSPEC = "vmspec" -var TASK_TYPE_MONITORING_POLICY = "monitoringpolicy" -var TASK_TYPE_MONITORINGTHRESHOLD_EVENTHANDLER = "monitoringthresholdeventhandler" -var TASK_TYPE_NLB = "nlb" -var TASK_TYPE_PMKS = "pmks" -var TASK_TYPE_DISK = "disk" - -// 요청상태 : socket 으로 전달하는 요청 상태 -var TASK_STATUS_REQUEST = "requested" -var TASK_STATUS_PROCESS = "processing" -var TASK_STATUS_FAIL = "failed" -var TASK_STATUS_COMPLETE = "completed" - -var VMSPEC_LIFECYCLE_CREATE = "create" - -var MCKS_LIFECYCLE_CREATE = "create" -var MCKS_LIFECYCLE_SUSPEND = "suspend" -var MCKS_LIFECYCLE_RESUME = "resume" -var MCKS_LIFECYCLE_TERMINATE = "terminate" -var MCKS_LIFECYCLE_DELETE = "delete" - -var NLB_LIFECYCLE_CREATE = "create" -var NLB_LIFECYCLE_DELETE = "delete" - -var PMKS_LIFECYCLE_CREATE = "create" -var PMKS_LIFECYCLE_SUSPEND = "suspend" -var PMKS_LIFECYCLE_RESUME = "resume" -var PMKS_LIFECYCLE_TERMINATE = "terminate" -var PMKS_LIFECYCLE_DELETE = "delete" - -var PMKS_CLUSTER_UPDATE = "update" - -var DISK_LIFECYCLE_CREATE = "create" -var DISK_LIFECYCLE_ATTACHED = "attached" -var DISK_LIFECYCLE_DETACHED = "detached" -var DISK_LIFECYCLE_DELETE = "delete" diff --git a/mc_web_console_api/util/HttpUtil.go b/mc_web_console_api/util/HttpUtil.go deleted file mode 100644 index d94eb587..00000000 --- a/mc_web_console_api/util/HttpUtil.go +++ /dev/null @@ -1,264 +0,0 @@ -package util - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "fmt" - "io/ioutil" - "log" - "math" - "mime/multipart" - "net/http" - "net/http/httputil" - "os" - "strconv" - "strings" -) - -// "reflect" -// "io" - -// "net/url" - -// "time" - -// "io/ioutil" -// echosession "github.com/go-session/echo-session" -// "github.com/labstack/echo" -// "mcone/fwmodels" - -type KeepZero float64 - -func (f KeepZero) MarshalJSON() ([]byte, error) { - if float64(f) == float64(int(f)) { - return []byte(strconv.FormatFloat(float64(f), 'f', 1, 32)), nil - } - return []byte(strconv.FormatFloat(float64(f), 'f', -1, 32)), nil -} - -type myFloat64 float64 - -func (mf myFloat64) MarshalJSON() ([]byte, error) { - const ε = 1e-12 - v := float64(mf) - w, f := math.Modf(v) - if f < ε { - return []byte(fmt.Sprintf(`%v.0`, math.Trunc(w))), nil - } - return json.Marshal(v) -} - -func AuthenticationHandler() string { - apiusername := os.Getenv("API_USERNAME") - apipassword := os.Getenv("API_PASSWORD") - apiUserInfo := apiusername + ":" + apipassword - encA := base64.StdEncoding.EncodeToString([]byte(apiUserInfo)) - fmt.Println("Basic " + encA) - return "Basic " + encA -} - -// http 호출 -func CommonHttp(url string, json []byte, httpMethod string) (*http.Response, error) { - - authInfo := AuthenticationHandler() - - log.Println("CommonHttp "+httpMethod+", ", url) - // log.Println("authInfo ", authInfo) - client := &http.Client{} - req, err1 := http.NewRequest(httpMethod, url, bytes.NewBuffer(json)) - if err1 != nil { - panic(err1) - } - - // set the request header Content-Type for json - req.Header.Set("Content-Type", "application/json; charset=utf-8") - // req.Header.Set("Content-Type", "application/json") - - req.Header.Add("Authorization", authInfo) - - requestDump, err := httputil.DumpRequest(req, true) - if err != nil { - log.Println(err) - } - log.Println(string(requestDump)) - resp, err := client.Do(req) // err 자체는 nil 이고 resp 내에 statusCode가 500임... - - return resp, err -} - -// originalUrl 은 API의 전체 경로 -// parammapper 의 Key는 replace할 모든 text -// ex1) path인 경우 {abc} -// ex2) path인 경우 :abc -func MappingUrlParameter(originalUrl string, paramMapper map[string]string) string { - returnUrl := originalUrl - log.Println("originalUrl\t= ", originalUrl) - if paramMapper != nil { - for key, replaceValue := range paramMapper { - returnUrl = strings.Replace(returnUrl, key, replaceValue, -1) - // fmt.Println("Key:", key, "=>", "Element:", replaceValue+":"+returnUrl) - } - } - log.Println("returnUrl\t= ", returnUrl) - return returnUrl -} - -// Json 형태의 bytes.Buffer 면 그대로 사용 -func CommonHttpBytes(url string, jsonBytesBuffer *bytes.Buffer, httpMethod string) (*http.Response, error) { - authInfo := AuthenticationHandler() - - // payload := strings.NewReader(`{ - // "CredentialName": "test-gcp-webtool21", - // "ProviderName": "GCP", - // "KeyValueInfoList": [ - // { - // "Key": "project_id", - // "Value": "megazone-for-yhnoh" - // }, - // { - // "Key": "client_email", - // "Value": "yhnoh-704@megazone-for-yhnoh.iam.gserviceaccount.com" - // }, - // { - // "Key": "private_key", - // "Value": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDcbgpvhNXoYvq+\nVKtfcH/s0NL9Shmn8aSMd0eXGMMQ1b/VQ2HGUMxSgoOa0fHXOzIhpEKHtnIdv1uf\nad+AGmkQOUTRvmmcBUuh3JFuZpSoGH1InBZUowvzqaJvIrhPkAzuu+0el9kHdqRu\nwgCZaZXar0jXji3CvdTeAKtKnC1UgxTUrPAsfTiRh2ZkXDsIsrnA8kL8oIqEGm/g\ncx681KoRpbVb3LPt2BMXwZkEt9x1x+ExEBMjfrr6PEMkvzDlMrY8TcGSNXCHUAmN\no5o8Rsy88Rphd6viOxNuiQA7MacKBB3cR4fl12tfEzxbQUtGPFJB4doKE7AVb+EP\nCD3M6S1XAgMBAAECggEAUjBli7dH2uItBBKl42wbBr3GLdMXRdt/szA2bUw6T2ij\nom0BY+R0ir9HOs7VEZ9szcZlWBza5+SV0Ra00xsF2ZrA4kPRNO90h+GqCDQPca3P\n6ObqHJy+tBeoDTAw8NmROOKxQxrzPSkrnnCPsKQB0AxTaKwGu/n0COLO+37IGB4m\noOGtGIG+hPfLWGUegtZ9WM9m+widM+WXCeWmEORZ+k5hxE82XFH8ayWgj22FG+ys\n+kI8FjdZX4DNmSzrAl6v/KKlvPgqsEksSllRf/409XPGWSO/NK1th+3wsk69NS3Q\nbQzyZyWD99ubA50I5YAhpimmPFS3NGwOdiPKRa4moQKBgQD6CbsZAfK+Lf9nf14l\nrrKhPZTqNjOFpB+yPFgOhWgPVS+BVEXqcOOJ5H21hla6hYEJvhPAZcWGh9uq2xtX\nVieyuy3DhHXXHy3xaTnimTcxMR5KrD/4R/dB2S0qPmMdWDOZKYRN5PYA4PECtt+b\nURltqmC/spQxZ2BWVVlKfA+oGwKBgQDhr5PIulSZE7gZi1oefMV32vBlHJZrSUzi\n8TRVKoixYQ/0DcffSKdWpoaFcmoi+JjiBT5iKFYvzqwOEB6WuiVY9OHHqh6PeG+S\nQnE4UI1lyP9mmX8FWwXmuz8qghJjRKlHMW2engbOC6cTudYt0JWDWOeu4CmX+pZy\ncGjBLnubdQKBgFJXDgQoPhYe87LToN9r7mtm6jlO7BygdceuU5lEmYYjGWfPps6T\nqnrogfVbbggymtHohHyhhzDMYKydRx21w5D6TxHJ9zyGigysCGH07tYGROF2ZAKR\nQH2w1UzKCr3JJATWRTmZouGbMgMg0fZF+MfCieXXGzJBxtnndWYwAL/tAoGAKIyC\nUftgfcx0NGq8O2QRmrJEpPYY9JfL766Ex5SH0M7urdvYAH8uSbxLyShAd54Q4fMt\nPTegHKDWewRcappxYWVGN7iSGxb5fN7hNswKS7JsaQPFNbIgAk+8TqfmI93PSFJS\nLsCX2mdvknS+Tab/ZgUQQ3RVJNBKPa+CssrmPI0CgYEAv/Vi7HFjv0ozCaBR7cVm\n+n4J2L7nVw44tYuzhIYM1b82FU1OywGl7101m2TliJKV4nJEUaOvW4zUp1YEx+Uj\n2FkO/v2ZRRAqbebovw7+fium+Xjcipw7zjKTKJ9mAs87A3JABahvyUeGyZSw6xyX\no4fl0OvwIH9WjjayOEeriDk=\n-----END PRIVATE KEY-----\n" - // } - // ] - // }`) - log.Println("CommonHttp "+httpMethod+", ", url) - //[]byte(creds.PrivateKey) - // log.Println("authInfo ", authInfo) - client := &http.Client{} - req, err1 := http.NewRequest(httpMethod, url, jsonBytesBuffer) - // ppp := make([]byte, len(payload)) - // req, err1 := http.NewRequest(httpMethod, url, payload) - if err1 != nil { - panic(err1) - } - - // url = "http://54.248.3.145:1323/tumblebug/ns/ns-01/resources/vNet" - - // set the request header Content-Type for json - req.Header.Set("Content-Type", "application/json; charset=utf-8") - // req.Header.Set("Content-Type", "application/json") - - req.Header.Add("Authorization", authInfo) - - // getBody := req.GetBody - // copyBody, err := getBody() - // if err == nil { - // log.Println("------stert"); - // log.Println(copyBody); - // log.Println("------end"); - // } - requestDump, err := httputil.DumpRequest(req, true) - if err != nil { - fmt.Println(err) - } - fmt.Println(string(requestDump)) - - resp, err := client.Do(req) // err 자체는 nil 이고 resp 내에 statusCode가 500임... - - return resp, err -} - -// parameter 없이 호출하는 경우 사용.받은대로 return하면 호출하는 method에서 가공하여 사용 -func CommonHttpWithoutParam(url string, httpMethod string) (*http.Response, error) { - authInfo := AuthenticationHandler() - log.Println("************ Authinfo: ", authInfo) - log.Println("CommonHttpWithoutParam "+httpMethod+", ", url) - fmt.Println("CommonHttpWithoutParam "+httpMethod+", ", url) - // log.Println("authInfo ", authInfo) - client := &http.Client{} - req, err := http.NewRequest(httpMethod, url, nil) - if err != nil { - fmt.Println("CommonHttpWithoutParam error") - fmt.Println(err) - panic(err) - } - - // set the request header Content-Type for json - // req.Header.Set("Content-Type", "application/json; charset=utf-8") // 사용에 주의할 것. - req.Header.Add("Authorization", authInfo) - // resp, err := client.Do(req) - return client.Do(req) -} - -// Put/Post 등을 formData 형태로 호출할 때 -// https://minwook-shin.github.io/go-decode-encode-url-values-form/ 참조할 것 -// func CommonHttpFormData(targetUrl string, formParam url.Values, httpMethod string) (*http.Response, error) { -// func CommonHttpFormData(targetUrl string, formParam map[string]string, httpMethod string) (*http.Response, error) { -func CommonHttpFormData(targetUrl string, formParam map[string]interface{}, httpMethod string) (*http.Response, error) { - //m := structs.Map(s) - authInfo := AuthenticationHandler() - - payload := &bytes.Buffer{} - writer := multipart.NewWriter(payload) - - log.Println(formParam) - - // writer.WriteField 는 int 등으로는 전송이 안됨.... string으로 변환 후 전송 - for key, val := range formParam { - _ = writer.WriteField(key, fmt.Sprintf("%v", val)) - } - err := writer.Close() - - client := &http.Client{} - req, _ := http.NewRequest(httpMethod, targetUrl, payload) - - req.Header.Set("Content-Type", writer.FormDataContentType()) - req.Header.Add("Authorization", authInfo) - - resp, err := client.Do(req) - return resp, err -} - -// return message 확인용 -func DisplayResponse(resp *http.Response) { - fmt.Println("*****DisplayResponse begin****") - if resp == nil { - log.Println(" response is nil ") - } else { - // resultMessage, err1 := ioutil.ReadAll(resp.Message) - // if err1 != nil { - // str := string(resultMessage) - // println("nil ", str) - // println("err1 ", err1) - // } - // fmt.Println(string(resultMessage)) - // log.Println(" 11111111111111111111111111111 ") - - fmt.Println(resp.StatusCode) - log.Println(" 22222222222222222222222222 ") - - fmt.Println(string(resp.Status)) - log.Println(" 3333333333333333333 ") - // data, err := ioutil.ReadAll(resp.Body) - // if err != nil { - // panic(err) - // } - // fmt.Printf("%s\n", string(data)) - - // resultStatus := resp.StatusCode - // fmt.Println("resultStatus ", resultStatus) - // // fmt.Println("body ", resp.Body) - resultBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - str := string(resultBody) - println("nil ", str) - println("err ", err) - } - fmt.Println(string(resultBody)) - - var target interface{} - body, _ := ioutil.ReadAll(resp.Body) - json.Unmarshal(body, &target) - fmt.Println(fmt.Println(target)) - // // json.NewDecoder(respBody).Decode(&stringMap) - // pbytes, _ := json.Marshal(resultBody) - // fmt.Println(string(pbytes)) - - fmt.Println("*****DisplayResponse end****") - } -} diff --git a/mc_web_console_api/util/ValidateUtil.go b/mc_web_console_api/util/ValidateUtil.go deleted file mode 100644 index 9f89cfab..00000000 --- a/mc_web_console_api/util/ValidateUtil.go +++ /dev/null @@ -1,26 +0,0 @@ -package util - -import ( - "fmt" - // "gopkg.in/go-playground/validator.v9" -) - -// var validate *validator.Validate - -type ValidObject struct { - Name string `validate:"required"` -} - -// Vadidation check -func ValidateString(param string) error { - vObj := ValidObject{} - vObj.Name = param - - fmt.Println("param valid ", param) - // validate = validator.New() - // err := validate.Struct(vObj) - // if err != nil { - // return err - // } - return nil -} diff --git a/mc_web_console_front/actions/actions_test.go b/mc_web_console_front/actions/actions_test.go deleted file mode 100644 index 0a480c4a..00000000 --- a/mc_web_console_front/actions/actions_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package actions - -import ( - "os" - "testing" - - "github.com/gobuffalo/suite/v4" -) - -type ActionSuite struct { - *suite.Action -} - -func Test_ActionSuite(t *testing.T) { - action, err := suite.NewActionWithFixtures(App(), os.DirFS("../fixtures")) - if err != nil { - t.Fatal(err) - } - - as := &ActionSuite{ - Action: action, - } - suite.Run(t, as) -} diff --git a/mc_web_console_front/actions/apicaller.go b/mc_web_console_front/actions/apicaller.go index bd0a03bd..c1ab7618 100644 --- a/mc_web_console_front/actions/apicaller.go +++ b/mc_web_console_front/actions/apicaller.go @@ -10,24 +10,30 @@ import ( ) var proxy *httputil.ReverseProxy +var ApiBaseHost *url.URL func init() { apiAddr := os.Getenv("API_ADDR") apiPort := os.Getenv("API_PORT") - apiBaseHost, err := url.Parse("http://" + apiAddr + ":" + apiPort) + var err error + ApiBaseHost, err = url.Parse("http://" + apiAddr + ":" + apiPort) if err != nil { panic(err) } - log.Println("APIbaseHost", apiBaseHost) - proxy = httputil.NewSingleHostReverseProxy(apiBaseHost) + log.Println("APIbaseHost", ApiBaseHost) + proxy = httputil.NewSingleHostReverseProxy(ApiBaseHost) } func ApiCaller(c buffalo.Context) error { - log.Println("#### IN ApiCaller") + log.Println("#### IN Api Proxy") log.Println("Method", c.Request().Method) log.Println("RequestURI", c.Request().RequestURI) - c.Request().Header.Add("Authorization", c.Session().Get("Authorization").(string)) - proxy.ServeHTTP(c.Response(), c.Request()) + if c.Request().RequestURI == "/api/auth/login" { + return SessionInitializer(c) + } else { + c.Request().Header.Add("Authorization", c.Session().Get("Authorization").(string)) + proxy.ServeHTTP(c.Response(), c.Request()) + } log.Println("#### ServeHTTP Success") return nil } diff --git a/mc_web_console_front/actions/app.go b/mc_web_console_front/actions/app.go index eba20886..de6e849e 100644 --- a/mc_web_console_front/actions/app.go +++ b/mc_web_console_front/actions/app.go @@ -1,11 +1,11 @@ package actions import ( + "log" "net/http" "os" - "strconv" - "mc_web_console_front/locales" + "mc_web_console_front/middleware" "mc_web_console_front/public" "github.com/gobuffalo/buffalo" @@ -49,59 +49,25 @@ func App() *buffalo.App { app.Use(forceSSL()) app.Use(paramlogger.ParameterLogger) - app.Use(csrf.New) // 프론트에서 CSRF 설정이 되어 있음! 백에서 처리할 시 아래 주석 할 것. - app.Use(translations()) + app.Use(csrf.New) - mciamUse, _ := strconv.ParseBool(os.Getenv("MCIAM_USE")) app.ANY("/alive", alive) + auth := app.Group("/auth") + auth.GET("/login", UserLoginHandler) + auth.GET("/logout", UserLogoutHandler) + auth.GET("/unauthorized", UserUnauthorizedHandler) - // pages app.Redirect(http.StatusSeeOther, "/", RootPathForRedirectString) //home redirect to dash pages := app.Group("/webconsole") - if mciamUse { - pages.Use(McIamAuthMiddleware) - } + pages.Use(session("")) + pages.ANY("/alive", alive) pages.GET("/{depth1}/{depth2}/{depth3}", PageController) - // mciamAuth pages - if mciamUse { - auth := app.Group("/auth") - auth.GET("/login", UserLoginHandler) - auth.POST("/login", UserLoginHandler) - auth.GET("/logout", UserLogoutHandler) - auth.GET("/register", UserRegisterpageHandler) - } - - // API 호출 Proxy to backend API buffalo apiPath := "/api" api := app.Group(apiPath) - api.ANY("/{path:.+}", ApiCaller) - - //////////////// debug section start //////////////// - // debug 이므로 별도 라우팅 처리... build에 포함되지 않도록 처리 할 것.. - if ENV == "development" { - debug := app.Group("/debug") - // common debug - debug.GET("/", DEBUGRouteHandler) - - // flowchart debug - // debug.GET("/flow", DEBUGWorkflowHandler) - - // tabler debug - // debug.GET("/tabler", DEBUGTablerMainHandler) - // debug.GET("/tabler/{target}", DEBUGTablerHandler) - - // tabulator debug - debug.GET("/tabulator", DEBUGTabulatorHandler) - - // page sample - // debug.GET("/sample", DEBUGSamplePageHandler) - // debug call Test - debug.GET("/apicall", DEBUGApicallPageController) - } - //////////////// debug section end //////////////// + api.ANY("/{path:.+}", ApiCaller) app.ServeFiles("/", http.FS(public.FS())) } @@ -109,18 +75,6 @@ func App() *buffalo.App { return app } -// translations will load locale files, set up the translator `actions.T`, -// and will return a middleware to use to load the correct locale for each -// request. -// for more information: https://gobuffalo.io/en/docs/localization -func translations() buffalo.MiddlewareFunc { - var err error - if T, err = i18n.New(locales.FS(), "en-US"); err != nil { - app.Stop(err) - } - return T.Middleware() -} - // forceSSL will return a middleware that will redirect an incoming request // if it is not HTTPS. "http://example.com" => "https://example.com". // This middleware does **not** enable SSL. for your application. To do that @@ -139,3 +93,16 @@ func alive(c buffalo.Context) error { "method": c.Request().Method, })) } + +func session(role string) buffalo.MiddlewareFunc { + if MCIAM_USE { + return middleware.Middleware(role) + } else { + return func(next buffalo.Handler) buffalo.Handler { + return func(c buffalo.Context) error { + log.Println("NO SESSION MIDDLEWARE") + return next(c) + } + } + } +} diff --git a/mc_web_console_front/actions/auth.go b/mc_web_console_front/actions/auth.go new file mode 100644 index 00000000..2b99f73e --- /dev/null +++ b/mc_web_console_front/actions/auth.go @@ -0,0 +1,51 @@ +package actions + +import ( + "encoding/json" + "fmt" + "io" + "log" + "net/http" + + "github.com/gobuffalo/buffalo" +) + +func SessionInitializer(c buffalo.Context) error { + fmt.Println("SessionInitializer", ApiBaseHost.String()+c.Request().RequestURI) + req, err := http.NewRequest(c.Request().Method, ApiBaseHost.String()+c.Request().RequestURI, c.Request().Body) + if err != nil { + return c.Render(http.StatusInternalServerError, defaultRender.JSON(map[string]interface{}{"error": err.Error()})) + } + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return c.Render(http.StatusInternalServerError, defaultRender.JSON(map[string]interface{}{"error": err.Error()})) + } + defer resp.Body.Close() + + respBody, ioerr := io.ReadAll(resp.Body) + if ioerr != nil { + log.Println("Error CommonHttp reading response:", ioerr) + } + var data map[string]interface{} + jsonerr := json.Unmarshal(respBody, &data) + if jsonerr != nil { + return c.Render(http.StatusInternalServerError, defaultRender.JSON(map[string]interface{}{"error": jsonerr.Error()})) + } + accessToken := data["responseData"].(map[string]interface{})["access_token"] + c.Session().Set("Authorization", accessToken) + return c.Render(http.StatusOK, defaultRender.JSON(map[string]interface{}{"status": "ok"})) +} + +func UserLoginHandler(c buffalo.Context) error { + return c.Render(http.StatusOK, defaultRender.HTML("pages/auth/login.html")) +} + +func UserUnauthorizedHandler(c buffalo.Context) error { + return c.Render(http.StatusOK, defaultRender.HTML("pages/auth/unauthorized.html")) +} + +func UserLogoutHandler(c buffalo.Context) error { + c.Session().Clear() + return c.Render(http.StatusOK, defaultRender.HTML("pages/auth/logout.html")) +} diff --git a/mc_web_console_front/actions/env.go b/mc_web_console_front/actions/env.go new file mode 100644 index 00000000..2a81aced --- /dev/null +++ b/mc_web_console_front/actions/env.go @@ -0,0 +1,12 @@ +package actions + +import ( + "os" + "strconv" +) + +func init() { + MCIAM_USE, _ = strconv.ParseBool(os.Getenv("MCIAM_USE")) +} + +var MCIAM_USE = false // MC-IAM-MANAGER 사용여부, init 에서 재정의 diff --git a/mc_web_console_front/actions/mciamauth.go b/mc_web_console_front/actions/mciamauth.go deleted file mode 100644 index 6fc55177..00000000 --- a/mc_web_console_front/actions/mciamauth.go +++ /dev/null @@ -1,70 +0,0 @@ -package actions - -import ( - "net/http" - - "github.com/gobuffalo/buffalo" - "github.com/mitchellh/mapstructure" - - mcmodels "mc_web_console_common_models" -) - -func UserLoginHandler(c buffalo.Context) error { - if c.Request().Method == "POST" { - - commonRequest := &CommonRequest{} - if err := c.Bind(commonRequest); err != nil { - return c.Render(http.StatusBadRequest, - defaultRender.JSON(CommonResponseProvider(http.StatusBadRequest, err.Error()))) - } - - commonResponse, err := CommonCallerWithoutToken(http.MethodPost, APILoginPath, commonRequest) - if err != nil { - return c.Render(commonResponse.Status.StatusCode, - defaultRender.JSON(CommonResponseProvider(commonResponse.Status.StatusCode, err.Error()))) - } - - accessTokenResponse := &mcmodels.AccessTokenResponse{} - if err := mapstructure.Decode(commonResponse.ResponseData, accessTokenResponse); err != nil { - return c.Render(http.StatusInternalServerError, - defaultRender.JSON(CommonResponseProvider(http.StatusInternalServerError, err.Error()))) - } - - c.Session().Set("Authorization", accessTokenResponse.AccessToken) - - return c.Render(http.StatusOK, - defaultRender.JSON(CommonResponseProvider(http.StatusOK, map[string]string{ - "redirect": RootPathForRedirectString, - }))) - } - - accessToken := c.Session().Get("Authorization") - if accessToken != nil { - c.Flash().Add("success", "You are already logged in.") - return c.Redirect(http.StatusSeeOther, - "webconsoleDepth1Depth2Depth3Path()", - RootPathForRedirect, - ) - } - - return c.Render(http.StatusOK, defaultRender.HTML("pages/auth/login.html")) -} - -func UserLogoutHandler(c buffalo.Context) error { - commonResponse, err := CommonCaller(http.MethodPost, APILogoutPath, &CommonRequest{}, c) - if err != nil { - return c.Render(commonResponse.Status.StatusCode, - defaultRender.JSON(CommonResponseProvider(commonResponse.Status.StatusCode, err.Error()))) - } - if commonResponse.Status.StatusCode != 200 { - return c.Render(commonResponse.Status.StatusCode, - defaultRender.JSON(CommonResponseProvider(commonResponse.Status.StatusCode, commonResponse.ResponseData))) - } - c.Session().Clear() - c.Flash().Add("success", "Logout") - return c.Redirect(http.StatusSeeOther, "authLoginPath()") -} - -func UserRegisterpageHandler(c buffalo.Context) error { - return c.Render(http.StatusOK, defaultRender.HTML("pages/auth/login.html")) -} diff --git a/mc_web_console_front/actions/mciammiddleware.go b/mc_web_console_front/actions/mciammiddleware.go deleted file mode 100644 index d9d7a95f..00000000 --- a/mc_web_console_front/actions/mciammiddleware.go +++ /dev/null @@ -1,68 +0,0 @@ -package actions - -import ( - "fmt" - "net/http" - "reflect" - "time" - - "github.com/gobuffalo/buffalo" - "github.com/golang-jwt/jwt/v4" -) - -func McIamAuthMiddleware(next buffalo.Handler) buffalo.Handler { - return func(c buffalo.Context) error { - accessToken := c.Session().Get("Authorization") - if accessToken == nil { - c.Flash().Add("danger", "No session") - c.Session().Clear() - return c.Redirect(http.StatusSeeOther, "authLoginPath()") - } - jwtDecode, _ := jwtDecode(accessToken.(string)) - if reflect.TypeOf(jwtDecode["exp"]) == reflect.TypeOf(nil) { - c.Session().Clear() - return c.Redirect(http.StatusSeeOther, "authLoginPath()") - } - t := time.Unix(int64(jwtDecode["exp"].(float64)), 0) - if t.Before(time.Now()) { - fmt.Println(time.Since(t)) - c.Session().Clear() - c.Flash().Add("danger", "Session Expired") - return c.Redirect(http.StatusSeeOther, "authLoginPath()") - } - - c.Set("name", jwtDecode["name"]) - - return next(c) - } -} - -// func getUserInfo(c buffalo.Context) (mcmodels.UserInfo, string, error) { -// userinfo := &mcmodels.UserInfo{} - -// status, commonRes, err := CommonAPIGet(APIUserInfoPath, c) -// if err != nil { -// msg := status.Status + " Error Get Userinfo from MC-IAM-MANAGER" -// return *userinfo, msg, err -// } -// if status.StatusCode != 200 { -// msg := status.Status + " Error Get Userinfo from MC-IAM-MANAGER" -// return *userinfo, msg, errors.New(msg) -// } - -// if decodeerr := mapstructure.Decode(commonRes.ResponseData, userinfo); decodeerr != nil { -// msg := "Authentication Info Error" -// return *userinfo, msg, decodeerr -// } - -// return *userinfo, "", nil -// } - -func jwtDecode(jwtToken string) (jwt.MapClaims, error) { - claims := jwt.MapClaims{} - _, err := jwt.ParseWithClaims(jwtToken, claims, func(token *jwt.Token) (interface{}, error) { return "", nil }) - if err != nil { - return claims, err - } - return claims, nil -} diff --git a/mc_web_console_front/actions/pageController.go b/mc_web_console_front/actions/pageController.go index 3a598051..0430a92a 100644 --- a/mc_web_console_front/actions/pageController.go +++ b/mc_web_console_front/actions/pageController.go @@ -1,7 +1,7 @@ package actions import ( - "fmt" + "log" "mc_web_console_front/templates" "net/http" "strings" @@ -9,16 +9,21 @@ import ( "github.com/gobuffalo/buffalo" ) +// 화면 제어 +// path에 맞게 호출을 해야 render 와 breadCrumb 가 동작함. +// ex) /webconsole/configuration/workspace/manage" 롤 경로를 주고 +// +// templates/pages 아래에 /configuration/workspace/manage 에 html 파일을 만들면 됨. func PageController(c buffalo.Context) error { - depth1 := c.Param("depth1") + depth1 := c.Param("depth1") // depth2 := c.Param("depth2") depth3 := c.Param("depth3") var renderHtmlPath string if depth1 != "" && depth2 != "" && depth3 != "" { c.Set("depth", [...]string{depth1, depth2, depth3}) - renderHtmlPath = "/pages" + strings.TrimPrefix(c.Request().URL.RequestURI(), "/webconsole") + renderHtmlPath = "/pages" + strings.TrimPrefix(c.Request().URL.Path, "/webconsole") renderHtmlPath = strings.TrimSuffix(renderHtmlPath, "/") + ".html" - fmt.Println(renderHtmlPath) + log.Println("renderHtmlPath : ", renderHtmlPath) _, err := templates.FS().Open(strings.TrimPrefix(renderHtmlPath, "/")) if err != nil { return c.Render(http.StatusNotFound, defaultRender.HTML("error-404.html")) diff --git a/mc_web_console_front/actions/util.go b/mc_web_console_front/actions/util.go deleted file mode 100644 index 3a957b36..00000000 --- a/mc_web_console_front/actions/util.go +++ /dev/null @@ -1,276 +0,0 @@ -package actions - -import ( - "bytes" - "encoding/json" - "io" - "log" - "net/http" - "net/http/httputil" - "net/url" - "os" - "strings" - - "github.com/gobuffalo/buffalo" -) - -var ( - apiBaseHost *url.URL -) - -func init() { - apiAddr := os.Getenv("API_ADDR") - apiPort := os.Getenv("API_PORT") - apiBaseHost, _ = url.Parse("http://" + apiAddr + ":" + apiPort) -} - -type CommonRequest struct { - PathParams map[string]string `json:"pathParams"` - QueryParams map[string]string `json:"queryParams"` - Request interface{} `json:"request"` -} - -type CommonResponse struct { - ResponseData interface{} `json:"responseData"` - Status WebStatus `json:"status"` -} - -type WebStatus struct { - StatusCode int `json:"code"` - Message string `json:"message"` -} - -func CommonResponseProvider(status int, responseData interface{}) *CommonResponse { - webStatus := WebStatus{ - StatusCode: status, - Message: http.StatusText(status), - } - return &CommonResponse{ - ResponseData: responseData, - Status: webStatus, - } -} - -func CommonCaller(callMethod string, endPoint string, commonRequest *CommonRequest, c buffalo.Context) (*CommonResponse, error) { - pathParamsUrl := mappingUrlPathParams(endPoint, commonRequest) - queryParamsUrl := mappingQueryParams(pathParamsUrl, commonRequest) - commonResponse, err := CommonHttpToCommonResponse(apiBaseHost.ResolveReference(&url.URL{Path: queryParamsUrl}).String(), commonRequest, callMethod, c.Session().Get("Authorization").(string)) - return commonResponse, err -} - -func CommonCallerWithoutToken(callMethod string, endPoint string, commonRequest *CommonRequest) (*CommonResponse, error) { - pathParamsUrl := mappingUrlPathParams(endPoint, commonRequest) - queryParamsUrl := mappingQueryParams(pathParamsUrl, commonRequest) - commonResponse, err := CommonHttpToCommonResponse(apiBaseHost.ResolveReference(&url.URL{Path: queryParamsUrl}).String(), commonRequest, callMethod, "") - return commonResponse, err -} - -func mappingUrlPathParams(endPoint string, commonRequest *CommonRequest) string { - u := endPoint - for k, r := range commonRequest.PathParams { - u = strings.Replace(u, "{"+k+"}", r, -1) - } - return u -} - -func mappingQueryParams(targeturl string, commonRequest *CommonRequest) string { - u, err := url.Parse(targeturl) - if err != nil { - return "" - } - q := u.Query() - for k, v := range commonRequest.QueryParams { - q.Set(string(k), v) - } - u.RawQuery = q.Encode() - return u.String() -} - -func CommonHttpToCommonResponse(url string, s interface{}, httpMethod string, auth string) (*CommonResponse, error) { - log.Println("CommonHttp - METHOD:" + httpMethod + " => url:" + url) - log.Println("isauth:", auth) - - jsonData, err := json.Marshal(s) - if err != nil { - log.Println("commonPostERR : json.Marshal : ", err.Error()) - return nil, err - } - - req, err := http.NewRequest(httpMethod, url, bytes.NewBuffer(jsonData)) - if err != nil { - log.Println("Error CommonHttp creating request:", err) - return nil, err - } - req.Header.Set("Content-Type", "application/json") - if auth != "" { - req.Header.Add("Authorization", auth) - } - - requestDump, err := httputil.DumpRequest(req, true) - if err != nil { - log.Println("Error CommonHttp creating httputil.DumpRequest:", err) - } - log.Println("\n", string(requestDump)) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - log.Println("Error CommonHttp request:", err) - } - defer resp.Body.Close() - - respBody, ioerr := io.ReadAll(resp.Body) - if ioerr != nil { - log.Println("Error CommonHttp reading response:", ioerr) - } - - commonResponse := &CommonResponse{} - commonResponse.Status.Message = resp.Status - commonResponse.Status.StatusCode = resp.StatusCode - if len(respBody) > 0 { - jsonerr := json.Unmarshal(respBody, &commonResponse) - if jsonerr != nil { - log.Println("Error CommonHttp Unmarshal response:", jsonerr.Error()) - return commonResponse, jsonerr - } - } - return commonResponse, nil -} - -// func CommonAPIPostWithoutAccessToken(path string, s *CommonRequest) (*http.Response, *CommonResponse, error) { -// jsonData, err := json.Marshal(s) -// if err != nil { -// log.Println("commonPostERR : json.Marshal : ", err.Error()) -// return nil, nil, err -// } - -// resp, err := http.Post(apiBaseHost.ResolveReference(&url.URL{Path: path}).String(), "application/json", bytes.NewBuffer(jsonData)) -// if err != nil { -// log.Println("commonPostERR : http.Post : ", err.Error()) -// return resp, nil, err -// } - -// defer resp.Body.Close() - -// respBody, err := io.ReadAll(resp.Body) -// if err != nil { -// log.Println("commonPostERR : io.ReadAll : ", err.Error()) -// return resp, nil, err -// } - -// commonResponse := &CommonResponse{} -// jsonerr := json.Unmarshal(respBody, &commonResponse) -// if jsonerr != nil { -// log.Println(jsonerr.Error()) -// return resp, commonResponse, nil -// } - -// return resp, commonResponse, nil -// } - -// func CommonAPIPost(path string, s *CommonRequest, c buffalo.Context) (*http.Response, *CommonResponse, error) { -// jsonData, err := json.Marshal(s) -// if err != nil { -// log.Println("CommonAPIPostWithAccesstoken ERR : json.Marshal : ", err.Error()) -// return nil, nil, err -// } - -// accessToken := c.Session().Get("Authorization") -// accessTokenHeader := "Bearer " + accessToken.(string) - -// req, err := http.NewRequest("POST", apiBaseHost.ResolveReference(&url.URL{Path: path}).String(), bytes.NewBuffer(jsonData)) -// if err != nil { -// log.Println("CommonAPIPostWithAccesstoken ERR : http.NewRequest : ", err.Error()) -// return nil, nil, err -// } - -// req.Header.Set("Authorization", accessTokenHeader) -// req.Header.Set("Content-Type", "application/json") // Content-Type 설정 - -// client := &http.Client{} - -// resp, err := client.Do(req) -// if err != nil { -// log.Println("CommonAPIPostWithAccesstoken ERR : client.Do : ", err.Error()) -// return resp, nil, err -// } - -// defer resp.Body.Close() - -// respBody, err := io.ReadAll(resp.Body) -// if err != nil { -// log.Println("CommonAPIPostWithAccesstoken ERR : io.ReadAll : ", err.Error()) -// return resp, nil, err -// } - -// commonResponse := &CommonResponse{} -// jsonerr := json.Unmarshal(respBody, &commonResponse) -// if jsonerr != nil { -// log.Println(jsonerr.Error()) -// return resp, commonResponse, nil -// } - -// return resp, commonResponse, nil -// } - -// func CommonAPIGetWithoutAccessToken(path string) (*http.Response, *CommonResponse, error) { -// resp, err := http.Get(apiBaseHost.ResolveReference(&url.URL{Path: path}).String()) -// if err != nil { -// log.Println("commonPostERR : http.Post : ", err.Error()) -// return resp, nil, err -// } - -// defer resp.Body.Close() - -// respBody, err := io.ReadAll(resp.Body) -// if err != nil { -// log.Println("commonPostERR : io.ReadAll : ", err.Error()) -// return resp, nil, err -// } - -// commonResponse := &CommonResponse{} -// jsonerr := json.Unmarshal(respBody, &commonResponse) -// if jsonerr != nil { -// log.Println(jsonerr.Error()) -// return resp, commonResponse, nil -// } - -// return resp, commonResponse, nil -// } - -// func CommonAPIGet(path string, c buffalo.Context) (*http.Response, *CommonResponse, error) { -// accessToken := c.Session().Get("Authorization").(string) - -// req, err := http.NewRequest("GET", apiBaseHost.ResolveReference(&url.URL{Path: path}).String(), nil) -// if err != nil { -// log.Println("CommonAPIGetWithAccesstoken ERR : http.NewRequest : ", err.Error()) -// return nil, nil, err -// } - -// req.Header.Set("Authorization", "Bearer "+accessToken) - -// client := &http.Client{} - -// resp, err := client.Do(req) -// if err != nil { -// log.Println("CommonAPIGetWithAccesstoken ERR : client.Do : ", err.Error()) -// return resp, nil, err -// } - -// defer resp.Body.Close() - -// respBody, err := io.ReadAll(resp.Body) -// if err != nil { -// log.Println("CommonAPIGetWithAccesstoken ERR : io.ReadAll : ", err.Error()) -// return resp, nil, err -// } - -// commonResponse := &CommonResponse{} -// jsonerr := json.Unmarshal(respBody, &commonResponse) -// if jsonerr != nil { -// log.Println(jsonerr.Error()) -// return resp, commonResponse, nil -// } - -// return resp, commonResponse, nil -// } diff --git a/mc_web_console_front/assets/css/application.scss b/mc_web_console_front/assets/css/application.scss index 71939ba0..993b18e0 100644 --- a/mc_web_console_front/assets/css/application.scss +++ b/mc_web_console_front/assets/css/application.scss @@ -1,11 +1,165 @@ // sequential-workflow-designer import -@import '~sequential-workflow-designer/css/designer.css'; -@import '~sequential-workflow-designer/css/designer-light.css'; -@import '~sequential-workflow-designer/css/designer-dark.css'; +@import "~sequential-workflow-designer/css/designer.css"; +@import "~sequential-workflow-designer/css/designer-light.css"; +@import "~sequential-workflow-designer/css/designer-dark.css"; //tabler -@import './inter/inter.css'; // font -@import './tabler_custom.scss'; +@import "./inter/inter.css"; // font +@import "./tabler_custom.scss"; // tabulator Custom CSS -@import "./tabulator_for_tabler.scss"; +@import "./tabulator_for_tabler.scss"; + +.section { + display: none; +} +.section.active { + display: block; +} + +.sub_section { + display: none; +} +.sub_section.active { + display: block; +} + +.vmStatus-list { + max-height: 150px; + overflow-y: auto; + list-style-type: none; + padding: 0; + margin: 0; + display: flex; + flex-wrap: wrap; +} + +.vmStatus-list li { + padding: 10px; + border: 1px solid #ccc; + box-sizing: border-box; + width: calc(100% / 2); /* 기본적으로 한 줄에 2개의 아이템을 배치 */ + height: 100px; + display: inline-block; + margin: 10px 0; + text-align: center; + + font-size: 16px; + border-radius: 15px; + // transition: background-color 0.3s; /* 배경색 변화 애니메이션 */ + cursor: pointer; /* 클릭 가능 커서 */ + overflow: hidden; /* 또는 overflow: auto; */ + transition: background-color 0.3s; +} +.vmStatus-list li.clicked { + background-color: #17a2b8; /* 클릭 시 배경색 변경 */ +} + +.removebullet { + list-style-type: none; + padding-left: 0px; + flex-wrap: wrap; +} + +// .dashboard .create_box .new_servers_config.active { +// display: block; +// } + +// .dashboard .create_box .express_servers_config.active { +// display: block; +// } + +/* 화면 폭이 1px 이상 400px 미만일 때 */ +@media (max-width: 399px) { + .vmStatus-list li { + width: calc(100% / 2); /* 한 줄에 3개의 아이템을 배치 */ + } +} + +/* 화면 폭이 400px 이상 600px 미만일 때 */ +@media (min-width: 400px) and (max-width: 599px) { + .vmStatus-list li { + width: calc(100% / 3); /* 한 줄에 3개의 아이템을 배치 */ + } +} + +/* 화면 폭이 600px 이상 900px 미만일 때 */ +@media (min-width: 600px) and (max-width: 899px) { + .vmStatus-list li { + width: calc(100% / 4); /* 한 줄에 4개의 아이템을 배치 */ + } +} + +/* 화면 폭이 900px 이상일 때 */ +@media (min-width: 900px) { + .vmStatus-list li { + width: calc(100% / 5); /* 한 줄에 5개의 아이템을 배치 */ + } +} + +// 전체 mcis / server 박스 스타일 +.mcislistbox { + display: flex; + flex-wrap: wrap; + gap: 10px; /* 카드 간의 간격 */ + width: 100%; +} + +.mcis-list { + border-radius: 15px; + border: 2px solid #ddd; + box-shadow: 0 0 10px rgba(0,0,0,0.1); + float: left; + position: relative; + width: 252px; + height: 259px; + overflow: hidden; /* 스크롤 가능 영역 설정 */ + cursor: pointer; /* 버튼 커서 */ + transition: background-color 0.3s; /* 호버 시 배경색 전환 효과 */ + +} + +// 전체 mcis / server ul 스타일 +.vm-list { + display: flex; + flex-wrap: wrap; + list-style-type: none; /* 기본 불릿 제거 */ + padding: 10px; + width: 100%; + max-height: 150px; + overflow-y: auto; + flex: 1; +} + +// 전체 mcis / server li 스타일 +.vm-item { + border-radius: 10px; + border: 1px solid #ddd; + width: 80px; /* 네모 크기 */ + height: 65px; /* 네모 크기 */ + border: 1px solid #ccc; /* 테두리 */ + display: flex; + align-items: center; + justify-content: center; + margin: 5px; /* 네모들 간의 간격 */ + text-align: center; +} + +// .vm-item:hover { +// background-color: hsl( 80%, 70%); /* 호버 시 배경색 변경 */ +// } + +/* 반응형 디자인 */ +@media (max-width: 600px) { + .vm-item { + width: 40px; + height: 40px; + } +} + +@media (max-width: 400px) { + .vm-item { + width: 30px; + height: 30px; + } +} diff --git a/mc_web_console_front/assets/css/tabulator_for_tabler.scss b/mc_web_console_front/assets/css/tabulator_for_tabler.scss index 67519500..79ee4a7f 100644 --- a/mc_web_console_front/assets/css/tabulator_for_tabler.scss +++ b/mc_web_console_front/assets/css/tabulator_for_tabler.scss @@ -27,8 +27,10 @@ $rowBorderColor:transparent; //table border color $rowTextColor:inherit; //table text color $rowHoverBackground:rgba(0, 0, 0, 0.1); //row background color on hover -$rowSelectedBackground: $primary; //row background color when selected -$rowSelectedBackgroundHover: $primary-darker;//row background color when selected and hovered +// $rowSelectedBackground: $primary; //row background color when selected +// $rowSelectedBackgroundHover: $primary-darker;//row background color when selected and hovered +$rowSelectedBackground: rgba(lighten($primary, 40%), 0.5); //row background color when selected +$rowSelectedBackgroundHover: rgba(0, 0, 0, 0.2); $editBoxColor:#1D68CD; //border color for edit boxes $errorColor:#dd0000; //error indication @@ -62,6 +64,7 @@ $rangeHeaderTextHighlightBackground: #000000; //header text color when highlight white-space: nowrap; overflow: hidden; outline: none; + border-top: 1px solid $border-color; } .tabulator .tabulator-header .tabulator-col .tabulator-col-content .tabulator-col-title{ diff --git a/mc_web_console_front/assets/images/common/icon_question.png b/mc_web_console_front/assets/images/common/icon_question.png new file mode 100644 index 00000000..94705e2d Binary files /dev/null and b/mc_web_console_front/assets/images/common/icon_question.png differ diff --git a/mc_web_console_front/assets/images/common/icon_running.svg b/mc_web_console_front/assets/images/common/icon_running.svg new file mode 100644 index 00000000..1d412b05 --- /dev/null +++ b/mc_web_console_front/assets/images/common/icon_running.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/mc_web_console_front/assets/images/common/icon_stop.svg b/mc_web_console_front/assets/images/common/icon_stop.svg new file mode 100644 index 00000000..59faaea0 --- /dev/null +++ b/mc_web_console_front/assets/images/common/icon_stop.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/mc_web_console_front/assets/images/common/icon_terminate.svg b/mc_web_console_front/assets/images/common/icon_terminate.svg new file mode 100644 index 00000000..22c70fc2 --- /dev/null +++ b/mc_web_console_front/assets/images/common/icon_terminate.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/mc_web_console_front/assets/images/common/img_logo_alibaba.png b/mc_web_console_front/assets/images/common/img_logo_alibaba.png new file mode 100644 index 00000000..cf83a66a Binary files /dev/null and b/mc_web_console_front/assets/images/common/img_logo_alibaba.png differ diff --git a/mc_web_console_front/assets/images/common/img_logo_aws.png b/mc_web_console_front/assets/images/common/img_logo_aws.png new file mode 100644 index 00000000..af2f1502 Binary files /dev/null and b/mc_web_console_front/assets/images/common/img_logo_aws.png differ diff --git a/mc_web_console_front/assets/images/common/img_logo_gcp.png b/mc_web_console_front/assets/images/common/img_logo_gcp.png new file mode 100644 index 00000000..79555edd Binary files /dev/null and b/mc_web_console_front/assets/images/common/img_logo_gcp.png differ diff --git a/mc_web_console_front/assets/images/common/img_logo_tencent.png b/mc_web_console_front/assets/images/common/img_logo_tencent.png new file mode 100644 index 00000000..47e60767 Binary files /dev/null and b/mc_web_console_front/assets/images/common/img_logo_tencent.png differ diff --git a/mc_web_console_front/assets/images/common/monitoring_example.png b/mc_web_console_front/assets/images/common/monitoring_example.png new file mode 100644 index 00000000..32b5bd3f Binary files /dev/null and b/mc_web_console_front/assets/images/common/monitoring_example.png differ diff --git a/mc_web_console_front/assets/images/common/worldmap_example.png b/mc_web_console_front/assets/images/common/worldmap_example.png new file mode 100644 index 00000000..49393a1a Binary files /dev/null and b/mc_web_console_front/assets/images/common/worldmap_example.png differ diff --git a/mc_web_console_front/assets/js/application.js b/mc_web_console_front/assets/js/application.js index 24dfa1d0..2825cce6 100644 --- a/mc_web_console_front/assets/js/application.js +++ b/mc_web_console_front/assets/js/application.js @@ -1,4 +1,5 @@ require("expose-loader?exposes=$,jQuery!jquery"); require("bootstrap/dist/js/bootstrap.bundle.js"); require("@fortawesome/fontawesome-free/js/all.js"); -require("jquery-ujs/src/rails.js"); \ No newline at end of file +require("jquery-ujs/src/rails.js"); +require("~jquery/dist/jquery.js"); \ No newline at end of file diff --git a/mc_web_console_front/assets/js/common/api/http.js b/mc_web_console_front/assets/js/common/api/http.js index 4d5bf1ce..4d145068 100644 --- a/mc_web_console_front/assets/js/common/api/http.js +++ b/mc_web_console_front/assets/js/common/api/http.js @@ -5,11 +5,12 @@ export async function commonAPIPost(url, data) { console.log("Request URL : ", url) console.log("Request Data : ") console.log(JSON.stringify(data)) - console.log("-----------------------") - let csrfToken = document.getElementById("csrf-token").getAttribute('content'); + const csrfToken = document.getElementById("csrf-token").getAttribute('content'); axios.defaults.headers.common['X-CSRF-TOKEN'] = csrfToken; + console.log("-----------------------") + const response = await axios.post(url, data) .then(function (response) { console.log("#### commonAPIPost Response") @@ -50,4 +51,4 @@ export async function commonAPIGet(url) { }); return response -} \ No newline at end of file +} diff --git a/mc_web_console_front/assets/jsOld/partials/operation/manage/server_info_monitoringcard.js b/mc_web_console_front/assets/js/common/server_info_monitoringcard.js similarity index 85% rename from mc_web_console_front/assets/jsOld/partials/operation/manage/server_info_monitoringcard.js rename to mc_web_console_front/assets/js/common/server_info_monitoringcard.js index 81dde130..96fa3a2d 100644 --- a/mc_web_console_front/assets/jsOld/partials/operation/manage/server_info_monitoringcard.js +++ b/mc_web_console_front/assets/js/common/server_info_monitoringcard.js @@ -1,5 +1,45 @@ import Apexcharts from "apexcharts" +// function drawGraph(data, label, ...){ + +// } +const coffeeData = { + cpuAmericano: { + name: "americano", + data: [75, 78, 76, 52, 82, 102, 90] + }, + cpuLatte: { + name: "latte", + data: [72, 43, 81, 54, 77, 63, 79] + }, + + memoryAmericano: { + name: "americano", + data: [63, 61, 65, 64, 62, 60, 76] + }, + memoryLatte: { + name: "latte", + data: [52, 50, 58, 49, 42, 50, 69] + }, + + diskAmericano: { + name: "americano", + data: [40, 42, 41, 43, 44, 39, 42] + }, + diskLatte: { + name: "latte", + data: [32, 30, 38, 39, 32, 30, 39] + }, + + networkAmericano: { + name: "americano", + data: [1520, 1410, 1583, 1495, 1623, 1389, 1501] + }, + networkLatte: { + name: "latte", + data: [1120, 1250, 1293, 1225, 1183, 1199, 1161] + } +}; document.addEventListener("DOMContentLoaded", function () { console.log("=====", window) @@ -10,7 +50,7 @@ document.addEventListener("DOMContentLoaded", function () { height: 240, parentHeightOffset: 0, toolbar: { - show: false, + show: true, }, animations: { enabled: false @@ -42,13 +82,10 @@ document.addEventListener("DOMContentLoaded", function () { lineCap: "round", curve: "smooth", }, - series: [{ - name: "series1", - data: [56, 40, 39, 47, 34, 48, 44] - }, { - name: "series2", - data: [45, 43, 30, 23, 38, 39, 54] - }], + series: [ + coffeeData.cpuAmericano, + coffeeData.cpuLatte + ], tooltip: { theme: 'dark' }, @@ -99,7 +136,6 @@ document.addEventListener("DOMContentLoaded", function () { })).render(); }); - document.addEventListener("DOMContentLoaded", function () { console.log("=====", window) window && (new Apexcharts(document.getElementById('memory-chart'), { @@ -109,7 +145,7 @@ document.addEventListener("DOMContentLoaded", function () { height: 240, parentHeightOffset: 0, toolbar: { - show: false, + show: true, }, animations: { enabled: false @@ -141,13 +177,10 @@ document.addEventListener("DOMContentLoaded", function () { lineCap: "round", curve: "smooth", }, - series: [{ - name: "series1", - data: [56, 40, 39, 47, 34, 48, 44] - }, { - name: "series2", - data: [45, 43, 30, 23, 38, 39, 54] - }], + series: [ + coffeeData.memoryAmericano, + coffeeData.memoryLatte + ], tooltip: { theme: 'dark' }, @@ -207,7 +240,7 @@ document.addEventListener("DOMContentLoaded", function () { height: 240, parentHeightOffset: 0, toolbar: { - show: false, + show: true, }, animations: { enabled: false @@ -241,13 +274,10 @@ document.addEventListener("DOMContentLoaded", function () { lineCap: "round", curve: "smooth", }, - series: [{ - name: "series1", - data: [56, 40, 39, 47, 34, 48, 44] - }, { - name: "series2", - data: [45, 43, 30, 23, 38, 39, 54] - }], + series: [ + coffeeData.diskAmericano, + coffeeData.diskLatte + ], tooltip: { theme: 'dark' }, @@ -307,7 +337,7 @@ document.addEventListener("DOMContentLoaded", function () { height: 240, parentHeightOffset: 0, toolbar: { - show: false, + show: true, }, animations: { enabled: false @@ -341,13 +371,10 @@ document.addEventListener("DOMContentLoaded", function () { lineCap: "round", curve: "smooth", }, - series: [{ - name: "series1", - data: [56, 40, 39, 47, 34, 48, 44] - }, { - name: "series2", - data: [45, 43, 30, 23, 38, 39, 54] - }], + series: [ + coffeeData.networkAmericano, + coffeeData.networkLatte + ], tooltip: { theme: 'dark' }, diff --git a/mc_web_console_front/assets/js/common/storage/sessionstorage.js b/mc_web_console_front/assets/js/common/storage/sessionstorage.js index aacec841..d495a514 100644 --- a/mc_web_console_front/assets/js/common/storage/sessionstorage.js +++ b/mc_web_console_front/assets/js/common/storage/sessionstorage.js @@ -1,4 +1,19 @@ -// workspace +// user token mng START +////////////////////////////////////////////////////////// + +export function setSessionCurrentUserToken(token) { + sessionStorage.setItem('currentUserToken',token) +} + +export function getSessionCurrentUserToken() { + let currentUserToken = sessionStorage.getItem('currentUserToken') + return currentUserToken +} + +// user token mng END +////////////////////////////////////////////////////////// + +// workspaceS export function getSessionCurrentWorkspace() { return JSON.parse(sessionStorage.getItem("currentWorkspace")) } @@ -6,7 +21,7 @@ export function setSessionCurrentWorkspace(workspace) { sessionStorage.setItem('currentWorkspace',JSON.stringify(workspace)) } -// project +// // project export function getSessionCurrentProject() { return JSON.parse(sessionStorage.getItem("currentProject")) } @@ -17,8 +32,29 @@ export function setSessionCurrentProject(project) { export function getSessionWorkspaceProjectList() { return JSON.parse(sessionStorage.getItem("currentWorkspaceProjcetList")) } -export function setSessionWorkspaceProjectList(v) { - sessionStorage.setItem('currentWorkspaceProjcetList',JSON.stringify(v)) +export function setSessionWorkspaceProjectList(userWorkspaceProjectList) { + var workspaceProjectList = JSON.stringify(userWorkspaceProjectList) + sessionStorage.setItem('currentWorkspaceProjcetList', workspaceProjectList) + + var workspaceList = [] + + const jsonData = JSON.parse(userWorkspaceProjectList); + //console.log(jsonData) + jsonData.forEach(item => { + console.log(item) + var wsItem = item.workspaceProject.workspace; + workspaceList.push(wsItem); + + var proItems = item.workspaceProject.projects; + var projectList = [] + proItems.forEach(subitem => { + projectList.push(subitem); + }); + setSessionProjectList(wsItem.id, JSON.stringify(projectList)) + //setSessionProjectList(wsItem.name, JSON.stringify(projectList))// 공백같은 것은 없겠지? + }); + setSessionWorkspaceList(JSON.stringify(workspaceList)) + } export function clearSessionCurrentWorkspaceProject() { @@ -26,3 +62,57 @@ export function clearSessionCurrentWorkspaceProject() { sessionStorage.removeItem("currentProject") sessionStorage.removeItem("currentWorkspace") } + +////////// 선택한 workspace, project 저장 +export function getSessionCurrentWorkspaceProjcet() { + let currentWorkspacProject = JSON.parse(sessionStorage.getItem('currentWorkspacProject')) + return currentWorkspacProject +} + +export function setSessionCurrentWorkspaceProjcet(workspaceId, projectId) { + let currentWorksppacProject = { + "currentWorkspace":workspaceId, + "currentProject":projectId + } + sessionStorage.setItem('currentWorkspacProject',JSON.stringify(currentWorksppacProject)) +} + +export async function getSessionWorkspaceList() { + let workspaceList = JSON.parse(await sessionStorage.getItem('workspaceList')) + if (workspaceList == null){ + await webconsolejs["common/storage/sessionstorage"].updateSessionWorkspaceList() + workspaceList = webconsolejs["common/storage/sessionstorage"].getSessionWorkspaceList() + } + return workspaceList.Workspaces +} + +export async function setSessionWorkspaceList(v) { + sessionStorage.setItem('workspaceList',v) +} + +export async function getSessionProjectList(workspaceId) { + console.log("getSessionProjectList ", workspaceId) + let projectList = JSON.parse( await sessionStorage.getItem("projectList_"+workspaceId)) + console.log(projectList); + return projectList +} + +export async function setSessionProjectList(workspaceId, projectList) { + + sessionStorage.setItem("projectList_"+workspaceId,projectList) +} + + +// sessionStorage의 workspaceList 갱신 +export async function updateSessionWorkspaceList(workspaceList) { + // const response = await webconsolejs["common/http/api"].commonAPIPost('/api/workspacelistbyuser') + // sessionStorage.setItem('workspaceList', JSON.stringify(response.data.responseData)); + sessionStorage.setItem('workspaceList', JSON.stringify(workspaceList)); +} + +// sessionStorage의 projectList 갱신 : 조회된 목록을 갱신 +//export async function updateSessionProjectListByWorkspaceId(workspaceId) { +export async function updateSessionProjectList(projectList) { + sessionStorage.setItem('projectList', JSON.stringify(projectList)); +} + diff --git a/mc_web_console_front/assets/js/common/util.js b/mc_web_console_front/assets/js/common/util.js index d749283d..5c56b504 100644 --- a/mc_web_console_front/assets/js/common/util.js +++ b/mc_web_console_front/assets/js/common/util.js @@ -1,17 +1,214 @@ +import { TabulatorFull as Tabulator } from "tabulator-tables"; + +export function setTabulator( + tableObjId, + tableObjParamMap, + columnsParams, + isMultiSelect +) { + var placeholder = "No Data"; + var pagination = "local"; + var paginationSize = 5; + var paginationSizeSelector = [5, 10, 15, 20]; + var movableColumns = true; + var columnHeaderVertAlign = "middle"; + var paginationCounter = "rows"; + var layout = "fitColumns"; + + if (tableObjParamMap.hasOwnProperty("placeholder")) { + placeholder = tableObjParamMap.placeholder; + } + + if (tableObjParamMap.hasOwnProperty("pagination")) { + pagination = tableObjParamMap.pagination; + } + + if (tableObjParamMap.hasOwnProperty("paginationSize")) { + paginationSize = tableObjParamMap.paginationSize; + } + + if (tableObjParamMap.hasOwnProperty("paginationSizeSelector")) { + paginationSizeSelector = tableObjParamMap.paginationSizeSelector; + } + + if (tableObjParamMap.hasOwnProperty("movableColumns")) { + movableColumns = tableObjParamMap.movableColumns; + } + + if (tableObjParamMap.hasOwnProperty("columnHeaderVertAlign")) { + columnHeaderVertAlign = tableObjParamMap.columnHeaderVertAlign; + } + + if (tableObjParamMap.hasOwnProperty("paginationCounter")) { + paginationCounter = tableObjParamMap.paginationCounter; + } + + if (tableObjParamMap.hasOwnProperty("layout")) { + layout = tableObjParamMap.layout; + } + + var tabulatorTable = new Tabulator("#" + tableObjId, { + //ajaxURL:"http://localhost:3000/operations/mcismng?option=status", + placeholder, + pagination, + paginationSize, + paginationSizeSelector, + movableColumns, + columnHeaderVertAlign, + paginationCounter, + layout, + columns: columnsParams, + selectable: isMultiSelect == false ? 1 : true, + }); + + return tabulatorTable; +} + + +// 화면이동 +export function changePage(target, urlParamMap){ + var url = ""; + // target에 따라 url을 달리한다. + if( target == "McisMng"){ + url = "/webconsole/operation/manage/mcis" + } + + // pathParam을 뒤에 붙인다. + var keyIndex = 0; + for (let key of urlParamMap.keys()) { + console.log("urlParamMap " + key + " : " + urlParamMap.get(key)); + + var urlParamValue = urlParamMap.get(key) + + if( keyIndex == 0 ) { + url += "?" + key + "=" + urlParamValue; + }else{ + url += "&" + key + "=" + urlParamValue; + } + + } + + // 해당 화면으로 이동한다. + location.href = url; +} + // default workspace에서 sessionstorage를 사용하지 않을때, 아래에서 리턴값 재정의 -// workspace +// workspace 만 export function getCurrentWorkspace() { - return webconsolejs["common/storage/sessionstorage"].getSessionCurrentWorkspace() + const currWs = webconsolejs["common/storage/sessionstorage"].getSessionCurrentWorkspace() + + console.log("currWs ", currWs) + return currWs } -export function setCurrentWorkspace(v) { - webconsolejs["common/storage/sessionstorage"].setSessionCurrentWorkspace(v) +export function setCurrentWorkspace(workspace) { + webconsolejs["common/storage/sessionstorage"].setSessionCurrentWorkspace(workspace) } export function getCurrentProject() { return webconsolejs["common/storage/sessionstorage"].getSessionCurrentProject() } -export function setCurrentProject(v) { - webconsolejs["common/storage/sessionstorage"].setSessionCurrentProject(v) +export function setCurrentProject(project) { + webconsolejs["common/storage/sessionstorage"].setSessionCurrentProject(project) +} + +// 세션에서 workspace project 목록 찾기 +function getWorkspaceProjectList(){ + webconsolejs["common/storage/sessionstorage"].getSessionWorkspaceProjectList(); +} + +// 세션에 workspace project 목록 저장 +function setWorkspaceProjectList(workspaceProjectList){ + webconsolejs["common/storage/sessionstorage"].setSessionWorkspaceProjectList(workspaceProjectList) +} + +// user의 workspace 목록만 추출 +export function getUserWorkspaceList() { + return webconsolejs["common/storage/sessionstorage"].getSessionWorkspaceList() +} + +export async function getUserProjectList(workspaceId) { + var projectList = await webconsolejs["common/storage/sessionstorage"].getSessionProjectList(workspaceId) + console.log("getUserProjectList ", projectList) + return projectList +} + +///////////////////////////////////// + +// 유저의 workspace 목록 조회 +async function getWorkspaceProjectListByUser() { + const response = await webconsolejs["common/api/http"].commonAPIPost('/api/getworkspacebyuserid', null) + return response.data.responseData +} + + +/////////////////////////////////////// +// 로그인 유저의 workspace 목록 조회 +export async function getWorkspaceListByUser() { + var workspaceList = []; + // 세션에서 찾기 + let userWorkspaceList = await webconsolejs["common/storage/sessionstorage"].getSessionWorkspaceProjectList(); + + if (userWorkspaceList == null ){// 없으면 조회 + console.log("not saved. get ") + var userWorkspaceProjectList = await getWorkspaceProjectListByUser()// workspace 목록, project 목록 조회 + setWorkspaceProjectList(userWorkspaceProjectList) + + // workspaceProjectList에서 workspace 목록만 추출 + const jsonData = JSON.parse(userWorkspaceProjectList); + //console.log(jsonData) + jsonData.forEach(item => { + //console.log(item) + workspaceList.push(item.workspaceProject.workspace); + }); + + // 새로 조회한 경우 저장된 curworkspace, curproject 는 초기화 할까? + setCurrentWorkspace("") + setCurrentProject("") + }else{ + const jsonData = JSON.parse(userWorkspaceList); + //console.log(jsonData) + jsonData.forEach(item => { + //console.log(item) + workspaceList.push(item.workspaceProject.workspace); + }); + } + + return workspaceList; +} + + +// workspace에 매핑된 project목록 조회 +export async function getProjectListByWorkspaceId(workspaceId) { + + console.log("getProjectListByWorkspaceId", workspaceId) + let requestObject = { + "pathParams": { + "workspaceId": workspaceId + }, + "requestData":{ + "userId":"mciamuser", // TODO : 실제 로그인 user의 id 설정하도록 변경할 것. + } + } + + var projectList = []; + const response = await webconsolejs["common/api/http"].commonAPIPost('/api/projectlistbyworkspaceid',requestObject) + console.log(response) + var data = response.data.responseData.projects + data.forEach(item => { + console.log(item) + projectList.push(item); + }); + + // project List + return projectList; +} + +export function getUserWorkspaceProjectList() { + return webconsolejs["common/storage/sessionstorage"].getSessionWorkspaceProjectList() +} + +export function setUserWorkspaceProjectList(workspaceProjectList) { + webconsolejs["common/storage/sessionstorage"].setSessionWorkspaceProjectList(workspaceProjectList) } // workspace project List @@ -25,3 +222,235 @@ export function setCurrentWorkspaceProjectList(v) { export function clearCurrentWorkspaceProject() { webconsolejs["common/storage/sessionstorage"].clearSessionCurrentWorkspaceProject() } + + +// TODO : 적절한 경로로 이동시킬 것. +/////////////////////// component util ////////////////////////// +// workspaceList select에 set. +//function updateWsSelectBox(workspaceList) { + +// navbar에 있는 workspace select 에 workspace 목록 set +// 만약 curworkspaceid가 있으면 selected 하도록 +// session에서 꺼내쓰려고 했으나 그냥 param으로 받는게 함. +export function setWorkspaceSelectBox(workspaceList, curWorkspaceId) { + let workspaceListselectBox = document.getElementById("select-current-workspace"); + + while (workspaceListselectBox.options.length > 0) { + workspaceListselectBox.remove(0); + } + var workspaceExists = false + //console.log("get workspace from session " , webconsolejs["common/util"].getCurrentWorkspace()) + //let curWorkspaceId = await webconsolejs["common/util"].getCurrentWorkspace()?.Id + + console.log("setWorkspaceSelectbox --------------------") + //console.log(workspaceList) + const defaultOpt = document.createElement("option"); + defaultOpt.value = "" + defaultOpt.textContent = "Please select a workspace"; + workspaceListselectBox.appendChild(defaultOpt); + + for (const w in workspaceList) { + const opt = document.createElement("option"); + opt.value = workspaceList[w].id; + opt.textContent = workspaceList[w].name; + console.log("curWorkspaceId", curWorkspaceId) + console.log("workspaceList[w]", workspaceList[w]) + if (curWorkspaceId != "" && workspaceList[w].id == curWorkspaceId) { + opt.setAttribute("selected", "selected"); + workspaceExists = true + } + workspaceListselectBox.appendChild(opt); + } +} + +// navbar에 있는 project select 에 project 목록 set +// 만약 curprojectid가 있으면 selected 하도록 +// session에서 꺼내쓰려고 했으나 그냥 param으로 받는게 함. +export function setPrjSelectBox(projectList, curProjectId) { +// function updatePrjSelectBox(workspaceId) { + + let projectListselectBox = document.getElementById("select-current-project"); + + //let projectList = await webconsolejs["common/util"].getProjectListByWorkspaceId(workspaceId) + console.log("setPrjSelectBox projectList ", projectList) + while (projectListselectBox.options.length > 0) { + projectListselectBox.remove(0); + } + + const defaultOpt = document.createElement("option"); + defaultOpt.value = "" + defaultOpt.textContent = "Please select a project"; + projectListselectBox.appendChild(defaultOpt); + + //let curProjectId = webconsolejs["common/util"].getCurrentProject()?.Id + for (const p in projectList) { + console.log("p ", p) + const opt = document.createElement("option"); + opt.value = projectList[p].id; + opt.textContent = projectList[p].name; + projectListselectBox.appendChild(opt); + + if (curProjectId != undefined && curProjectId != "" && projectList[p].id == curProjectId) { + opt.setAttribute("selected", "selected"); + } + } +} + + +/////////////////////// + +function isEmpty(str) { + if (typeof str == "undefined" || str == null || str == "") + return true; + else + return false; +} + +// export function setTabulator( +// tableObjId, +// tableObjParamMap, +// columnsParams, +// isMultiSelect +// ) { +// var placeholder = "No Data"; +// var pagination = "local"; +// var paginationSize = 5; +// var paginationSizeSelector = [5, 10, 15, 20]; +// var movableColumns = true; +// var columnHeaderVertAlign = "middle"; +// var paginationCounter = "rows"; +// var layout = "fitColumns"; + +// if (tableObjParamMap.hasOwnProperty("placeholder")) { +// placeholder = tableObjParamMap.placeholder; +// } + +// if (tableObjParamMap.hasOwnProperty("pagination")) { +// pagination = tableObjParamMap.pagination; +// } + +// if (tableObjParamMap.hasOwnProperty("paginationSize")) { +// paginationSize = tableObjParamMap.paginationSize; +// } + +// if (tableObjParamMap.hasOwnProperty("paginationSizeSelector")) { +// paginationSizeSelector = tableObjParamMap.paginationSizeSelector; +// } + +// if (tableObjParamMap.hasOwnProperty("movableColumns")) { +// movableColumns = tableObjParamMap.movableColumns; +// } + +// if (tableObjParamMap.hasOwnProperty("columnHeaderVertAlign")) { +// columnHeaderVertAlign = tableObjParamMap.columnHeaderVertAlign; +// } + +// if (tableObjParamMap.hasOwnProperty("paginationCounter")) { +// paginationCounter = tableObjParamMap.paginationCounter; +// } + +// if (tableObjParamMap.hasOwnProperty("layout")) { +// layout = tableObjParamMap.layout; +// } + +// var tabulatorTable = new Tabulator("#" + tableObjId, { +// //ajaxURL:"http://localhost:3000/operations/mcismng?option=status", +// placeholder, +// pagination, +// paginationSize, +// paginationSizeSelector, +// movableColumns, +// columnHeaderVertAlign, +// paginationCounter, +// layout, +// columns: columnsParams, +// selectable: isMultiSelect == false ? 1 : true, +// }); + +// return tabulatorTable; +// } + +// column show & hide +export function displayColumn(table) { + $(".display-column").on("click", function () { + if ($(this).children("input:checkbox").is(":checked")) { + $(this).children(".material-icons").text("visibility"); + table.showColumn($(this).data("column")); + } else { + $(this).children(".material-icons").text("visibility_off"); + table.hideColumn($(this).data("column")); + } + }); +} + +// mcis내 vm들의 provider별 connection count +export function calculateConnectionCount(vmList) { + +// console.log("calculateConnectionCount") +// console.log(vmList) +var vmCloudConnectionCountMap = new Map(); + +for (var vmIndex in vmList) { + var aVm = vmList[vmIndex]; + var location = aVm.connectionConfig; + if (!isEmpty(location)) { + + var cloudType = location.providerName; + if (vmCloudConnectionCountMap.has(cloudType)) { + + vmCloudConnectionCountMap.set( + cloudType, + vmCloudConnectionCountMap.get(cloudType) + 1 + ); + } else { + vmCloudConnectionCountMap.set(cloudType, 0); + } + } +} + +return vmCloudConnectionCountMap; +} + +// 공통으로 사용하는 data 조회 function : 목록(list), 단건(data) 동일 +// optionParamMap.set("is_cb", "N");// db를 조회하는 경우 'N', cloud-barista를 직접호출하면 is_cb='Y'. 기본은 is_cb=Y +// filter 할 조건이 있으면 filterKey="connectionName", filterVal="conn-xxx" 등으로 optionParam에 추가하면 됨. +// optionParamMap.set("option", "id");// 결과를 id만 가져오는 경우는 option="id"를 추가 한다. +// buffalo의 helperName으로 router를 찾도록 변경함. +//export function getCommonData(caller, controllerKeyName, optionParamMap, callbackSuccessFunction, callbackFailFunction){ +export function getCommonData( + caller, + helperName, + optionParamMap, + callbackSuccessFunction, + callbackFailFunction + ) { + //var url = getURL(controllerKeyName, optionParamMap); + var url = getURL(helperName, optionParamMap); + + axios + .get(url, { + headers: { + "Content-Type": "application/json", + }, + }) + .then((result) => { + console.log(result); + if ( + callbackSuccessFunction == undefined || + callbackSuccessFunction == "" + ) { + var data = result.data; + console.log("callbackSuccessFunction undefined get data : ", data); + } else { + callbackSuccessFunction(caller, result); + } + }) + .catch((error) => { + console.warn(error); + if (callbackFailFunction == undefined || callbackFailFunction == "") { + mcpjs["util/util"].commonAlert(error); + } else { + callbackFailFunction(caller, error); + } + }); +} \ No newline at end of file diff --git a/mc_web_console_front/assets/js/pages/auth/login.js b/mc_web_console_front/assets/js/pages/auth/login.js index 7a9ebbe2..54936b73 100644 --- a/mc_web_console_front/assets/js/pages/auth/login.js +++ b/mc_web_console_front/assets/js/pages/auth/login.js @@ -6,12 +6,13 @@ document.getElementById("loginbtn").addEventListener('click',async function () { "password":document.getElementById("password").value } }; - const response = await webconsolejs["common/api/http"].commonAPIPost('/auth/login', data) + const response = await webconsolejs["common/api/http"].commonAPIPost('/api/auth/login', data) if (response.status != 200){ alert("LoginFail\n"+response.data) document.getElementById("id").value = null document.getElementById("password").value = null }else{ - window.location = response.data.responseData.redirect + // webconsolejs["common/storage/sessionstorage"].setSessionCurrentUserToken(response.data.responseData.access_token) + window.location = "/" } }); \ No newline at end of file diff --git a/mc_web_console_front/assets/js/pages/configuration/role/manage.js b/mc_web_console_front/assets/js/pages/configuration/role/manage.js new file mode 100644 index 00000000..90c1befb --- /dev/null +++ b/mc_web_console_front/assets/js/pages/configuration/role/manage.js @@ -0,0 +1,397 @@ +import { TabulatorFull as Tabulator } from "tabulator-tables"; + +//// +// 모달 콜백 예제 : confirm 버튼을 눌렀을 때 호출될 callback 함수로 사용할 용도 +export function commoncallbac(val) { + alert(val); +} +//// + +////////// TABULATOR ////////// +var table; +var checked_array = []; +initTable(); +// function setTabulator( +// tableObjId, +// tableObjParamMap, +// columnsParams, +// isMultiSelect +// ) { +// var placeholder = "No Data"; +// var pagination = "local"; +// var paginationSize = 5; +// var paginationSizeSelector = [5, 10, 15, 20]; +// var movableColumns = true; +// var columnHeaderVertAlign = "middle"; +// var paginationCounter = "rows"; +// var layout = "fitColumns"; + +// if (tableObjParamMap.hasOwnProperty("placeholder")) { +// placeholder = tableObjParamMap.placeholder; +// } + +// if (tableObjParamMap.hasOwnProperty("pagination")) { +// pagination = tableObjParamMap.pagination; +// } + +// if (tableObjParamMap.hasOwnProperty("paginationSize")) { +// paginationSize = tableObjParamMap.paginationSize; +// } + +// if (tableObjParamMap.hasOwnProperty("paginationSizeSelector")) { +// paginationSizeSelector = tableObjParamMap.paginationSizeSelector; +// } + +// if (tableObjParamMap.hasOwnProperty("movableColumns")) { +// movableColumns = tableObjParamMap.movableColumns; +// } + +// if (tableObjParamMap.hasOwnProperty("columnHeaderVertAlign")) { +// columnHeaderVertAlign = tableObjParamMap.columnHeaderVertAlign; +// } + +// if (tableObjParamMap.hasOwnProperty("paginationCounter")) { +// paginationCounter = tableObjParamMap.paginationCounter; +// } + +// if (tableObjParamMap.hasOwnProperty("layout")) { +// layout = tableObjParamMap.layout; +// } + +// var tabulatorTable = new Tabulator("#" + tableObjId, { +// placeholder, +// pagination, +// paginationSize, +// paginationSizeSelector, +// movableColumns, +// columnHeaderVertAlign, +// paginationCounter, +// layout, +// columns: columnsParams, +// selectableRows: isMultiSelect == false ? 1 : true, +// }); + +// return tabulatorTable; +// } + +// Table 초기값 설정 +function initTable() { + + var tableObjParams = {}; + + var columns = [ + { + formatter: "rowSelection", + titleFormatter: "rowSelection", + vertAlign: "middle", + hozAlign: "center", + headerHozAlign: "center", + headerSort: false, + width: 60, + }, + { + title: "Id", + field: "id", + visible: false + }, + { + title: "Name", + field: "name", + vertAlign: "middle" + }, + ]; + + table = webconsolejs["common/util"].setTabulator("workspacelist-table", tableObjParams, columns); + + // 행 클릭 시 + table.on("rowClick", function (e, row) { + console.log(row) + var roleID = row.getCell("id").getValue(); + console.log("roleID", roleID) + // console.log("eeeee",e) + //clickListOfMcis(row.getCell("id").getValue()); + + getSelectedRoleData(roleID) + + }); + + //  선택된 여러개 row에 대해 처리 + table.on("rowSelectionChanged", function (data, rows) { + checked_array = data + console.log("checked_array", checked_array) + console.log("rowsrows", data) + }); +} + +// 클릭한 role info 가져오기 +async function getSelectedRoleData(roleID) { + const data = { + pathParams: { + roleId: roleID + } + } + + + var controller = "/api/" + "getrolebyid"; + const response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + + console.log("response", response) + var roleData = response.data.responseData; + console.log("roleData", roleData) + + // SET Role Info + setRoleInfoData(roleData) + + window.location.hash = "info_role" +} + +// 클릭한 mcis info 세팅 +function setRoleInfoData(roleData) { + console.log("setRoleInfoData", roleData) + try { + var roleId = roleData.id; + console.log("roleId ", roleId) + + var name = roleData.name; + console.log("name ", name) + var description = roleData.description; + console.log("description ", description) + + $("#info_id").val(""); + $("#info_name").val(""); + + $("#info_id").val(id); + $("#info_name").val(name); + $("#info_desc").val(description); + + } catch (e) { + console.error(e); + } +} + + +export async function roleDetailInfo(roleID) { + // Toggle Info + var div = document.getElementById("server_info"); + webconsolejs["partials/layout/navigatePages"].toggleElement(div) + + // 기존 값들 초기화 + //clearServerInfo(); + + var data = new Object(); + + // + //vm info + // $("#mcis_server_info_status_img").attr("src", "/assets/images/common/" + mcisStatusIcon) + // $("#mcis_server_info_connection").empty() + // $("#mcis_server_info_connection").append(vmProviderIcon) + + + // $("#server_info_text").text(' [ ' + vmName + ' / ' + mcisName + ' ]') + // $("#server_info_name").text(vmName + "/" + vmID) + // $("#server_info_desc").text(vmDescription) + // $("#server_info_os").text(operatingSystem) + // $("#server_info_start_time").text(startTime) + // $("#server_info_private_ip").text(privateIp) + // $("#server_info_cspVMID").text(data.cspViewVmDetail.IId.NameId) + +} + + +function clearRoleInfo() { + console.log("clearRoleInfo") + + + // $("#server_info_text").text("") + // $("#server_detail_info_text").text("") + + // $("#server_detail_view_server_status").val(""); + + // $("#server_info_status_icon_img").attr("src", ""); + +} + +//Tabulator Filter +//Define variables for input elements +var fieldEl = document.getElementById("filter-field"); +var typeEl = document.getElementById("filter-type"); +var valueEl = document.getElementById("filter-value"); + +// provider filtering / equel 고정 +function providerFilter(data) { + + // case type like, equal, not eual + // equal only +// if (typeEl.value == "=") { +// var vmCloudConnectionMap = webconsolejs["common/util"].calculateConnectionCount( +// data.vm +// ); +// var valueElValue = valueEl.value; +// if (valueElValue != "") { +// if (vmCloudConnectionMap.has(valueElValue)) { +// return true; +// } else { +// return false; +// } +// } + +// } else { +// return true; +// } + + return true +} + +//Trigger setFilter function with correct parameters +function updateFilter() { + var filterVal = fieldEl.options[fieldEl.selectedIndex].value; + var typeVal = typeEl.options[typeEl.selectedIndex].value; + + var filter = filterVal == "provider" ? providerFilter : filterVal; + + if (filterVal == "provider") { + typeEl.value = "="; + typeEl.disabled = true; + } else { + typeEl.disabled = false; + } + + if (filterVal) { + table.setFilter(filter, typeVal, valueEl.value); + } +} + +//Update filters on value change +document.getElementById("filter-field").addEventListener("change", updateFilter); +document.getElementById("filter-type").addEventListener("change", updateFilter); +document.getElementById("filter-value").addEventListener("keyup", updateFilter); + +//Clear filters on "Clear Filters" button click +document.getElementById("filter-clear").addEventListener("click", function () { + fieldEl.value = ""; + typeEl.value = "="; + valueEl.value = ""; + + table.clearFilter(); + +}); +// filter end + +////////////////////////////////////////////////////// END TABULATOR /////////////////////////////////////////////////// + +document.addEventListener("DOMContentLoaded", getRoleList); + +// workspace 목록조회 +async function getRoleList() { + console.log("getRoleList") + + const data = { + pathParams: {}, + }; + //var controller = "targetController=getmcislist" + var controller = "/api/" + "getrolelist"; + const response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + console.log("response ", response) + var roleList = response.data.responseData;//response 자체가 array임. + + getRoleListCallbackSuccess(roleList); +} + +// MCIS 목록 조회 후 화면에 Set + +function getRoleListCallbackSuccess(roleList) { + console.log("getRoleListCallbackSuccess"); + console.log("roleList : ", roleList); + table.setData(roleList); +} + +// 해당 mcis에서 상태값들을 count : 1개 mcis의 상태는 1개만 있으므로 running, stop, terminate 중 1개만 1, 나머지는 0 +// dashboard, mcis 에서 사용 + +///////////////////////////////////////////////////////////////////////////////////////////////// + + +/////////////// Role Handling ///////////////// +export async function deleteRole() { + console.log("deleteRole ", checked_array); + + if( checked_array.length == 0 || checked_array.length > 1){ + alert(" 1개만 선택 하세요 ") + return; + } + + for (const role of checked_array) { + console.log(role.id) + let data = { + pathParams: { + "roleId": role.id, + } + }; + let controller = "/api/" + "deleterolebyid"; + let response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + console.log(response) + if( response.data.status.code == "200" || response.data.status.code == "201" ){ + console.log("successfully deleted") + // 저장 후 role 목록 조회 + getRoleList() + } + + } +} + +function validRole(){ + var name = $("#create_name").val(); + var desc = $("#create_description").val(); + + return true +} +// role 저장 및 Create form 닫기 +export async function saveRole() { + console.log("add workspace") + + if( validRole() ){ + + var name = $("#create_name").val(); + var desc = $("#create_description").val(); + + const data = { + request: { + "name": name, + "description": desc, + } + } + + var controller = "/api/" + "createrole"; + const response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + console.log(response) + // save success 시 + if( response.data.status.code == "200" || response.data.status.code == "201" ){ + var div = document.getElementById("create_workspace"); + webconsolejs["partials/layout/navigatePages"].toggleElement(div) + + // 저장 후 workspace 목록 조회 + getRoleList() + } + + } +} + +// Info Form 닫기 +export function closeInfoForm(){ + console.log(" close form ") + + var div = document.getElementById("info_role"); + webconsolejs["partials/layout/navigatePages"].toggleElement(div) +} \ No newline at end of file diff --git a/mc_web_console_front/assets/js/pages/configuration/workspace/manage.js b/mc_web_console_front/assets/js/pages/configuration/workspace/manage.js new file mode 100644 index 00000000..325f396b --- /dev/null +++ b/mc_web_console_front/assets/js/pages/configuration/workspace/manage.js @@ -0,0 +1,429 @@ +import { TabulatorFull as Tabulator } from "tabulator-tables"; + +//// +// 모달 콜백 예제 : confirm 버튼을 눌렀을 때 호출될 callback 함수로 사용할 용도 +export function commoncallbac(val) { + alert(val); +} +//// + +////////// TABULATOR ////////// +var table; +var checked_array = []; +initWorkspaceTable(); +// function setTabulator( +// tableObjId, +// tableObjParamMap, +// columnsParams, +// isMultiSelect +// ) { +// var placeholder = "No Data"; +// var pagination = "local"; +// var paginationSize = 5; +// var paginationSizeSelector = [5, 10, 15, 20]; +// var movableColumns = true; +// var columnHeaderVertAlign = "middle"; +// var paginationCounter = "rows"; +// var layout = "fitColumns"; + +// if (tableObjParamMap.hasOwnProperty("placeholder")) { +// placeholder = tableObjParamMap.placeholder; +// } + +// if (tableObjParamMap.hasOwnProperty("pagination")) { +// pagination = tableObjParamMap.pagination; +// } + +// if (tableObjParamMap.hasOwnProperty("paginationSize")) { +// paginationSize = tableObjParamMap.paginationSize; +// } + +// if (tableObjParamMap.hasOwnProperty("paginationSizeSelector")) { +// paginationSizeSelector = tableObjParamMap.paginationSizeSelector; +// } + +// if (tableObjParamMap.hasOwnProperty("movableColumns")) { +// movableColumns = tableObjParamMap.movableColumns; +// } + +// if (tableObjParamMap.hasOwnProperty("columnHeaderVertAlign")) { +// columnHeaderVertAlign = tableObjParamMap.columnHeaderVertAlign; +// } + +// if (tableObjParamMap.hasOwnProperty("paginationCounter")) { +// paginationCounter = tableObjParamMap.paginationCounter; +// } + +// if (tableObjParamMap.hasOwnProperty("layout")) { +// layout = tableObjParamMap.layout; +// } + +// var tabulatorTable = new Tabulator("#" + tableObjId, { +// placeholder, +// pagination, +// paginationSize, +// paginationSizeSelector, +// movableColumns, +// columnHeaderVertAlign, +// paginationCounter, +// layout, +// columns: columnsParams, +// selectableRows: isMultiSelect == false ? 1 : true, +// }); + +// return tabulatorTable; +// } + +// Table 초기값 설정 +function initWorkspaceTable() { + + var tableObjParams = {}; + + var columns = [ + { + formatter: "rowSelection", + titleFormatter: "rowSelection", + vertAlign: "middle", + hozAlign: "center", + headerHozAlign: "center", + headerSort: false, + width: 60, + }, + { + title: "Id", + field: "id", + visible: false + }, + { + title: "Name", + field: "name", + vertAlign: "middle" + }, + { + title: "WorkspaceId", + field: "workspace_id", + visible: false + }, + ]; + + //table = setTabulator("workspacelist-table", tableObjParams, columns); + table = webconsolejs["common/util"].setTabulator("workspacelist-table", tableObjParams, columns); + + // 행 클릭 시 + table.on("rowClick", function (e, row) { + console.log(row) + //var workspaceID = row.getCell("id").getValue(); + //var workspaceID = row.getCell("workspaceId").getValue(); + var workspaceID = row.getCell("workspace_id").getValue(); + console.log("workspaceID", workspaceID) + // console.log("eeeee",e) + //clickListOfMcis(row.getCell("id").getValue()); + + getSelectedWorkspaceData(workspaceID) + + }); + + //  선택된 여러개 row에 대해 처리 + table.on("rowSelectionChanged", function (data, rows) { + checked_array = data + console.log("checked_array", checked_array) + console.log("rowsrows", data) + }); +} + +// 클릭한 workspace info 가져오기 +async function getSelectedWorkspaceData(workspaceID) { + const data = { + pathParams: { + workspaceId: workspaceID + } + } + + ///api/ws/workspace/{workspaceId} + var controller = "/api/" + "getworkspace"; + const response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + + console.log("response", response) + var workspaceData = response.data.responseData.responseData; + console.log("workspaceData", workspaceData) + + // SET MCIS Info + setWorkspaceInfoData(workspaceData) + + // Toggle MCIS Info + // var div = document.getElementById("info_workspace"); + // webconsolejs["partials/layout/navigatePages"].toggleElement(div) + window.location.hash = "info_workspace" + //window.location.hash = "" + +} + +// 클릭한 mcis info 세팅 +function setWorkspaceInfoData(workspaceData) { + console.log("setWorkspaceInfoData", workspaceData) + try { + var workspaceId = workspaceData.workspace_id; + console.log("workspaceId ", workspaceId) + var id = workspaceData.id; + console.log("id ", id) + var name = workspaceData.name; + console.log("name ", name) + var description = workspaceData.description; + console.log("description ", description) + + $("#info_id").val(""); + $("#info_name").val(""); + $("#info_workspace_desc").val(""); + $("#info_workspace_id").val(""); + + $("#info_id").val(id); + $("#info_name").val(name); + $("#info_workspace_desc").val(description); + $("#info_workspace_id").val(workspaceId); + + } catch (e) { + console.error(e); + } + + + +} + + +export async function workspaceDetailInfo(workspaceID) { + // Toggle MCIS Info + var div = document.getElementById("server_info"); + webconsolejs["partials/layout/navigatePages"].toggleElement(div) + + // 기존 값들 초기화 + //clearServerInfo(); + + var data = new Object(); + + // + //vm info + // $("#mcis_server_info_status_img").attr("src", "/assets/images/common/" + mcisStatusIcon) + // $("#mcis_server_info_connection").empty() + // $("#mcis_server_info_connection").append(vmProviderIcon) + + + // $("#server_info_text").text(' [ ' + vmName + ' / ' + mcisName + ' ]') + // $("#server_info_name").text(vmName + "/" + vmID) + // $("#server_info_desc").text(vmDescription) + // $("#server_info_os").text(operatingSystem) + // $("#server_info_start_time").text(startTime) + // $("#server_info_private_ip").text(privateIp) + // $("#server_info_cspVMID").text(data.cspViewVmDetail.IId.NameId) + +} + + +function clearWorkspaceInfo() { + console.log("clearWorkspaceInfo") + + + // $("#server_info_text").text("") + // $("#server_detail_info_text").text("") + + // $("#server_detail_view_server_status").val(""); + + // $("#server_info_status_icon_img").attr("src", ""); + +} + +//Tabulator Filter +//Define variables for input elements +var fieldEl = document.getElementById("filter-field"); +var typeEl = document.getElementById("filter-type"); +var valueEl = document.getElementById("filter-value"); + +// provider filtering / equel 고정 +function providerFilter(data) { + + // case type like, equal, not eual + // equal only + if (typeEl.value == "=") { + var vmCloudConnectionMap = webconsolejs["common/util"].calculateConnectionCount( + data.vm + ); + var valueElValue = valueEl.value; + if (valueElValue != "") { + if (vmCloudConnectionMap.has(valueElValue)) { + return true; + } else { + return false; + } + } + + } else { + return true; + } + + return true +} + +//Trigger setFilter function with correct parameters +function updateFilter() { + var filterVal = fieldEl.options[fieldEl.selectedIndex].value; + var typeVal = typeEl.options[typeEl.selectedIndex].value; + + var filter = filterVal == "provider" ? providerFilter : filterVal; + + if (filterVal == "provider") { + typeEl.value = "="; + typeEl.disabled = true; + } else { + typeEl.disabled = false; + } + + if (filterVal) { + table.setFilter(filter, typeVal, valueEl.value); + } +} + +//Update filters on value change +document.getElementById("filter-field").addEventListener("change", updateFilter); +document.getElementById("filter-type").addEventListener("change", updateFilter); +document.getElementById("filter-value").addEventListener("keyup", updateFilter); + +//Clear filters on "Clear Filters" button click +document.getElementById("filter-clear").addEventListener("click", function () { + fieldEl.value = ""; + typeEl.value = "="; + valueEl.value = ""; + + table.clearFilter(); + +}); +// filter end + +////////////////////////////////////////////////////// END TABULATOR /////////////////////////////////////////////////// + +document.addEventListener("DOMContentLoaded", getWorkspaceList); + +// workspace 목록조회 +async function getWorkspaceList() { + + console.log("getWorkspaceList") + console.log($("#select-current-workspace") ); + var selectedWs = $("#select-current-workspace").val()// + + console.log("~~~~~~~ " , selectedWs) + + + // var namespace = webconsolejs["common/util"].getCurrentProject() + // nsid = namespace.Name + + const data = { + pathParams: { +// nsId: nsid, + }, + }; + //var controller = "targetController=getmcislist" + var controller = "/api/" + "getworkspacelist"; + const response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + console.log("response ", response) + //var workspaceList = response.data.responseData;//response 자체가 array임. + var workspaceList = response.data.responseData;//response 자체가 array임. + + getWorkspaceListCallbackSuccess(workspaceList); +} + +// MCIS 목록 조회 후 화면에 Set + +function getWorkspaceListCallbackSuccess(workspaceList) { + console.log("getWorkspaceListCallbackSuccess"); + console.log("workspaceList : ", workspaceList); + table.setData(workspaceList); +} + +// 해당 mcis에서 상태값들을 count : 1개 mcis의 상태는 1개만 있으므로 running, stop, terminate 중 1개만 1, 나머지는 0 +// dashboard, mcis 에서 사용 + +///////////////////////////////////////////////////////////////////////////////////////////////// + + +/////////////// Workspace Handling ///////////////// +export async function deleteWorkspace() { + console.log("deleteWorkspace ", checked_array); + + if( checked_array.length == 0 || checked_array.length > 1){ + alert(" 1개만 선택 하세요 ") + return; + } + + for (const workspace of checked_array) { + console.log(workspace.id) + let data = { + pathParams: { + "workspaceId": workspace.workspace_id, + } + }; + let controller = "/api/" + "deleteworkspace"; + let response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + console.log(response) + if( response.data.status.code == "200" || response.data.status.code == "201" ){ + console.log("successfully deleted") + // 저장 후 workspace 목록 조회 + getWorkspaceList() + } + + } +} + +function validWorkspace(){ + var name = $("#create_name").val(); + var desc = $("#create_description").val(); + + return true +} +// workspace 저장 및 Create form 닫기 +export async function saveWorkspace() { + console.log("add workspace") + + if( validWorkspace() ){ + + var name = $("#create_name").val(); + var desc = $("#create_description").val(); + + const data = { + request: { + "name": name, + "description": desc, + } + } + + var controller = "/api/" + "createworkspace"; + const response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + console.log(response) + // save success 시 + if( response.data.status.code == "200" || response.data.status.code == "201" ){ + var div = document.getElementById("create_workspace"); + webconsolejs["partials/layout/navigatePages"].toggleElement(div) + + // 저장 후 workspace 목록 조회 + getWorkspaceList() + } + + } +} + +// Info Form 닫기 +export function closeInfoForm(){ + console.log(" close form ") + + var div = document.getElementById("info_workspace"); + webconsolejs["partials/layout/navigatePages"].toggleElement(div) +} \ No newline at end of file diff --git a/mc_web_console_front/assets/js/pages/operation/manage/mcis.js b/mc_web_console_front/assets/js/pages/operation/manage/mcis.js new file mode 100644 index 00000000..d997b0b5 --- /dev/null +++ b/mc_web_console_front/assets/js/pages/operation/manage/mcis.js @@ -0,0 +1,1222 @@ +import { TabulatorFull as Tabulator } from "tabulator-tables"; + +//// +// 모달 콜백 예제 +export function commoncallbac(val) { + alert(val); +} +//// + +var totalMcisListObj = new Object(); +export var selectedMcisObj = new Object(); +export var nsid = ""; +var totalMcisStatusMap = new Map(); +var totalVmStatusMap = new Map(); +// var totalCloudConnectionMap = new Map(); + +var mcisListTable; +var checked_array = []; +initMcisTable(); // init tabulator + +//DOMContentLoaded 는 Page에서 1개만. +// init + 파일명 () : ex) initMcis() 를 호출하도록 한다. +document.addEventListener("DOMContentLoaded", initMcis); + +// 해당 화면에서 최초 설정하는 function +//로드 시 prj 값 받아와 getMcisList 호출 +async function initMcis() { + console.log("initMcis") + + ////////////////////// partials init functions/////////////////////////////////////// + try{ + webconsolejs["partials/operation/manage/mciscreate"].initMcisCreate();//McisCreate을 Partial로 가지고 있음. + }catch(e){ + console.log(e); + } + ////////////////////// partials init functions end /////////////////////////////////////// + + + ////////////////////// set workspace list, project list at Navbar/////////////////////////////////////// + var workspaceIdProjectId = webconsolejs["partials/layout/navbar"].workspaceProjectInit(); + + ////////////////////// set workspace list, project list at Navbar end ////////////////////////////////// + + //console.log("workspaceIdProjectId=", workspaceIdProjectId) + if (workspaceIdProjectId.projectId != "") { + getMcisList();// project가 선택되어 있으면 mcis목록을 조회한다. + } + + ////////////////////// 받은 mcisId가 있으면 해당 mcisId를 set하고 조회한다. //////////////// + // 외부(dashboard)에서 받아온 mcisID가 있으면 MCIS INFO 이동 + // 현재 브라우저의 URL + const url = window.location.href; + const urlObj = new URL(url); + // URLSearchParams 객체 생성 + const params = new URLSearchParams(urlObj.search); + // mcisID 파라미터 값 추출 + const selectedMcisID = params.get('mcisID'); + + console.log('selectedMcisID:', selectedMcisID); // 출력: mcisID의 값 (예: com) + if (selectedMcisID != undefined) { + getSelectedMcisData(selectedMcisID) + } + //////////////////// mcisId를 set하고 조회 완료. //////////////// + +} + +// navBar에 있는 object인데 직접 handling( onchange) +$("#select-current-workspace").on('change', async function () { + webconsolejs["partials/layout/navbar"].setWorkspaceChanged(this.value); +}) + +// navBar에 있는 object인데 직접 handling( onchange) +$("#select-current-project").on('change', async function () { + getMcisList(); +}) + +// 받아온 project(namespace)로 McisList GET +async function getMcisList() { + console.log("getMcisList") + var projectId = $("#select-current-project").val() + var projectName = $('#select-current-project').find('option:selected').text(); + // var projectName = $("#select-current-project").text() + // $('#select-current-project').find('option:selected').each(function() { + // projectName = $(this).text(); + // }); + console.log("projectId", projectId) + console.log("projectName", projectName) + + if( projectId == ""){ + console.log("Project has not set") + return; + } + nsid = projectName + + // nsid = "project1"; + + var data = { + pathParams: { + nsId: nsid, + // nsId: "testns01", + }, + }; + //var controller = "targetController=getmcislist" + var controller = "/api/" + "getmcislist"; + const response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ) + + // if (response.response.data.status.code != 200 && response.response.data.status.code != 201) { + // alert(response.response.data.responseData.message) + // } else { + var mcisList = response.data.responseData; + console.log("mcisList : ", mcisList); + + // 호출 성공 시 + getMcisListCallbackSuccess(nsid, mcisList); + // } +} + +// getMcisList 호출 성공 시 +function getMcisListCallbackSuccess(caller, mcisList) { + console.log("getMcisListCallbackSuccess"); + + totalMcisListObj = mcisList.mcis; + console.log("total mcis : ", totalMcisListObj); + mcisListTable.setData(totalMcisListObj); + setToTalMcisStatus(); // mcis상태 표시 + setTotalVmStatus(); // mcis 의 vm들 상태표시 + // setTotalConnection();// Mcis의 provider별 connection 표시 + + // displayMcisDashboard(); + + // // setMap();// MCIS를 가져와서 화면에 뿌려지면 vm정보가 있으므로 Map그리기 + + // AjaxLoadingShow(false); +} + +// 클릭한 mcis info 가져오기 +// 표에서 선택된 McisId 받아옴 +async function getSelectedMcisData(mcisID) { + + const data = { + pathParams: { + nsId: nsid, + // nsId: "testns01", + mcisId: mcisID + } + } + + var controller = "/api/" + "getmcis"; + const response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + + console.log("response", response) + var mcisData = response.data.responseData; + console.log("mcisdata", mcisData) + + // SET MCIS Info page + setMcisInfoData(mcisData) + + // Toggle MCIS Info + var div = document.getElementById("mcis_info"); + webconsolejs["partials/layout/navigatePages"].toggleElement(div) + +} + +// 클릭한 mcis의 info값 세팅 +function setMcisInfoData(mcisData) { + // console.log("setMcisInfoData", mcisIndex) + try { + var mcisID = mcisData.id; + var mcisName = mcisData.name; + var mcisDescription = mcisData.description; + var mcisStatus = mcisData.status; + var mcisDispStatus = getMcisStatusDisp(mcisStatus); + var mcisStatusIcon = getMcisStatusIcon(mcisDispStatus); + var mcisProviderNames = getMCISInfoProviderNames(mcisData); //MCIS에 사용 된 provider + var totalvmCount = mcisData.vm.length; //mcis의 vm개수 + + console.log("totalvmCount", totalvmCount) + + $("#mcis_info_text").text(" [ " + mcisName + " ]") + $("#mcis_server_info_status").empty(); + $("#mcis_server_info_status").text(" [ " + mcisName + " ]") + $("#mcis_server_info_count").text(" Server(" + totalvmCount + ")") + + + $("#mcis_info_status_img").attr("src", "/assets/images/common/" + mcisStatusIcon) + $("#mcis_info_name").text(mcisName + " / " + mcisID) + $("#mcis_info_description").text(mcisDescription) + $("#mcis_info_status").text(mcisStatus) + $("#mcis_info_cloud_connection").empty() + $("#mcis_info_cloud_connection").append(mcisProviderNames) + + } catch (e) { + console.error(e); + } + + // TODO : mcis info로 cursor 이동 + // vm상태별로 icon 표시한다 + displayServerStatusList(mcisID, mcisData.vm) + +} + +// vm 상태별 icon으로 표시 +// Server List / Status VM리스트 +function displayServerStatusList(mcisID, vmList) { + console.log("displayServerStatusList") + + var mcisName = mcisID; + var vmLi = ""; + vmList.sort(); + for (var vmIndex in vmList) { + var aVm = vmList[vmIndex] + + var vmID = aVm.id; + var vmName = aVm.name; + var vmStatus = aVm.status; + var vmDispStatus = getVmStatusDisp(vmStatus); // vmStatus set + var vmStatusClass = getVmStatusClass(vmDispStatus) // vmStatus 별로 상태 색상 set + + vmLi += '
  • ' + vmName + '
  • '; + + }// end of mcis loop + // totalvmCount = vmCount + + // console.log(vmLi) + $("#mcis_server_info_box").empty(); + $("#mcis_server_info_box").append(vmLi); + //Manage MCIS Server List on/off + +} + +// Server List / Status VM 리스트에서 +// VM 한 개 클릭시 vm의 세부 정보 +export async function vmDetailInfo(mcisID, mcisName, vmID) { + // Toggle MCIS Info + var div = document.getElementById("server_info"); + webconsolejs["partials/layout/navigatePages"].toggleElement(div) + + console.log("vmDetailInfo") + console.log("mcisID : ", mcisID) + console.log("mcisName : ", mcisName) + console.log("vmID : ", vmID) + + clearServerInfo(); + + var aMcis = new Object(); + for (var mcisIndex in totalMcisListObj) { + var tempMcis = totalMcisListObj[mcisIndex] + if (mcisID == tempMcis.id) { + aMcis = tempMcis; + break; + } + }// end of mcis loop + console.log("aMcis", aMcis); + var vmList = aMcis.vm; + var vmExist = false + var data = new Object(); + for (var vmIndex in vmList) { + var aVm = vmList[vmIndex] + if (vmID == aVm.id) { + //aVm = vmData; + data = aVm; + vmExist = true + console.log("aVm", aVm) + break; + } + } + if (!vmExist) { + console.log("vm is not exist"); + console.log(vmList) + } + console.log("selected Vm"); + console.log("selected vm data : ", data); + var vmId = data.id; + var vmName = data.name; + var vmStatus = data.status; + var vmDescription = data.description; + var vmPublicIp = data.publicIP == undefined ? "" : data.publicIP; + console.log("vmPublicIp", vmPublicIp) + var vmSshKeyID = data.sshKeyId; + var imageId = data.imageId + var operatingSystem = await getCommonVmImageInfo(imageId) + var startTime = data.cspViewVmDetail.StartTime + var privateIp = data.privateIP + var securityGroupID = data.securityGroupIds[0]; + var providerName = data.connectionConfig.providerName + var vmProviderIcon = "" + vmProviderIcon += + '' +
+    providerName +
+    ''; + + var vmDispStatus = getMcisStatusDisp(vmStatus); + var mcisStatusIcon = getMcisStatusIcon(vmDispStatus); + // var mcisProviderNames = getMCISInfoProviderNames(data);//MCIS에 사용 된 provider + + //vm info + $("#mcis_server_info_status_img").attr("src", "/assets/images/common/" + mcisStatusIcon) + $("#mcis_server_info_connection").empty() + $("#mcis_server_info_connection").append(vmProviderIcon) + + + $("#server_info_text").text(' [ ' + vmName + ' / ' + mcisName + ' ]') + $("#server_info_name").text(vmName + "/" + vmID) + $("#server_info_desc").text(vmDescription) + $("#server_info_os").text(operatingSystem) + $("#server_info_start_time").text(startTime) + $("#server_info_private_ip").text(privateIp) + $("#server_info_cspVMID").text(data.cspViewVmDetail.IId.NameId) + + // ip information + $("#server_info_public_ip").text(vmPublicIp) + $("#server_detail_info_public_ip_text").text("Public IP : " + vmPublicIp) + $("#server_info_public_dns").text(data.publicDNS) + // $("#server_info_private_ip").val(data.privateIP) + $("#server_info_private_dns").text(data.privateDNS) + + $("#server_detail_view_public_ip").text(vmPublicIp) + $("#server_detail_view_public_dns").text(data.publicDNS) + $("#server_detail_view_private_ip").text(data.privateIP) + $("#server_detail_view_private_dns").text(data.privateDNS) + + // detail tab + $("#server_detail_info_text").text(' [' + vmName + '/' + mcisName + ']') + $("#server_detail_view_server_id").text(vmId) + $("#server_detail_view_server_status").text(vmStatus); + $("#server_detail_view_public_dns").text(data.publicDNS) + $("#server_detail_view_public_ip").text(vmPublicIp) + $("#server_detail_view_private_ip").text(data.privateIP) + $("#server_detail_view_security_group_text").text(securityGroupID) + $("#server_detail_view_private_dns").text(data.privateDNS) + $("#server_detail_view_private_ip").text(data.privateIP) + $("#server_detail_view_image_id").text(imageId) + $("#server_detail_view_os").text(operatingSystem); + $("#server_detail_view_user_id_pass").text(data.vmUserAccount + "/ *** ") + + + + + var region = data.region.Region + + var zone = data.region.Zone + // $("#manage_mcis_popup_public_ip").val(vmPublicIp) + + // connection tab + var connectionName = data.connectionName + var credentialName = data.connectionConfig.credentialName + var driverName = data.connectionConfig.driverName + var locationInfo = data.location; + var cloudType = locationInfo.cloudType; + + $("#server_connection_view_connection_name").text(connectionName) + $("#server_connection_view_credential_name").text(credentialName) + $("#server_connection_view_csp").text(providerName) + $("#server_connection_view_driver_name").text(driverName) + $("#server_connection_view_region").text(providerName + " : " + region) + $("#server_connection_view_zone").text(zone) + + + + // $("#server_info_csp_icon").empty() + // $("#server_info_csp_icon").append('') + // $("#server_connection_view_csp").val(cloudType) + // $("#manage_mcis_popup_csp").val(cloudType) + + + // var latitude = locationInfo.latitude; + // var longitude = locationInfo.longitude; + // var briefAddr = locationInfo.briefAddr; + // var nativeRegion = locationInfo.nativeRegion; + + // if (locationInfo) { + // $("#server_location_latitude").val(latitude) + // $("#server_location_longitude").val(longitude) + + // } + // region zone locate + $("#server_info_region").text(providerName + ":" + region) + $("#server_info_zone").text(zone) + + + $("#server_detail_view_region").text(providerName + " : " + region) + $("#server_detail_view_zone").text(zone) + + // connection name + var connectionName = data.connectionName; + $("#server_info_connection_name").text(connectionName) + + var vmDetail = data.cspViewVmDetail; + var vmDetailKeyValueList = vmDetail.KeyValueList + var architecture = ""; + + if (vmDetailKeyValueList) { + for (var i = 0; i < vmDetailKeyValueList.length; i++) { + if (vmDetailKeyValueList[i].key === "Architecture") { + architecture = vmDetailKeyValueList[i].value; + break; // 찾았으므로 반복문을 종료 + } + } + } + var vmSpecName = vmDetail.VMSpecName + var vpcId = vmDetail.VpcIID.NameId + var vpcSystemId = vmDetail.VpcIID.SystemId + var subnetId = vmDetail.SubnetIID.NameId + var subnetSystemId = vmDetail.SubnetIID.SystemId + var eth = vmDetail.NetworkInterface + + + + $("#server_info_archi").text(architecture) + // detail tab + $("#server_detail_view_archi").text(architecture) + $("#server_detail_view_vpc_id").text(vpcId + "(" + vpcSystemId + ")") + $("#server_detail_view_subnet_id").text(subnetId + "(" + subnetSystemId + ")") + $("#server_detail_view_eth").text(eth) + $("#server_detail_view_root_device_type").text(vmDetail.RootDiskType); + $("#server_detail_view_root_device").text(vmDetail.RootDeviceName); + $("#server_detail_view_keypair_name").text(vmDetail.KeyPairIId.NameId) + $("#server_detail_view_access_id_pass").text(vmDetail.VMUserId + "/ *** ") + + + // server spec + // var vmSecName = data.VmSpecName + $("#server_info_vmspec_name").text(vmSpecName) + $("#server_detail_view_server_spec").text(vmSpecName) // detail tab + + +} + +// VM의 OS를 가져온다 +// common에 있는 이미지 사용 (system-purpose-common-ns) +// TODO: custom 일 때 처리 +async function getCommonVmImageInfo(imageId) { + + // endPoint := "/ns/{nsId}/resources/image/{imageId}" + + // "/ns/system-purpose-common-ns/resources/image/{imageId}" + + const data = { + pathParams: { + // nsId: nsid, + imageId: imageId + } + } + + var controller = "/api/" + "getimageid"; + const response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + + var operatingSystem = response.data.responseData.guestOS + console.log("OperatingSystem : ", operatingSystem) + return operatingSystem +} + +// vm 세부 정보 초기화 +function clearServerInfo() { + console.log("clearServerInfo") + // $("#vm_id").val(""); + // $("#vm_name").val(""); + + // $("#manage_mcis_popup_vm_id").val("") + // $("#manage_mcis_popup_mcis_id").val("") + // $("#manage_mcis_popup_sshkey_name").val("") + + $("#server_info_text").text("") + $("#server_detail_info_text").text("") + + $("#server_detail_view_server_status").val(""); + + // $("#server_info_status_icon_img").attr("src", ""); + + $("#server_info_name").val("") + $("#server_info_desc").val("") + + // ip information + $("#server_info_public_ip").val("") + $("#server_detail_info_public_ip_text").text("") + $("#server_info_public_dns").val("") + $("#server_info_private_ip").val("") + $("#server_info_private_dns").val("") + + $("#server_detail_view_public_ip").val("") + $("#server_detail_view_public_dns").val("") + $("#server_detail_view_private_ip").val("") + $("#server_detail_view_private_dns").val("") + + $("#manage_mcis_popup_public_ip").val("") + + // connection tab + $("#server_info_csp_icon").empty() + $("#server_connection_view_csp").val("") + $("#manage_mcis_popup_csp").val("") + + $("#latitude").val("") + $("#longitude").val("") + + $("#server_info_region").val("") + $("#server_info_zone").val("") + + $("#server_detail_view_region").val("") + $("#server_detail_view_zone").val("") + + $("#server_connection_view_region").val("") + $("#server_connection_view_zone").val("") + + $("#server_info_connection_name").val("") + $("#server_connection_view_connection_name").val("") + + $("#server_connection_view_credential_name").val("") + $("#server_connection_view_driver_name").val("") + + $("#server_info_archi").val("") + $("#server_detail_view_archi").val("") + + $("#server_info_vmspec_name").val("") + $("#server_detail_view_server_spec").text("") + + $("#server_info_start_time").val("") + + $("#server_detail_view_server_id").val("") + + $("#server_detail_view_image_id").text("") + + $("#server_detail_view_vpc_id").text("") + + $("#server_detail_view_subnet_id").text("") + $("#server_detail_view_eth").val("") + + // user account + $("#server_detail_view_access_id_pass").val("") + $("#server_detail_view_user_id_pass").val("") + // $("#manage_mcis_popup_user_name").val("") + + $("#block_device_section").empty() + // $("#attachedDiskList").empty() + + $("#server_detail_view_root_device_type").val(""); + $("#server_detail_view_root_device").val(""); + // $("#server_detail_disk_id").val(""); + // $("#server_detail_disk_mcis_id").val(""); + // $("#server_detail_disk_vm_id").val(""); + + $("#server_detail_view_security_group").empty() + $("#server_detail_view_keypair_name").val("") + $("#server_info_cspVMID").val("") + + // $("#selected_mcis_id").val(""); + // $("#selected_vm_id").val(""); + + // $("#exportFileName").val(""); + // $("#exportScript").val(""); +} + +// MCIS 상태별 이미지 추가 +function getMcisStatusIcon(mcisDispStatus) { + var mcisStatusIcon = ""; + if (mcisDispStatus == "running") { + mcisStatusIcon = "icon_running.svg" + } else if (mcisDispStatus == "include") { + mcisStatusIcon = "icon_stop.svg" + } else if (mcisDispStatus == "suspended") { + mcisStatusIcon = "icon_stop.svg" + } else if (mcisDispStatus == "terminate") { + mcisStatusIcon = "icon_terminate.svg" + } else { + mcisStatusIcon = "icon_stop.svg" + } + return mcisStatusIcon +} + +// MCIS Info에 Set providerName +function getMCISInfoProviderNames(mcisData) { + + var mcisProviderNames = ""; + var vmCloudConnectionMap = webconsolejs["common/util"].calculateConnectionCount( + mcisData.vm + ); + console.log("vmCloudConnectionMap", vmCloudConnectionMap) + if (vmCloudConnectionMap) { + vmCloudConnectionMap.forEach((value, key) => { + mcisProviderNames += + '' +
+        key +
+        ''; + }); + } + return mcisProviderNames +} + +// function displayColumn(table) { +// console.log("displayColumndisplayColumndisplayColumn") +// $(".display-column").on("click", function () { +// if ($(this).children("input:checkbox").is(":checked")) { +// $(this).children(".material-icons").text("visibility"); +// table.showColumn($(this).data("column")); +// } else { +// $(this).children(".material-icons").text("visibility_off"); +// table.hideColumn($(this).data("column")); +// } +// }); +// } + +// function getCommonMcisDataCallbackSuccess(caller, data, mcisID) { +// if (caller == "mcisexport") { + +// var mcisIndex = 0; +// // console.log("mcisScriptExport start " + mcisID) +// // console.log(data); +// $("[id^='mcisID']").each(function () { +// if (mcisID == $(this).val()) { +// mcisIndex = $(this).attr("id").replace("mcisID", "") +// return false; +// } +// }); +// // +// // var mcisNameVal = $("#m_mcisName_" + mcisIndex).val(); +// var mcisCreateScript = JSON.stringify(data) +// console.log(mcisCreateScript) +// // $("#m_exportFileName_" + mcisIndex).val(mcisNameVal); +// // $("#m_mcisExportScript_" + mcisIndex).val(mcisCreateScript); +// $("#exportFileName").val(data.id); +// $("#exportScript").val(mcisCreateScript); + +// saveToMcisAsJsonFile(mcisIndex); +// } else if (caller == "refreshmcisdata") { +// console.log(" gogo ") +// // var mcisID = $("#selected_mcis_id").val(); +// // var mcisIndex = $("#selected_mcis_index").val(); +// // console.log("setMcisData " + mcisIndex) +// // setMcisData(data, mcisIndex); +// // console.log("clock List of Mcis ") +// // clickListOfMcis(mcisID,mcisIndex); + +// updateMcisData(data, mcisID); +// } +// } + +// mcis 상태 표시 +function setToTalMcisStatus() { + console.log("setToTalMcisStatus"); + try { + for (var mcisIndex in totalMcisListObj) { + var aMcis = totalMcisListObj[mcisIndex]; + + var aMcisStatusCountMap = calculateMcisStatusCount(aMcis); + console.log("aMcis.id : ", aMcis.id); + console.log("mcisStatusMap ::: ", aMcisStatusCountMap); + totalMcisStatusMap.set(aMcis.id, aMcisStatusCountMap); + } + } catch (e) { + console.log("mcis status error", e); + } + displayMcisStatusArea(); +} + +// 해당 mcis에서 상태값들을 count : 1개 mcis의 상태는 1개만 있으므로 running, stop, terminate 중 1개만 1, 나머지는 0 +// dashboard, mcis 에서 사용 +function calculateMcisStatusCount(mcisData) { + console.log("calculateMcisStatusCount"); + + console.log("mcisData : ", mcisData); + var mcisStatusCountMap = new Map(); + mcisStatusCountMap.set("running", 0); + mcisStatusCountMap.set("stop", 0); // partial 도 stop으로 보고있음. + mcisStatusCountMap.set("terminate", 0); + try { + var mcisStatus = mcisData.status; + var mcisDispStatus = getMcisStatusDisp(mcisStatus); // 화면 표시용 status + + if (mcisStatus != "") { + // mcis status 가 없는 경우는 skip + if (mcisStatusCountMap.has(mcisDispStatus)) { + mcisStatusCountMap.set( + mcisDispStatus, + mcisStatusCountMap.get(mcisDispStatus) + 1 + ); + } + } + } catch (e) { + console.log("mcis status error", e); + } + // console.log(mcisStatusCountMap); + return mcisStatusCountMap; +} + +// Mcis 목록에서 vmStatus만 처리 : 화면표시는 display function에서 +// vm 상태 표시 +function setTotalVmStatus() { + console.log("setTotalVmstatus") + try { + for (var mcisIndex in totalMcisListObj) { + var aMcis = totalMcisListObj[mcisIndex]; + console.log("aMcis : ", aMcis); + var vmStatusCountMap = calculateVmStatusCount(aMcis); + totalVmStatusMap.set(aMcis.id, vmStatusCountMap); + } + } catch (e) { + console.log("mcis status error"); + } + displayVmStatusArea(); +} + +// mcis status display +function displayMcisStatusArea() { + console.log("displayMcisStatusArea"); + var sumMcisCnt = 0; + var sumMcisRunningCnt = 0; + var sumMcisStopCnt = 0; + var sumMcisTerminateCnt = 0; + totalMcisStatusMap.forEach((value, key) => { + var statusRunning = value.get("running"); + var statusStop = value.get("stop"); + var statusTerminate = value.get("terminate"); + sumMcisRunningCnt += statusRunning; + sumMcisStopCnt += statusStop; + sumMcisTerminateCnt += statusTerminate; + console.log("totalMcisStatusMap :: ", key, value); + }); + sumMcisCnt = sumMcisRunningCnt + sumMcisStopCnt + sumMcisTerminateCnt; + + $("#total_mcis").text(sumMcisCnt); + $("#mcis_status_running").text(sumMcisRunningCnt); + $("#mcis_status_stopped").text(sumMcisStopCnt); + $("#mcis_status_terminated").text(sumMcisTerminateCnt); + console.log("displayMcisStatusArea "); + console.log("running status count ", $("#mcis_status_running").text()); +} + +// 해당 vm에서 상태값들을 count : 1개 mcis의 상태는 1개만 있으므로 running, stop, terminate 중 1개만 1, 나머지는 0 +function calculateVmStatusCount(aMcis) { + console.log("calculateVmStatusCount") + // console.log("calculateVmStatusCount") + // console.log(vmList) + var sumVmCnt = 0; + var vmStatusCountMap = new Map(); + vmStatusCountMap.set("running", 0); + vmStatusCountMap.set("stop", 0); // partial 도 stop으로 보고있음. + vmStatusCountMap.set("terminate", 0); + + try { + if (aMcis.statusCount) { + console.log("statusCount part", aMcis); + var statusCountObj = aMcis.statusCount; + console.log(statusCountObj); + var countCreating = statusCountObj.countCreating; + var countFailed = statusCountObj.countFailed; + var countRebooting = statusCountObj.countRebooting; + var countResuming = statusCountObj.countResuming; + var countRunning = statusCountObj.countRunning; + var countSuspended = statusCountObj.countSuspended; + var countSuspending = statusCountObj.countSuspending; + var countTerminated = statusCountObj.countTerminated; + var countTerminating = statusCountObj.countTerminating; + var countTotal = statusCountObj.countTotal; + var countUndefined = statusCountObj.countUndefined; + + var sumEtc = + Number(countCreating) + + Number(countFailed) + + Number(countRebooting) + + Number(countResuming) + + Number(countSuspending) + + Number(countTerminated) + + Number(countTerminating) + + Number(countUndefined); + + vmStatusCountMap.set("running", Number(countRunning)); + vmStatusCountMap.set("stop", Number(countSuspended)); // partial 도 stop으로 보고있음. + vmStatusCountMap.set("terminate", sumEtc); + } else if (aMcis.vm) { + console.log("statusCount part list part"); + vmList = aMcis.vm; + for (var vmIndex in vmList) { + var aVm = vmList[vmIndex]; + var vmStatus = aVm.status; + var vmDispStatus = getVmStatusDisp(vmStatus); + + if (vmStatus != "") { + // vm status 가 없는 경우는 skip + if (vmStatusCountMap.has(vmDispStatus)) { + vmStatusCountMap.set( + vmDispStatus, + vmStatusCountMap.get(vmDispStatus) + 1 + ); + } + } + } + } + } catch (e) { + console.log("mcis status error"); + } + return vmStatusCountMap; +} + +// 화면 표시용 status +function getMcisStatusDisp(mcisFullStatus) { + console.log("getMcisStatus " + mcisFullStatus); + var statusArr = mcisFullStatus.split("-"); + var returnStatus = statusArr[0].toLowerCase(); + + if (mcisFullStatus.toLowerCase().indexOf("running") > -1) { + returnStatus = "running"; + } else if (mcisFullStatus.toLowerCase().indexOf("suspend") > -1) { + returnStatus = "stop"; + } else if (mcisFullStatus.toLowerCase().indexOf("terminate") > -1) { + returnStatus = "terminate"; + // TODO : partial도 있는데... 처리를 어떻게 하지?? + } else { + returnStatus = "terminate"; + } + console.log("after status " + returnStatus); + return returnStatus; +} + +// vm status display +function displayVmStatusArea() { + var sumVmCnt = 0; + var sumVmRunningCnt = 0; + var sumVmStopCnt = 0; + var sumVmTerminateCnt = 0; + totalVmStatusMap.forEach((value, key) => { + var statusRunning = value.get("running"); + var statusStop = value.get("stop"); + var statusTerminate = value.get("terminate"); + sumVmRunningCnt += statusRunning; + sumVmStopCnt += statusStop; + sumVmTerminateCnt += statusTerminate; + }); + sumVmCnt = sumVmRunningCnt + sumVmStopCnt + sumVmTerminateCnt; + $("#total_vm").text(sumVmCnt); + $("#vm_status_running").text(sumVmRunningCnt); + $("#vm_status_stopped").text(sumVmStopCnt); + $("#vm_status_terminated").text(sumVmTerminateCnt); +} + +// mcisLifeCycle 제어 option : reboot / suspend / resume / terminate +export function mcisLifeCycle(type) { + console.log("mcisLifeCycle option : ", type) + console.log("selected mcis : ", checked_array) + + for (const mcis of checked_array) { + console.log(mcis.id) + let data = { + pathParams: { + nsId: nsid, + mcisId: mcis.id, + }, + queryParams: { + "action": type + } + }; + let controller = "/api/" + "controllifecycle"; + let response = webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + console.log(response) + } +} + +// VM 상태를 UI에서 표현하는 방식으로 변경 +function getVmStatusDisp(vmFullStatus) { + console.log("getVmStatusDisp " + vmFullStatus); + var returnVmStatus = vmFullStatus.toLowerCase() // 소문자로 변환 + + const VM_STATUS_RUNNING = "running" + const VM_STATUS_STOPPED = "stop" + const VM_STATUS_RESUMING = "resuming"; + const VM_STATUS_INCLUDE = "include" + const VM_STATUS_SUSPENDED = "suspended" + const VM_STATUS_TERMINATED = "terminated" + const VM_STATUS_FAILED = "failed" + + if (returnVmStatus == VM_STATUS_RUNNING) { + returnVmStatus = "running" + } else if (returnVmStatus == VM_STATUS_TERMINATED) { + returnVmStatus = "terminate" + } else if (returnVmStatus == VM_STATUS_FAILED) { + returnVmStatus = "terminate" + } else { + returnVmStatus = "stop" + } + return returnVmStatus +} + +// VM 상태 별로 색 설정 +function getVmStatusClass(vmDispStatus) { + var vmStatusClass = "bg-info"; + if (vmDispStatus == "running") { + vmStatusClass = "bg-info" + } else if (vmDispStatus == "include") { + vmStatusClass = "bg-red" + } else if (vmDispStatus == "suspended") { + vmStatusClass = "bg-red" + } else if (vmDispStatus == "terminated") { + vmStatusClass = "bg-secondary" + } else { + vmStatusClass = "bg-secondary" + } + return vmStatusClass; +} + +////////////////////////////////////////////////////// TABULATOR Start ////////////////////////////////////////////////////// +// tabulator 행, 열, 기본값 설정 +// table이 n개 가능하므로 개별 tabulator 정의 : 원리 util 안에 setTabulator있음. +function setMcisTabulator( + tableObjId, + tableObjParamMap, + columnsParams, + isMultiSelect +) { + var placeholder = "No Data"; + var pagination = "local"; + var paginationSize = 5; + var paginationSizeSelector = [5, 10, 15, 20]; + var movableColumns = true; + var columnHeaderVertAlign = "middle"; + var paginationCounter = "rows"; + var layout = "fitColumns"; + + if (tableObjParamMap.hasOwnProperty("placeholder")) { + placeholder = tableObjParamMap.placeholder; + } + + if (tableObjParamMap.hasOwnProperty("pagination")) { + pagination = tableObjParamMap.pagination; + } + + if (tableObjParamMap.hasOwnProperty("paginationSize")) { + paginationSize = tableObjParamMap.paginationSize; + } + + if (tableObjParamMap.hasOwnProperty("paginationSizeSelector")) { + paginationSizeSelector = tableObjParamMap.paginationSizeSelector; + } + + if (tableObjParamMap.hasOwnProperty("movableColumns")) { + movableColumns = tableObjParamMap.movableColumns; + } + + if (tableObjParamMap.hasOwnProperty("columnHeaderVertAlign")) { + columnHeaderVertAlign = tableObjParamMap.columnHeaderVertAlign; + } + + if (tableObjParamMap.hasOwnProperty("paginationCounter")) { + paginationCounter = tableObjParamMap.paginationCounter; + } + + if (tableObjParamMap.hasOwnProperty("layout")) { + layout = tableObjParamMap.layout; + } + + var tabulatorTable = new Tabulator("#" + tableObjId, { + //ajaxURL:"http://localhost:3000/operations/mcismng?option=status", + placeholder, + pagination, + paginationSize, + paginationSizeSelector, + movableColumns, + columnHeaderVertAlign, + paginationCounter, + layout, + columns: columnsParams, + selectableRows: isMultiSelect == false ? 1 : true, + }); + + return tabulatorTable; +} + +// tabulator Table 초기값 설정 +function initMcisTable() { + + var tableObjParams = {}; + + var columns = [ + { + formatter: "rowSelection", + titleFormatter: "rowSelection", + vertAlign: "middle", + hozAlign: "center", + headerHozAlign: "center", + headerSort: false, + width: 60, + }, + { + title: "Status", + field: "status", + formatter: statusFormatter, + vertAlign: "middle", + hozAlign: "center", + headerHozAlign: "center", + headerSort: false, + maxWidth: 100, + }, + { + title: "Id", + field: "id", + visible: false + }, + { + title: "System Label", + field: "systemLabel", + visible: false + }, + { + title: "Name", + field: "name", + vertAlign: "middle" + }, + { + title: "ProviderImg", + field: "providerImg", + formatter: providerFormatter, + vertAlign: "middle", + hozAlign: "center", + headerSort: false, + }, + { + title: "Provider", + field: "provider", + formatter: providerFormatterString, + visible: false + }, + { + title: "Total Servers", + field: "statusCount.countTotal", + vertAlign: "middle", + hozAlign: "center", + maxWidth: 150, + }, + { + title: "Running", + field: "statusCount.countRunning", + formatterParams: { status: "running" }, + vertAlign: "middle", + hozAlign: "center", + headerHozAlign: "center", + maxWidth: 135, + }, + { + title: "Suspended", + field: "statusCount.countSuspended", + formatterParams: { status: "stop" }, + vertAlign: "middle", + hozAlign: "center", + headerHozAlign: "center", + maxWidth: 135, + }, + { + title: "Terminated", + field: "statusCount.countTerminated", + formatterParams: { status: "terminate" }, + vertAlign: "middle", + hozAlign: "center", + headerHozAlign: "center", + maxWidth: 135, + }, + ]; + + //mcisListTable = webconsolejs["common/util"].setTabulator("mcislist-table", tableObjParams, columns);// TODO [common/util]에 정의되어 있는데 호출하면 에러남... why? + mcisListTable = setMcisTabulator("mcislist-table", tableObjParams, columns); + + // 행 클릭 시 + mcisListTable.on("rowClick", function (e, row) { + + var mcisID = row.getCell("id").getValue(); + console.log("mcisID", mcisID) + // console.log("eeeee",e) + //clickListOfMcis(row.getCell("id").getValue()); + + // 표에서 선택된 MCISInfo + getSelectedMcisData(mcisID) + + }); + + //  선택된 여러개 row에 대해 처리 + mcisListTable.on("rowSelectionChanged", function (data, rows) { + checked_array = data + console.log("checked_array", checked_array) + console.log("rowsrows", data) + selectedMcisObj = data + // console.log(providerFormatterString()); + }); + + // displayColumn(table); + +} + +// 상태값을 table에서 표시하기 위해 감싸기 +function statusFormatter(cell) { + var mcisDispStatus = getMcisStatusDisp( + cell.getData().status + ); // 화면 표시용 status + var mcisStatusCell = + ''; + + return mcisStatusCell; +} + +// provider를 table에서 표시하기 위해 감싸기 +function providerFormatter(data) { + console.log("datadata", data) + console.log("cell.getData().vm", data.getData().vm) + var vmCloudConnectionMap = webconsolejs["common/util"].calculateConnectionCount( + data.getData().vm + ); + var mcisProviderCell = ""; + vmCloudConnectionMap.forEach((value, key) => { + mcisProviderCell += + '' +
+      key +
+      ''; + }); + + return mcisProviderCell; +} + +// provider를 string으로 추출 +// table에서 provider 이름으로 필터링 하기 위해 +function providerFormatterString(data) { + + var vmCloudConnectionMap = webconsolejs["common/util"].calculateConnectionCount( + data.getData().vm + ); + + var mcisProviderCell = ""; + vmCloudConnectionMap.forEach((value, key) => { + mcisProviderCell += key + ", " + }); + + // Remove the trailing comma and space + if (mcisProviderCell.length > 0) { + mcisProviderCell = mcisProviderCell.slice(0, -2); + } + + return mcisProviderCell; +} + +/////////////////////////Tabulator Filter start///////////////////////// +//Define variables for input elements +var fieldEl = document.getElementById("filter-field"); +var typeEl = document.getElementById("filter-type"); +var valueEl = document.getElementById("filter-value"); + +// table rovider filtering / equel 고정 +function providerFilter(data) { + + // case type like, equal, not eual + // equal only + if (typeEl.value == "=") { + var vmCloudConnectionMap = webconsolejs["common/util"].calculateConnectionCount( + data.vm + ); + var valueElValue = valueEl.value; + if (valueElValue != "") { + if (vmCloudConnectionMap.has(valueElValue)) { + return true; + } else { + return false; + } + } + + } else { + return true; + } + + return true +} + +// Trigger setFilter function with correct parameters +function updateFilter() { + var filterVal = fieldEl.options[fieldEl.selectedIndex].value; + var typeVal = typeEl.options[typeEl.selectedIndex].value; + + var filter = filterVal == "provider" ? providerFilter : filterVal; + + if (filterVal == "provider") { + typeEl.value = "="; + typeEl.disabled = true; + } else { + typeEl.disabled = false; + } + + if (filterVal) { + table.setFilter(filter, typeVal, valueEl.value); + } +} + +// Update filters on value change +document.getElementById("filter-field").addEventListener("change", updateFilter); +document.getElementById("filter-type").addEventListener("change", updateFilter); +document.getElementById("filter-value").addEventListener("keyup", updateFilter); + +// Clear filters on "Clear Filters" button click +document.getElementById("filter-clear").addEventListener("click", function () { + fieldEl.value = ""; + typeEl.value = "="; + valueEl.value = ""; + + table.clearFilter(); + +}); +/////////////////////////Tabulator Filter END///////////////////////// + +////////////////////////////////////////////////////// END TABULATOR /////////////////////////////////////////////////// \ No newline at end of file diff --git a/mc_web_console_front/assets/js/pages/operation/workflow/createworkflow.js b/mc_web_console_front/assets/js/pages/operation/workflow/createworkflow.js new file mode 100644 index 00000000..eef28ec2 --- /dev/null +++ b/mc_web_console_front/assets/js/pages/operation/workflow/createworkflow.js @@ -0,0 +1 @@ +console.log("createworkflow.js") \ No newline at end of file diff --git a/mc_web_console_front/assets/js/pages/operation/workflow/manageworkflow.js b/mc_web_console_front/assets/js/pages/operation/workflow/manageworkflow.js new file mode 100644 index 00000000..c141616d --- /dev/null +++ b/mc_web_console_front/assets/js/pages/operation/workflow/manageworkflow.js @@ -0,0 +1 @@ +console.log("manageworkflow.js") \ No newline at end of file diff --git a/mc_web_console_front/assets/js/partials/layout/modal.js b/mc_web_console_front/assets/js/partials/layout/modal.js new file mode 100644 index 00000000..c76c5949 --- /dev/null +++ b/mc_web_console_front/assets/js/partials/layout/modal.js @@ -0,0 +1,570 @@ +/* + + commonSimpleModal + +*/ +export function commonModal(elm, title, content, func, argument) { + const form = elm.getAttribute('data-bs-target').replace(/^#/, ''); // 불러올 modal Id + const funcArr = func.split("."); + document.getElementById(`${form}-title`).innerText = title + document.getElementById(`${form}-content`).innerText = content + document.getElementById(`${form}-confirm-btn`).onclick = function() { + const executefunction = `webconsolejs["${funcArr[0]}"].${funcArr[1]}('${argument}')`; + eval(executefunction); + }; +} + + +// Modal OLD +////////////////////////////////////////////////////////////////////////////////////////// + +// confirm modal창 보이기 modal창이 열릴 때 해당 창의 text 지정, close될 때 action 지정 +function commonConfirmOpen(targetAction, caller) { + console.log("commonConfirmOpen : " + targetAction) + + // [ id , 문구] + let confirmModalTextMap = new Map( + [ + ["CreateSnapshot", "Would you like to Create Snapshot?"], + ["DeleteDataDisk", "Would you like to Delete Disk?"], + ["DeleteMyImage", "Would you like to Delete MyImage?"], + ["Logout", "Would you like to logout?"], + ["Config", "Would you like to set Cloud config ?"], + ["SDK", "Would you like to set Cloud Driver SDK ?"], + ["Credential", "Would you like to set Credential ?"], + ["Region", "Would you like to set Region ?"], + ["Provider", "Would you like to set Cloud Provider ?"], + + ["MoveToConnection", "Would you like to set Cloud config ?"], + ["ChangeConnection", "Would you like to change Cloud connection ?"], + ["DeleteCloudConnection", "Would you like to delete
    the Cloud connection? "], + + ["DeleteCredential", "Would you like to delete
    the Credential? "], + ["DeleteDriver", "Would you like to delete
    the Driver? "], + ["DeleteRegion", "Would you like to delete
    the Region? "], + + + // ["IdPassRequired", "ID/Password required !"], --. 이거는 confirm이 아니잖아 + ["idpwLost", "Illegal account / password 다시 입력 하시겠습니까?"], + ["ManageNS", "Would you like to manage
    Name Space?"], + ["NewNS", "Would you like to add a new Name Space?"], + ["AddNewNameSpace", "Would you like to register NameSpace
    Resource ?"], + ["NameSpace", "Would you like to move
    selected NameSpace?"], + ["ChangeNameSpace", "Would you like to move
    selected NameSpace?"], + ["DeleteNameSpace", "Would you like to delete
    selected NameSpace?"], + + ["AddNewVpc", "Would you like to create a new Network
    Resource ?"], + ["DeleteVpc", "Are you sure to delete this Network
    Resource ?"], + + ["AddNewSecurityGroup", "Would you like to create a new Security
    Resource ?"], + ["DeleteSecurityGroup", "Would you like to delete Security
    Resource ?"], + + ["AddNewSshKey", "Would you like to create a new SSH key
    Resource ?"], + ["DeleteSshKey", "Would you like to delete SSH key
    Resource ?"], + + ["AddNewVirtualMachineImage", "Would you like to register Image
    Resource ?"], + ["DeleteVirtualMachineImage", "Would you like to un-register Image
    Resource ?"], + ["FetchImages", "Would you like to fetch images
    to this NameSpace ?"], + + ["AddNewVmSpec", "Would you like to register Spec
    Resource ?"], + ["DeleteVmSpec", "Would you like to un-register Spec
    Resource ?"], + ["FetchSpecs", "Would you like to fetch Spec
    to this NameSpace ?"], + + ["GotoMonitoringPerformance", "Would you like to view performance
    for MCIS ?"], + ["GotoMonitoringFault", "Would you like to view fault
    for MCIS ?"], + ["GotoMonitoringCost", "Would you like to view cost
    for MCIS ?"], + ["GotoMonitoringUtilize", "Would you like to view utilize
    for MCIS ?"], + + ["McisLifeCycleReboot", "Would you like to reboot MCIS ?"],// mcis_life_cycle('reboot') + ["McisLifeCycleSuspend", "Would you like to suspend MCIS ?"],//onclick="mcis_life_cycle('suspend') + ["McisLifeCycleResume", "Would you like to resume MCIS ?"],//onclick="mcis_life_cycle('resume')" + ["McisLifeCycleTerminate", "Would you like to terminate MCIS ?"],//onclick="mcis_life_cycle('terminate') + ["McisManagement", "Would you like to manage MCIS ?"],// 해당 function 없음... + ["MoveToMcisManagement", "Would you like to manage MCIS ?"], + ["MoveToMcisManagementFromDashboard", "Would you like to manage MCIS ?"], + + ["AddNewMcis", "Would you like to create MCIS ?"], + ["AddNewMcisDynamic", "Would you like to create MCIS ?"], + ["DeleteMcis", "Are you sure to delete this MCIS? "], + ["ImportScriptOfMcis", "Would you like to import MCIS script? "], + ["ExportScriptOfMcis", "Would you like to export MCIS script? "], + ["ShowMonitoring", "Would you like to go to the Monitoring page?"], + + ["AddNewVmOfMcis", "Would you like to add a new VM to this MCIS ?"], + ["DeployServer", "Would you like to deploy?"], + + ["VmLifeCycle", "Would you like to view Server ?"], + ["VmLifeCycleReboot", "Would you like to reboot VM ?"], //onclick="vm_life_cycle('reboot')" + ["VmLifeCycleSuspend", "Would you like to suspend VM ?"], // onclick="vm_life_cycle('suspend')" + ["VmLifeCycleResume", "Would you like to resume VM ?"], // onclick="vm_life_cycle('resume')" + ["VmLifeCycleTerminate", "Would you like to terminate VM ?"], // onclick="vm_life_cycle('terminate')" + ["VmManagement", "Would you like to manage VM ?"], // 해당 function 없음 + ["AddNewVm", "Would you like to add VM ?"], //onclick="vm_add()" + ["ExportVmScriptOfMcis", "Would you like to export VM script ?"], //onclick="vm_add()" + + + ["DifferentConnection", "Do you want to set different connectionName?"], + ["DifferentConnectionAtSecurityGroup", "Do you want to set different connectionName?"], + ["DifferentConnectionAtAssistPopup", "Do you want to set different connectionName?"], + + ["AddMonitoringAlertPolicy", "Would you like to register Threshold ?"], + ["DeleteMonitoringAlertPolicy", "Are you sure to delete this Threshold ?"], + ["AddNewMcks", "Would you like to create MCKS ?"], + ["DeleteMcks", "Are you sure to delete this MCKS? "], + ["AddNewNodeOfMcks", "Would you like to add a new Node to this MCKS ?"], + ["DeleteNodeOfMcks", "Would you like to delete a Node of this MCKS ?"], + + + ["AddMonitoringAlertEventHandler", "Would you like to add
    Monitoring Alert Event-Handler ?"], + ["deleteMonitoringAlertEventHandler", "Are you sure to delete
    this Monitoring Alert Event-Handler?"], + + ["RegisterRecommendSpec", "현재 해당 connection에서 사용가능한 spec 이 없습니다. 등록 하시겠습니까?"], + + ["DeleteNlb", "Would you like to delete NLB ?"], + + ["AddNewPmks", "Would you like to create PMKS ?"], + ["DeletePmks", "Are you sure to delete this PMKS? "], + ["AddNewNodeGroupOfPmks", "Would you like to add a new NodeGroup to this PMKS ?"], + ["DeleteNodeGroupOfPmks", "Would you like to delete a NodeGroup of this PMKS ?"], + + + ["WorkspaceDelete", "Are you sure you want to delete the Workspace ?"], + + ] + ); + console.log(confirmModalTextMap.get(targetAction)); + try { + // $('#modalText').text(targetText);// text아니면 html로 해볼까? 태그있는 문구가 있어서 + //$('#modalText').text(confirmModalTextMap.get(targetAction)); + $('#confirmText').html(confirmModalTextMap.get(targetAction)); + $('#confirmOkAction').val(targetAction); + console.log("caller : ", caller); + $('#confirmCaller').val(caller); + + if (targetAction == "Region") { + // button에 target 지정 + // data-target="#Add_Region_Register" + // TODO : confirm 으로 물어본 뒤 OK버튼 클릭 시 targetDIV 지정하도록 + } + $('#confirmArea').modal(); + } catch (e) { + console.log(e); + alert(e); + } +} + +// confirm modal창에서 ok버튼 클릭시 수행할 method 지정 +function commonConfirmOk() { + //modalArea + var targetAction = $('#confirmOkAction').val(); + var caller = $('#confirmCaller').val(); + if (targetAction == "Logout") { + // Logout처리하고 index화면으로 간다. Logout ==> cookie expire + // location.href="/logout" + var targetUrl = "/logout" + changePage(targetUrl) + + } else if (targetAction == "MoveToConnection") { + var targetUrl = "/setting/connections/cloudconnectionconfig/mngform" + changePage(targetUrl) + } else if (targetAction == "ChangeConnection") { // recommendvm에서 다른 connection 선택 시 + changeCloudConnection() + } else if (targetAction == "DeleteCloudConnection") { + deleteCloudConnection(); + } else if (targetAction == "Config") { + //id="Config" + console.log("commonConfirmOk " + targetAction); + } else if (targetAction == "SDK") { + //id="SDK" + console.log("commonConfirmOk " + targetAction); + } else if (targetAction == "DeleteCredential") { + deleteCredential(); + } else if (targetAction == "DeleteDriver") { + deleteDriver(); + } else if (targetAction == "DeleteRegion") { + deleteRegion(); + + } else if (targetAction == "Credential") { + //id="Credential" + console.log("commonConfirmOk " + targetAction); + } else if (targetAction == "Region") { + //id="Region" + console.log("commonConfirmOk " + targetAction); + } else if (targetAction == "Provider") { + //id="Provider" + console.log("commonConfirmOk " + targetAction); + } else if (targetAction == "required") {//-- IdPassRequired + console.log("commonConfirmOk " + targetAction); + } else if (targetAction == "idpwLost") {//-- + console.log("commonConfirmOk " + targetAction); + } else if (targetAction == "ManageNS") {//-- ManageNS + var targetUrl = "/setting/namespaces/namespace/mngform" + changePage(targetUrl) + } else if (targetAction == "NewNS") {//-- NewNS + var targetUrl = "/setting/namespaces/namespace/mngform" + changePage(targetUrl) + } else if (targetAction == "ChangeNameSpace") {//-- ChangeNameSpace + var changeNameSpaceID = $("#tempSelectedNameSpaceID").val(); + setDefaultNameSpace(changeNameSpaceID) + } else if (targetAction == "AddNewNameSpace") {//-- AddNewNameSpace + displayNameSpaceInfo("REG") + goFocus('ns_reg');// 해당 영역으로 scroll + } else if (targetAction == "DeleteNameSpace") { + deleteNameSpace() + } else if (targetAction == "AddNewVpc") { + displayVNetInfo("REG") + goFocus('vnetCreateBox'); + } else if (targetAction == "DeleteVpc") { + deleteVPC() + } else if (targetAction == "AddNewSecurityGroup") { + displaySecurityGroupInfo("REG") + goFocus('securityGroupCreateBox'); + } else if (targetAction == "DeleteSecurityGroup") { + deleteSecurityGroup() + } else if (targetAction == "AddNewSshKey") { + displaySshKeyInfo("REG") + goFocus('sshKeyCreateBox'); + } else if (targetAction == "DeleteSshKey") { + deleteSshKey() + } else if (targetAction == "AddNewVirtualMachineImage") { + displayVirtualMachineImageInfo("REG") + goFocus('virtualMachineImageCreateBox'); + } else if (targetAction == "DeleteVirtualMachineImage") { + deleteVirtualMachineImage() + } else if (targetAction == "FetchImages") { + getCommonFetchImages(); + } else if (targetAction == "AddNewVmSpec") { + displayVmSpecInfo("REG") + goFocus('vmSpecCreateBox'); + } else if (targetAction == "ExportVmScriptOfMcis") { + vmScriptExport(); + } else if (targetAction == "DeleteVmSpec") { + deleteVmSpec(); + } else if (targetAction == "FetchSpecs") { + var connectionName = $("#regConnectionName").val(); + putFetchSpecs(connectionName); + } else if (targetAction == "GotoMonitoringPerformance") { + // alert("모니터링으로 이동 GotoMonitoringPerformance") + // location.href ="";//../operation/Monitoring_Mcis.html + var targetUrl = "/operation/monitorings/mcismng/mngform" + changePage(targetUrl) + } else if (targetAction == "GotoMonitoringFault") { + // alert("모니터링으로 이동 GotoMonitoringFault") + // location.href ="";//../operation/Monitoring_Mcis.html + var targetUrl = "/operation/monitorings/mcismng/mngform" + changePage(targetUrl) + } else if (targetAction == "GotoMonitoringCost") { + // alert("모니터링으로 이동 GotoMonitoringCost") + // location.href ="";//../operation/Monitoring_Mcis.html + var targetUrl = "/operation/monitorings/mcismng/mngform" + changePage(targetUrl) + } else if (targetAction == "GotoMonitoringUtilize") { + // alert("모니터링으로 이동 GotoMonitoringUtilize") + // location.href ="";//../operation/Monitoring_Mcis.html + var targetUrl = "/operation/monitorings/mcismng/mngform" + changePage(targetUrl) + } else if (targetAction == "McisLifeCycleReboot") { + callMcisLifeCycle('reboot') + } else if (targetAction == "McisLifeCycleSuspend") { + callMcisLifeCycle('suspend') + } else if (targetAction == "McisLifeCycleResume") { + callMcisLifeCycle('resume') + } else if (targetAction == "McisLifeCycleTerminate") { + callMcisLifeCycle('terminate') + } else if (targetAction == "McisManagement") { + alert("수행할 function 정의되지 않음"); + } else if (targetAction == "MoveToMcisManagementFromDashboard") { + var mcisID = $("#mcis_id").val(); + var targetUrl = "/operation/manages/mcismng/mngform?mcisid=" + mcisID; + changePage(targetUrl) + } else if (targetAction == "MoveToMcisManagement") { + var targetUrl = "/operation/manages/mcismng/mngform"; + changePage(targetUrl) + } else if (targetAction == "AddNewMcis") { + // $('#loadingContainer').show(); + // location.href ="/operation/manages/mcis/regform/"; + var targetUrl = "/operation/manages/mcismng/regform"; + changePage(targetUrl) + } else if (targetAction == "DeleteMcis") { + deleteMCIS(); + } else if (targetAction == "DeployServer") { + btn_deploy(); + } else if (targetAction == "ImportScriptOfMcis") { + mcisScriptImport(); + } else if (targetAction == "ExportScriptOfMcis") { + mcisScriptExport(); + } else if (targetAction == "ShowMonitoring") { + var mcisID = $("#mcis_id").val(); + var targetUrl = "/operation/monitorings/mcismonitoring/mngform?mcisId=" + mcisID; + changePage(targetUrl) + } else if (targetAction == "VmLifeCycle") { + alert("수행할 function 정의되지 않음"); + } else if (targetAction == "VmLifeCycleReboot") { + vmLifeCycle('reboot') + } else if (targetAction == "VmLifeCycleSuspend") { + vmLifeCycle('suspend') + } else if (targetAction == "VmLifeCycleResume") { + vmLifeCycle('resume') + } else if (targetAction == "VmLifeCycleTerminate") { + vmLifeCycle('terminate') + } else if (targetAction == "VmManagement") { + alert("수행할 function 정의되지 않음"); + } else if (targetAction == "AddNewVm") { + addNewVirtualMachine() + } else if (targetAction == "AddNewVmOfMcis") { + addNewVirtualMachine() + } else if (targetAction == "ExportVmScriptOfMcis") { + vmScriptExport(); + } else if (targetAction == "--") { + addNewVirtualMachine() + } else if (targetAction == "monitoringConfigPolicyConfig") { + regMonitoringConfigPolicy() + } else if (targetAction == "DifferentConnection") { + setAndClearByDifferentConnectionName(caller); + } else if (targetAction == "DifferentConnectionAtSecurityGroup") { + uncheckDifferentConnectionAtSecurityGroup(); + } else if (targetAction == "DifferentConnectionAtAssistPopup") { + // connection이 다른데도 set 한다고 하면 이전에 설정한 값들을 초기화 한 후 set한다. + applyAssistValues(caller); + } else if (targetAction == "AddMonitoringAlertPolicy") { + addMonitoringAlertPolicy(); + } else if (targetAction == "DeleteMonitoringAlertPolicy") { + deleteMonitoringAlertPolicy(); + } else if (targetAction == "AddNewMcks") { + var targetUrl = "/operation/manages/mcksmng/regform"; + changePage(targetUrl) + } else if (targetAction == "AddNewNodeOfMcks") { + addNewNode(); + } else if (targetAction == "DeleteNodeOfMcks") { + deleteNodeOfMcks(); + } else if (targetAction == "AddMonitoringAlertEventHandler") { + addMonitoringAlertEventHandler(); + } else if (targetAction == "deleteMonitoringAlertEventHandler") { + deleteMonitoringAlertEventHandler(); + } else if (targetAction == "DeleteMcks") { + deleteMCKS(); + } else if (targetAction == "RegisterRecommendSpec") { + commonPromptOpen("RegisterRecommendSpec") + } else if (targetAction == "AddNewMcisDynamic") { + createMcisDynamic() + } else if (targetAction == "DeleteDataDisk") { + deleteDataDisk(); + + } else if (targetAction == "DeleteMyImage") { + deleteMyImageDisk(); + + } else if (targetAction == "CreateSnapshot") { + commonPromptOk + createSnapshot(); + + } else if (targetAction == "DeleteNlb") { + deleteNlb(); + } else if (targetAction == "AddNewPmks") { + changePage("PmksClusterRegForm"); + } else if (targetAction == "DeletePmks") { + deleteCluster(); + } else if (targetAction == "AddNewNodeGroupOfPmks") { + changePage("PmksNodeGroupRegForm"); + } else if (targetAction == "DeleteNodeGroupOfPmks") { + deleteNodeGroupOfPmks(); + } else { + alert("수행할 function 정의되지 않음 " + targetAction); + } + console.log("commonConfirmOk " + targetAction); + commonConfirmClose(); +} + +// confirm modal창 닫기. setting값 초기화 +function commonConfirmClose() { + $('#confirmText').text(''); + $('#confirmOkAction').val(''); + // $('#modalArea').hide(); + $("#confirmArea").modal("hide"); +} + +function commonPromptEnter(keyEvent) { + if (keyEvent.keyCode == 13) { + commonPromptOk(); + } +} + +function commonPromptOk() { + var targetAction = $('#promptOkAction').val(); + var targetObjId = $('#promptTargetObjId').val(); + var targetValue = $('#promptText').val(); + + console.log("promptOkAction : " + targetAction) + if (targetAction == 'FilterName') {// Name이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "Name", targetValue) + } + } else if (targetAction == 'FilterCloudProvider') {// Name이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "Cloud Provider", targetValue) + } + } else if (targetAction == 'FilterDriver') {// Name이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "Driver", targetValue) + } + } else if (targetAction == 'FilterCredential') {// Name이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "Credential", targetValue) + } + } else if (targetAction == 'RsFltVPCName') {// Name이라는 Column을 Filtering + var filterKey = "name" + if (targetValue) { + getCommonSecurityGroupList("", "name", "", filterKey, targetValue) + } + } else if (targetAction == 'RsFltCIDRBlock') {// Name이라는 Column을 Filtering + var filterKey = "cidrBlock" + if (targetValue) { + getCommonSecurityGroupList("", "name", "", filterKey, targetValue) + } + } else if (targetAction == 'RsFltSecurityGroupName') {// Name이라는 Column을 Filtering + var filterKey = "cspSecurityGroupName" + if (targetValue) { + getCommonSecurityGroupList("securitygroupmng", "name", "", filterKey, targetValue) + } + } else if (targetAction == 'RsFltConnectionName') {// Name이라는 Column을 Filtering + var filterKey = "connectionName" + if (targetValue) { + getCommonSecurityGroupList("securitygroupmng", "name", "", filterKey, targetValue) + } + } else if (targetAction == 'RsFltSshName') {// Name이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "Name", targetValue) + } + } else if (targetAction == 'RsFltSshConnName') {// Name이라는 Column을 Filtering + var filterKey = "connectionName" + if (targetValue) { + getCommonSshKeyList("", "name", "", filterKey, targetValue) + } + } else if (targetAction == 'RsFltSshKeyName') {// Name이라는 Column을 Filtering + var filterKey = "name" + if (targetValue) { + getCommonSshKeyList("", "name", "", filterKey, targetValue) + } + } else if (targetAction == 'RsFltSrvImgId') {// Name이라는 Column을 Filtering + var filterKey = "cspImageId" + if (targetValue) { + getCommonVirtualMachineImageList("virtualmachineimagemng", "name", "", filterKey, targetValue) + } + } else if (targetAction == 'RsFltSrvImgName') {// Name이라는 Column을 Filtering + var filterKey = "name" + if (targetValue) { + getCommonVirtualMachineImageList("virtualmachineimagemng", "name", "", filterKey, targetValue) + } + } else if (targetAction == 'RsFltSrvSpecName') {// Name이라는 Column을 Filtering + var filterKey = "name" + if (targetValue) { + getCommonVirtualMachineSpecList("virtualmachinespecmng", "name", "", filterKey, targetValue) + } + } else if (targetAction == 'RsFltSrvSpecConnName') {// Name이라는 Column을 Filtering + var filterKey = "connectionName" + if (targetValue) { + getCommonVirtualMachineSpecList("virtualmachinespecmng", "name", "", filterKey, targetValue) + } + } else if (targetAction == 'RsFltSrvCspSpecName') {// Name이라는 Column을 Filtering + var filterKey = "cspSpecName" + if (targetValue) { + getCommonVirtualMachineSpecList("virtualmachinespecmng", "name", "", filterKey, targetValue) + } + } else if (targetAction == 'NSFltName') {// Name이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "Name", targetValue) + } + } else if (targetAction == 'NSFltId') {// Name이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "ID", targetValue) + } + } else if (targetAction == 'NSFltDescription') {// Name이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "description", targetValue) + } + } else if (targetAction == 'AlertPolicyName') {// Name이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "Name", targetValue) + } + } else if (targetAction == 'AlertPolicyMeasurement') {// Name이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "Measurement", targetValue) + } + } else if (targetAction == 'AlertPolicyTargetType') {// Name이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "Target Type", targetValue) + } + } else if (targetAction == 'AlertPolicyEventType') {// Name이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "Alert Event Type", targetValue) + } + } else if (targetAction == 'FilterMcisName') {// Name이라는 Column을 Filtering + if (targetValue) { + // keyword표시 + searchKeyword(targetValue, 'mcislistfilter') + } + } else if (targetAction == 'FilterMcisStatus') {// Status이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "Status", targetValue) + } + } else if (targetAction == 'FilterMcisDesc') {// Description이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "Description", targetValue) + } + } else if (targetAction == 'OprMngMcksStatus') {// Description이라는 Column을 Filtering + console.log("OprMngMcksStatus"); + if (targetValue) { + filterTable(targetObjId, "Status", targetValue) + } + } else if (targetAction == 'OprMngMcksName') {// Description이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "Name", targetValue) + } + } else if (targetAction == 'OprMngMcksNetworkCni') {// Description이라는 Column을 Filtering + if (targetValue) { + filterTable(targetObjId, "NetworkCni", targetValue) + } + } else if (targetAction == 'RemoteCommandMcis') { + if (targetValue) { + remoteCommandMcis(targetValue); + //postRemoteCommandMcis(targetValue); + } + } else if (targetAction == 'RemoteCommandVmOfMcis') { + if (targetValue) { + remoteCommandVmMcis(targetValue); + } + } else if (targetAction == 'RegisterRecommendSpec') { + createRecommendSpec(targetValue); + } else if (targetAction == 'AddNewMcisDynamic') { + $("#mcis_name").val(targetValue) + createMcisDynamic() + } else if (targetAction == 'CreateSnapshot') { + createSnapshot(targetValue); + } + + + commonPromptClose(); +} + +function commonPromptClose() { + $('#promptQuestion').text(''); + $('#promptText').text(''); + $('#promptOkAction').val(''); + $("#promptArea").modal("hide"); +} + +// alert창 닫기 +function commonAlertClose() { + $("#alertArea").modal("hide"); +} + +// alert창 닫기 +function commonResultAlertClose() { + $("#alertResultArea").modal("hide"); +} + +function guideAreaHide() { + console.log("hide brfore") + $("#guideArea").modal("hide"); + console.log("hide after") +} \ No newline at end of file diff --git a/mc_web_console_front/assets/js/partials/layout/navbar.js b/mc_web_console_front/assets/js/partials/layout/navbar.js index ebc35cbc..a3afc4f2 100644 --- a/mc_web_console_front/assets/js/partials/layout/navbar.js +++ b/mc_web_console_front/assets/js/partials/layout/navbar.js @@ -1,81 +1,193 @@ +// navigation 에 workspace목록, project목록 set +// - local storage에 저장된 user의 workspace목록, project 목록을 우선 set. +// - workspace 변경시 project 목록 조회 +// - refresh 버튼 클릭 시 user의 workspace, project 목록 조회하여 local storage에 저장 init 호출 +// - init은 저장된 user의 workspace목록, project 목록을 조회하여 set let workspaceListselectBox = document.getElementById("select-current-workspace"); let projectListselectBox = document.getElementById("select-current-project"); -let workspaceRefresh = document.getElementById("select-refresh") +let workspaceRefreshBtn = document.getElementById("refresh-user-ws-prj")// ws prj refresh 버튼 document.addEventListener('DOMContentLoaded',async function () { - workspaceProjectInit() + console.log("navbar init") + //await workspaceProjectInit()// workspace select box, project select box 초기화 from local storage }); -workspaceListselectBox.addEventListener('change',function () { + +// navbar에서는 변경시 session에만 set. 필요화면에서 사용 +workspaceListselectBox.addEventListener('change', function () { + // if (this.value == "") return; + let workspace = {"Id":this.value, "Name":this.options[this.selectedIndex].text} - webconsolejs["common/util"].setCurrentWorkspace(workspace) - updatePrjSelectBox(workspace.Id) + webconsolejs["common/util"].setCurrentWorkspace(workspace);//세션에 저장 + + // // workspace 변경 시 currProject 다시 set + // setPrjSelectBox(workspace.Id) + }); +// navbar에서는 변경시 session에만 set. 필요화면에서 사용 projectListselectBox.addEventListener('change',function () { let project = {"Id":this.value, "Name":this.options[this.selectedIndex].text} - webconsolejs["common/util"].setCurrentProject(project) + webconsolejs["common/util"].setCurrentProject(project)// 세션에 저장 + + // 현재 화면의 iniPage() 호출 + //webconsolejs["pages/manage/mcis"].inptPage(project) + //webconsolejs["pages/configuration/workspace/manage"].inptPage(project) }); -workspaceRefresh.addEventListener('click',function () { - webconsolejs["common/util"].clearCurrentWorkspaceProject() - while (workspaceListselectBox.options.length > 0) { - workspaceListselectBox.remove(0); - } - while (projectListselectBox.options.length > 0) { - projectListselectBox.remove(0); - } - workspaceProjectInit() +// refresh 버튼 클릭시 user의 workspace, project 목록 조회 +workspaceRefreshBtn.addEventListener('click',function () { + // webconsolejs["common/util"].clearCurrentWorkspaceProject() + // while (workspaceListselectBox.options.length > 0) { + // workspaceListselectBox.remove(0); + // } + // while (projectListselectBox.options.length > 0) { + // projectListselectBox.remove(0); + // } + // workspaceProjectInit() }); +// user의 workspace와 project 목록 조회 +// async function getWorkspaceProjectListByUser() { +// //async function updateWorkspaceProjectList() { +// const response = await webconsolejs["common/api/http"].commonAPIPost('/api/getworkspacebyuserid', null) +// return response.data.responseData +// } -async function updateWorkspaceProjectList() { - const response = await webconsolejs["common/api/http"].commonAPIPost('/api/getworkspacebyuserid', null) - return response.data.responseData -} +// // workspaceList select에 set. +// //function updateWsSelectBox(workspaceList) { +// async function setWorkspaceSelectBox(workspaceList) { +// while (workspaceListselectBox.options.length > 0) { +// workspaceListselectBox.remove(0); +// } +// var workspaceExists = false +// console.log("get workspace from session " , webconsolejs["common/util"].getCurrentWorkspace()) +// let curWorkspaceId = await webconsolejs["common/util"].getCurrentWorkspace()?.Id + +// console.log("setWorkspaceSelectbox --------------------") +// //console.log(workspaceList) +// const defaultOpt = document.createElement("option"); +// defaultOpt.value = "" +// defaultOpt.textContent = "Please select a workspace"; +// workspaceListselectBox.appendChild(defaultOpt); + +// for (const w in workspaceList) { +// const opt = document.createElement("option"); +// opt.value = workspaceList[w].id; +// opt.textContent = workspaceList[w].name; +// console.log("curWorkspaceId", curWorkspaceId) +// console.log("workspaceList[w]", workspaceList[w]) +// if (curWorkspaceId != "" && workspaceList[w].id == curWorkspaceId) { +// opt.setAttribute("selected", "selected"); +// workspaceExists = true +// } +// workspaceListselectBox.appendChild(opt); +// } +// } + +// // project는 조회한다. +// async function setPrjSelectBox(workspaceId) { +// // function updatePrjSelectBox(workspaceId) { +// let projectList = await webconsolejs["common/util"].getProjectListByWorkspaceId(workspaceId) +// console.log("projectList ", projectList) +// while (projectListselectBox.options.length > 0) { +// projectListselectBox.remove(0); +// } + +// const defaultOpt = document.createElement("option"); +// defaultOpt.value = "" +// defaultOpt.textContent = "Please select a project"; +// projectListselectBox.appendChild(defaultOpt); + +// let curProjectId = webconsolejs["common/util"].getCurrentProject()?.Id +// for (const p in projectList) { +// console.log("p ", p) +// const opt = document.createElement("option"); +// opt.value = projectList[p].id; +// opt.textContent = projectList[p].name; +// projectListselectBox.appendChild(opt); + +// if (curProjectId != "" && projectList[p].id == curProjectId) { +// opt.setAttribute("selected", "selected"); +// } +// } + +// //initPage("PROJECT_CHANGED");// project가 변경되면 InitPage 호출 +// } + +// 기본은 local storage에 저장된 값 사용 -> 없으면 조회 +// navbar에 workspace 목록 selectbox와 project 목록 select box set +export async function workspaceProjectInit(){ + + let userWorkspaceList = await webconsolejs["common/util"].getWorkspaceListByUser() + console.log("user wslist ", userWorkspaceList) -function updateWsSelectBox(workspaceList) { - while (workspaceListselectBox.options.length > 0) { - workspaceListselectBox.remove(0); + let curWorkspace = await webconsolejs["common/util"].getCurrentWorkspace() + let curWorkspaceId = ""; + //let curWorkspaceName = ""; + if( curWorkspace ){ + curWorkspaceId = curWorkspace.Id; + //curWorkspaceName = curWorkspace.Name; } - for (const w in workspaceList) { - const opt = document.createElement("option"); - opt.value = workspaceList[w].workspaceId; - opt.textContent = workspaceList[w].workspaceName; - workspaceListselectBox.appendChild(opt); + + webconsolejs["common/util"].setWorkspaceSelectBox(userWorkspaceList, curWorkspaceId) + + + // workspace, project 가 먼저 설정되어 있어야 한다. + console.log("curWorkspaceId", curWorkspaceId) + let curProjectId = ""; + if( curWorkspaceId == "" || curWorkspaceId == undefined){ + console.log(" curWorkspaceId is not set ") + }else{ + // workspace가 선택되어 있으면 project 목록도 표시 + let userProjectList = await webconsolejs["common/util"].getUserProjectList(curWorkspaceId) + console.log("userProjectList ", userProjectList) + + // project 목록이 있으면 cur project set + curProjectId = await webconsolejs["common/util"].getCurrentProject()?.Id + console.log("curProjectId", curProjectId) + + webconsolejs["common/util"].setPrjSelectBox(userProjectList, curProjectId) } - workspaceListselectBox.value = "" + + return {workspaceId:curWorkspaceId, projectId:curProjectId}; } -function updatePrjSelectBox(workspaceId) { - let currentWorkspaceProjectList = webconsolejs["common/util"].getCurrentWorkspaceProjectList() - let projecWorkspace = currentWorkspaceProjectList.find(item => item.workspaceId === workspaceId); - let projectList = projecWorkspace.projectList + +// workspaceObj +export async function setWorkspaceChanged(selectedWorkspaceValue){ + console.log(" setWorkspaceChanged ") + + if( selectedWorkspaceValue == ""){ + console.log("selectedWorkspace Value empty") + return; + } + + let projectListselectBox = document.getElementById("select-current-project"); + + let projectList = await webconsolejs["common/util"].getProjectListByWorkspaceId(selectedWorkspaceValue); + console.log("set project select box") while (projectListselectBox.options.length > 0) { - projectListselectBox.remove(0); + projectListselectBox.remove(0); } + + const defaultOpt = document.createElement("option"); + defaultOpt.value = "" + defaultOpt.textContent = "Please select a project"; + projectListselectBox.appendChild(defaultOpt); + + let curProjectId = webconsolejs["common/util"].getCurrentProject()?.Id for (const p in projectList) { + console.log("p ", p) const opt = document.createElement("option"); - opt.value = projectList[p].projectId; - opt.textContent = projectList[p].projectName; + opt.value = projectList[p].id; + opt.textContent = projectList[p].name; projectListselectBox.appendChild(opt); - } - projectListselectBox.value = "" -} -async function workspaceProjectInit(){ - let currentWorkspaceProjectList = webconsolejs["common/util"].getCurrentWorkspaceProjectList() - if (currentWorkspaceProjectList == null ){ - currentWorkspaceProjectList = await updateWorkspaceProjectList() - webconsolejs["common/util"].setCurrentWorkspaceProjectList(currentWorkspaceProjectList) - } - updateWsSelectBox(currentWorkspaceProjectList) - let workspaceId = webconsolejs["common/util"].getCurrentWorkspace()?.Id - if (workspaceId != "") { - workspaceListselectBox.value = webconsolejs["common/util"].getCurrentWorkspace()?.Id - updatePrjSelectBox(workspaceId) - projectListselectBox.value = webconsolejs["common/util"].getCurrentProject()?.Id; + if (curProjectId != "" && projectList[p].id == curProjectId) { + opt.setAttribute("selected", "selected"); + } } } \ No newline at end of file diff --git a/mc_web_console_front/assets/js/partials/layout/navigatePages.js b/mc_web_console_front/assets/js/partials/layout/navigatePages.js new file mode 100644 index 00000000..fc0f72e7 --- /dev/null +++ b/mc_web_console_front/assets/js/partials/layout/navigatePages.js @@ -0,0 +1,44 @@ +function showSection() { + const sections = document.querySelectorAll('.section'); + sections.forEach(section => section.classList.remove('active')); + const hash = window.location.hash || '#index'; + const activeSection = document.querySelector(hash); + if (activeSection) { + activeSection.classList.add('active'); + } +} + +function hideLoader() { + document.getElementById("loader").classList.remove('active') +} + +export function toggleElement(elem){ + // 자기 자신에 대한 Toggle + if (elem.classList.contains("active")){ + console.log("here") + elem.classList.remove('active') + window.location.hash = "" + }else{ + console.log("zzz") + elem.classList.add('active') + console.log(elem) + } +} + +export function toggleSubElement(elem){ + // 자기 자신에 대한 Toggle + if (elem.classList.contains("active")){ + console.log("subhere") + elem.classList.remove('active') + // window.location.hash = "" + }else{ + console.log("subzzz") + elem.classList.add('active') + console.log(elem) + } +} + + +window.addEventListener('hashchange', showSection); +window.addEventListener('load', showSection); +window.addEventListener('load', hideLoader); \ No newline at end of file diff --git a/mc_web_console_front/assets/js/partials/layout/sidebar.js b/mc_web_console_front/assets/js/partials/layout/sidebar.js index 5df845b0..b39dafe7 100644 --- a/mc_web_console_front/assets/js/partials/layout/sidebar.js +++ b/mc_web_console_front/assets/js/partials/layout/sidebar.js @@ -1,7 +1,12 @@ + +// sidebar.html 에 path 지정 시 id="sidebar_workflow_manage" 3단계로 구성. 3번째 항목의 classList에 active document.addEventListener("DOMContentLoaded", function () { - const path = window.location.pathname.split('/') + const path = window.location.pathname.split('/'); + console.log("path ", path) const depth2 = 'sidebar_'+ path[3] - const depth3 = 'sidebar_'+path[3]+'_'+path[4] + const depth3 = 'sidebar_'+path[3]+'_'+path[4] + + console.log("depth2 ", depth2) document.getElementsByName(depth2).forEach(i => i.classList.add('show', 'active')); document.getElementById(depth3).classList.add('active'); }); \ No newline at end of file diff --git a/mc_web_console_front/assets/js/partials/operation/dashboard/mcisrunning.js b/mc_web_console_front/assets/js/partials/operation/dashboard/mcisrunning.js new file mode 100644 index 00000000..af7249e6 --- /dev/null +++ b/mc_web_console_front/assets/js/partials/operation/dashboard/mcisrunning.js @@ -0,0 +1,587 @@ +console.log("mcisrunning.js"); + +var totalMcisListObj = new Object(); +var totalMcisStatusMap = new Map(); +var totalVmStatusMap = new Map(); +var nsid = "" + +document.addEventListener("DOMContentLoaded", initMcisMngPage); + +// 페이지 로드 시 prj 값 받아와 getMcisList 호출 +async function initMcisMngPage() { + console.log("initMcisMngPage") + + // user의 workspace목록, project 목록 조회 + // workspace list 표시 + // let userWorkspaceProjectList = await webconsolejs["common/util"].getUserWorkspaceProjectList() + // console.log("user workspaceList ", userWorkspaceProjectList) + + let userWorkspaceList = await webconsolejs["common/util"].getWorkspaceListByUser() + console.log("user wslist ", userWorkspaceList) + + let curWorkspace = await webconsolejs["common/util"].getCurrentWorkspace() + let curWorkspaceId = ""; + //let curWorkspaceName = ""; + if( curWorkspace ){ + curWorkspaceId = curWorkspace.Id; + //curWorkspaceName = curWorkspace.Name; + } + + webconsolejs["common/util"].setWorkspaceSelectBox(userWorkspaceList, curWorkspaceId) + + + // workspace, project 가 먼저 설정되어 있어야 한다. + //console.log("get workspace from session " , webconsolejs["common/util"].getCurrentWorkspace()) + console.log("curWorkspaceId", curWorkspaceId) + if( curWorkspaceId == "" || curWorkspaceId == undefined){ + console.log(" curWorkspaceId is not set ") + //alert("workspace 먼저 선택하시오"); + //return; + }else{ + // workspace가 선택되어 있으면 project 목록도 표시 + let userProjectList = await webconsolejs["common/util"].getUserProjectList(curWorkspaceId) + console.log("userProjectList ", userProjectList) + + // project 목록이 있으면 cur project set + let curProjectId = await webconsolejs["common/util"].getCurrentProject()?.Id + console.log("curProjectId", curProjectId) + + webconsolejs["common/util"].setPrjSelectBox(userProjectList, curProjectId) + + // curWorkspace cur project가 모두 선택되어 있으면 mcisList 조회 + if (curProjectId != undefined && curProjectId != "") { + getMcisList(); + }} + // var namespace = webconsolejs["common/util"].getCurrentProject() +} + +async function getMcisList() { + console.log("getMcisList") + var projectId = $("#select-current-project").val() + var projectName = $('#select-current-project').find('option:selected').text(); + // var projectName = $("#select-current-project").text() + // $('#select-current-project').find('option:selected').each(function() { + // projectName = $(this).text(); + // }); + console.log("projectId", projectId) + console.log("projectName", projectName) + nsid = projectName + + // nsid = "project1"; + + var data = { + pathParams: { + nsId: nsid, + // nsId: "testns01", + }, + }; + //var controller = "targetController=getmcislist" + var controller = "/api/" + "getmcislist"; + const response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ) + + // if (response.response.data.status.code != 200 && response.response.data.status.code != 201) { + // alert(response.response.data.responseData.message) + // } else { + var mcisList = response.data.responseData; + console.log("mcisList : ", mcisList); + getMcisListCallbackSuccess(nsid, mcisList); + // } +} +// MCIS 목록 조회 후 화면에 Set + +// Mcis조회 성공시 +function getMcisListCallbackSuccess(caller, mcisList) { + console.log("getMcisListCallbackSuccess"); + + totalMcisListObj = mcisList.mcis; + + setToTalMcisStatus(); // mcis상태 표시 를 위해 필요 + setTotalVmStatus(); // mcis 의 vm들 상태표시 를 위해 필요 + // setTotalConnection();// Mcis의 provider별 connection 표시를 위해 필요 + + displayMcisDashboard(); + + // TODO : map표시 + // // setMap();// MCIS를 가져와서 화면에 뿌려지면 vm정보가 있으므로 Map그리기 + +} + +function setToTalMcisStatus() { + console.log("setToTalMcisStatus"); + try { + for (var mcisIndex in totalMcisListObj) { + var aMcis = totalMcisListObj[mcisIndex]; + + var aMcisStatusCountMap = calculateMcisStatusCount(aMcis); + console.log("aMcis.id : ", aMcis.id); + console.log("mcisStatusMap ::: ", aMcisStatusCountMap); + totalMcisStatusMap.set(aMcis.id, aMcisStatusCountMap); + } + } catch (e) { + console.log("mcis status error", e); + } + displayMcisStatusArea(); +} + +// Mcis 목록에서 vmStatus만 처리 : 화면표시는 display function에서 +function setTotalVmStatus() { + try { + for (var mcisIndex in totalMcisListObj) { + var aMcis = totalMcisListObj[mcisIndex]; + console.log("aMcis : ", aMcis); + var vmStatusCountMap = calculateVmStatusCount(aMcis); + totalVmStatusMap.set(aMcis.id, vmStatusCountMap); + } + } catch (e) { + console.log("mcis status error"); + } + displayVmStatusArea(); +} + +function displayMcisStatusArea() { + console.log("displayMcisStatusArea"); + var sumMcisCnt = 0; + var sumMcisRunningCnt = 0; + var sumMcisStopCnt = 0; + var sumMcisTerminateCnt = 0; + totalMcisStatusMap.forEach((value, key) => { + var statusRunning = value.get("running"); + var statusStop = value.get("stop"); + var statusTerminate = value.get("terminate"); + sumMcisRunningCnt += statusRunning; + sumMcisStopCnt += statusStop; + sumMcisTerminateCnt += statusTerminate; + console.log("totalMcisStatusMap :: ", key, value); + }); + sumMcisCnt = sumMcisRunningCnt + sumMcisStopCnt + sumMcisTerminateCnt; + + $("#total_mcis").text(sumMcisCnt); + $("#mcis_status_running").text(sumMcisRunningCnt); + $("#mcis_status_stopped").text(sumMcisStopCnt); + $("#mcis_status_terminated").text(sumMcisTerminateCnt); + console.log("displayMcisStatusArea "); + console.log("running status count ", $("#mcis_status_running").text()); +} + +// 해당 mcis에서 상태값들을 count : 1개 mcis의 상태는 1개만 있으므로 running, stop, terminate 중 1개만 1, 나머지는 0 +// dashboard, mcis 에서 사용 +function calculateMcisStatusCount(mcisData) { + //O + console.log("calculateMcisStatusCount"); + console.log("mcisData : ", mcisData); + var mcisStatusCountMap = new Map(); + mcisStatusCountMap.set("running", 0); + mcisStatusCountMap.set("stop", 0); // partial 도 stop으로 보고있음. + mcisStatusCountMap.set("terminate", 0); + try { + var mcisStatus = mcisData.status; + var mcisDispStatus = getMcisStatusDisp(mcisStatus); // 화면 표시용 status + + if (mcisStatus != "") { + // mcis status 가 없는 경우는 skip + if (mcisStatusCountMap.has(mcisDispStatus)) { + mcisStatusCountMap.set( + mcisDispStatus, + mcisStatusCountMap.get(mcisDispStatus) + 1 + ); + } + } + } catch (e) { + console.log("mcis status error", e); + } + // console.log(mcisStatusCountMap); + return mcisStatusCountMap; +} + +function calculateVmStatusCount(aMcis) { + // console.log("calculateVmStatusCount") + // console.log(vmList) + var sumVmCnt = 0; + var vmStatusCountMap = new Map(); + vmStatusCountMap.set("running", 0); + vmStatusCountMap.set("stop", 0); // partial 도 stop으로 보고있음. + vmStatusCountMap.set("terminate", 0); + + try { + if (aMcis.statusCount) { + console.log("statusCount part", aMcis); + var statusCountObj = aMcis.statusCount; + console.log(statusCountObj); + var countCreating = statusCountObj.countCreating; + var countFailed = statusCountObj.countFailed; + var countRebooting = statusCountObj.countRebooting; + var countResuming = statusCountObj.countResuming; + var countRunning = statusCountObj.countRunning; + var countSuspended = statusCountObj.countSuspended; + var countSuspending = statusCountObj.countSuspending; + var countTerminated = statusCountObj.countTerminated; + var countTerminating = statusCountObj.countTerminating; + var countTotal = statusCountObj.countTotal; + var countUndefined = statusCountObj.countUndefined; + + var sumEtc = + Number(countCreating) + + Number(countFailed) + + Number(countRebooting) + + Number(countResuming) + + Number(countSuspending) + + Number(countTerminated) + + Number(countTerminating) + + Number(countUndefined); + + vmStatusCountMap.set("running", Number(countRunning)); + vmStatusCountMap.set("stop", Number(countSuspended)); // partial 도 stop으로 보고있음. + vmStatusCountMap.set("terminate", sumEtc); + } else if (aMcis.vm) { + console.log("statusCount part list part"); + vmList = aMcis.vm; + for (var vmIndex in vmList) { + var aVm = vmList[vmIndex]; + var vmStatus = aVm.status; + var vmDispStatus = getVmStatusDisp(vmStatus); + + if (vmStatus != "") { + // vm status 가 없는 경우는 skip + if (vmStatusCountMap.has(vmDispStatus)) { + vmStatusCountMap.set( + vmDispStatus, + vmStatusCountMap.get(vmDispStatus) + 1 + ); + } + } + } + } + } catch (e) { + console.log("mcis status error"); + } + return vmStatusCountMap; +} + +function displayMcisDashboard() { + console.log("displayMcisDashboard"); + if (!isEmpty(totalMcisListObj) && totalMcisListObj.length > 0) { + //totalMcisCnt = mcisList.length; + var addMcis = ""; + for (var mcisIndex in totalMcisListObj) { + var aMcis = totalMcisListObj[mcisIndex]; + console.log("aMcis.id 22: ", aMcis.id) + if (aMcis.id != "") { + addMcis += setMcisListTableRow(aMcis, mcisIndex); + } + } // end of mcis loop + $("#mcisList").empty(); + $("#mcisList").append(addMcis); + console.log("after add", addMcis) + } else { + var addMcis = ""; + addMcis += ""; + addMcis += 'No Data'; + addMcis += ""; + $("#mcisList").empty(); + $("#mcisList").append(addMcis); + } +} + +function setMcisListTableRow(aMcisData, mcisIndex) { + var mcisTableRow = ""; + var mcisStatus = aMcisData.status + var mcisDispStatus = getMcisStatusDisp(mcisStatus);// 화면 표시용 status + + var vmStatusCountMap = totalVmStatusMap.get(aMcisData.id); + var totalVmCountOfMcis = vmStatusCountMap.get('running') + vmStatusCountMap.get('stop') + vmStatusCountMap.get('terminate'); + console.log("totalVmStatusMap", totalVmStatusMap) + // List of Mcis table + try { + + // vm항목 미리 생성 후 mcis 생성할 때 붙임 + var addVm = ""; + var vmListOfMcis = aMcisData.vm; + var vmLength = 9; + if (typeof vmListOfMcis !== 'undefined' && vmListOfMcis.length > 0) { + for (var vmIndex in vmListOfMcis) { + var aVm = vmListOfMcis[vmIndex]; + + var vmName = "" + var vmNamelength = aVm.name + console.log("vmNamelength", vmNamelength) + if (vmNamelength.length > vmLength) { + var vmName = vmNamelength.substring(0, vmLength - 3) + "..."; + console.log("vmNameString", vmName) + console.log("vmNamelength.length", vmNamelength.length) + } else { + vmName = vmNamelength; + console.log("vmName", vmName) + } + + + var vmDispStatus = getVmStatusDisp(aVm.status); + var sumVmCountRunning = vmStatusCountMap.get("running") + var sumVmCountStop = vmStatusCountMap.get("stop") + var sumVmCountTerminate = vmStatusCountMap.get("terminate") + var sumVmCount = sumVmCountRunning + sumVmCountStop + sumVmCountTerminate + // connections + var location = aVm.location; + if (!isEmpty(location)) { + var vmLongitude = location.longitude; + var vmLatitude = location.latitude; + + } + + // vmStatus별 vm 색 설정 + if (vmDispStatus == "running") { + + addVm += '
  • ' + } + if (vmDispStatus == "suspend") { + addVm += '
  • ' + } + if (vmDispStatus == "terminate") { + addVm += '
  • ' + } + + addVm += ' ' + vmName + '' + // addVm += ' ' + (Number(vmIndex) + 1).toString() + '' + // for map : 원래는 vmId, Name등의 정보가 보여져야하나, mcis를 simple로 가져오면 해당 정보가 비어있어 화면상의 mcis이름 과 vm index를 보여주게 함 + // addVm += ' ' + // addVm += ' ' + addVm += ' ' + addVm += ' ' + addVm += ' ' + addVm += ' ' + addVm += ' ' + addVm += ' ' + addVm += '
  • ' + } + } + + mcisTableRow += '
    ' + mcisTableRow += ' ' + mcisTableRow += ' ' + mcisTableRow += '
    ' + mcisTableRow += ' ' + aMcisData.name + '' + mcisTableRow += '
    ' + mcisTableRow += '
    ' + mcisTableRow += ' infra ' + totalVmCountOfMcis + '' + mcisTableRow += ' ( ' + sumVmCountRunning + '' + mcisTableRow += ' / ' + sumVmCountStop + '' + mcisTableRow += ' / ' + sumVmCountTerminate + ') ' + mcisTableRow += '
    ' + mcisTableRow += ' server ' + sumVmCount + '' + mcisTableRow += '
    ' + mcisTableRow += '
      ' + mcisTableRow += addVm + mcisTableRow += '
    ' + mcisTableRow += '
    ' + mcisTableRow += '
    ' + + } catch (e) { + console.log("list of mcis error") + console.log(e) + } + return mcisTableRow; +} + +// dashboard 의 MCIS 목록에서 mcis 선택 : 색상반전, 선택한 mcis id set -> status변경에 사용 +// 1번클릭시 선택 +// 2번 클릭 시 해당 MCIS로 이동 + +var selectedMcisId = "" +var clickCount = 0; + +export function selectMcis(id, name, target, obj) { + + // TODO: navbar 통합 후 MCIS INFO이동 + // var moveUrl = "/webconsole/operation/manage/mcis"; + // window.location.href = moveUrl; + // TODO: navbar 통합 시 선택된 MCIS INFO 열리도록 + console.log("selectMCIS", id, name, target) + selectedMcisId = id + console.log("selectedMcisId", selectedMcisId) + var mcisId = id + var mcisName = name + + $("#mcis_id").val(mcisId) + $("#mcis_name").val(mcisName) + console.log(" mcis_id =" + mcisId + ", mcisName = " + mcisName); + + // active 면 이동한다. + var urlParamMap = new Map(); + urlParamMap.set("mcisID", mcisId) + webconsolejs["common/util"].changePage("McisMng", urlParamMap) + + // 클릭 횟수 변수 선언 + var clickCount = 0; + + // 클릭 이벤트 처리 + // focus 받으면 active, 기존에 받은 곳이 있으면 active 해제 시키고 자신을 active로 + // $(obj).click(function(event) { + // // 클릭 횟수 증가 + // clickCount++; + + // // 단일 클릭 판별 + // if (clickCount === 1) { + // // 단일 클릭! + // console.log("단일 클릭"); + // // 여기에 단일 클릭 시 수행할 로직 작성 + // // 예: 특정 데이터 표시, 메뉴 활성화 등 + // // ... + // } else if (clickCount === 2) { + // // 더블 클릭! + // console.log("더블 클릭"); + // // 여기에 더블 클릭 시 수행할 로직 작성 + // // 예: 특정 페이지로 이동, 모달창 띄우기 등 + // // ... + // } else { + // // 2회 이상 클릭 무시하거나 별도 처리 + // console.log(clickCount + "회 이상 클릭"); + // // ... + // } + + // // 클릭 횟수 초기화 (선택적) + // // setTimeout(function() { + // // clickCount = 0; + // // }, 300); + // }); +} + +export function mcisLifeCycle(type) { + /* + { + "mcisID":mcis01, + "type":reboot + } + */ + + // for (const mcis of checked_array) { + // console.log(mcis.id) + let data = { + pathParams: { + nsId: nsid, + mcisId: selectedMcisId, + }, + queryParams: { + "action": type + } + }; + let controller = "/api/" + "controllifecycle"; + let response = webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + console.log(response) + // } +} + +function getMcisStatusDisp(mcisFullStatus) { + console.log("getMcisStatus " + mcisFullStatus); + var statusArr = mcisFullStatus.split("-"); + var returnStatus = statusArr[0].toLowerCase(); + + if (mcisFullStatus.toLowerCase().indexOf("running") > -1) { + returnStatus = "running"; + } else if (mcisFullStatus.toLowerCase().indexOf("suspend") > -1) { + returnStatus = "stop"; + } else if (mcisFullStatus.toLowerCase().indexOf("terminate") > -1) { + returnStatus = "terminate"; + // TODO : partial도 있는데... 처리를 어떻게 하지?? + } else { + returnStatus = "terminate"; + } + console.log("after status " + returnStatus); + return returnStatus; +} +function isEmpty(str) { + if (typeof str == "undefined" || str == null || str == "") return true; + else return false; +} + +// MCIS List table의 1개 Row Update +function updateMcisListTableRow(aMcisData, mcisIndex) { + + var mcisStatus = aMcisData.status + var mcisProviderNames = getProviderNamesOfMcis(aMcisData.id);//MCIS에 사용 된 provider + var mcisDispStatus = getMcisStatusDisp(mcisStatus);// 화면 표시용 status + + var vmStatusCountMap = totalVmStatusMap.get(aMcisData.id); + var mcisStatusImg = "/assets/img/contents/icon_" + mcisDispStatus + ".png" + + var sumVmCountRunning = vmStatusCountMap.get("running") + var sumVmCountStop = vmStatusCountMap.get("stop") + var sumVmCountTerminate = vmStatusCountMap.get("terminate") + var sumVmCount = sumVmCountRunning + sumVmCountStop + sumVmCountTerminate + + // id="server_info_tr_" + mcisIndex // tr -> 변경없음 + // id="mcisInfo_mcisStatus_icon_" + mcisIndex // icon + $("#mcisInfo_mcisStatus_icon_" + mcisIndex).attr("src", mcisStatusImg); + + // id="mcisInfo_mcisstatus_" + mcisIndex + $("#mcisInfo_mcisstatus_" + mcisIndex).text(mcisStatus) + // id="mcisInfo_mcisName_" + mcisIndex + $("#mcisInfo_mcisName_" + mcisIndex).text(aMcisData.name) + // id="mcisInfo_mcisProviderNames_" + mcisIndex + $("#mcisInfo_mcisProviderNames_" + mcisIndex).text(mcisProviderNames) + // id="mcisInfo_totalVmCountOfMcis_" + mcisIndex + $("#mcisInfo_totalVmCountOfMcis_" + mcisIndex).text(sumVmCount) + // id="mcisInfo_vmstatus_running_" + mcisIndex + $("#mcisInfo_vmstatus_running_" + mcisIndex).text(sumVmCountRunning) + // id="mcisInfo_vmstatus_stop_" + mcisIndex + $("#mcisInfo_vmstatus_stop_" + mcisIndex).text(sumVmCountStop) + // id="mcisInfo_vmstatus_terminate_" + mcisIndex + $("#mcisInfo_vmstatus_terminate_" + mcisIndex).text(sumVmCountTerminate) + // id="mcisInfo_mcisDescription_" + mcisIndex + $("#mcisInfo_mcisDescription_" + mcisIndex).text(sumVmCount) + // id="td_ch_" + mcisIndex // checkbox -> 변경없음 +} + + +// 화면 표시 +function displayVmStatusArea() { + var sumVmCnt = 0; + var sumVmRunningCnt = 0; + var sumVmStopCnt = 0; + var sumVmTerminateCnt = 0; + totalVmStatusMap.forEach((value, key) => { + var statusRunning = value.get("running"); + var statusStop = value.get("stop"); + var statusTerminate = value.get("terminate"); + sumVmRunningCnt += statusRunning; + sumVmStopCnt += statusStop; + sumVmTerminateCnt += statusTerminate; + }); + sumVmCnt = sumVmRunningCnt + sumVmStopCnt + sumVmTerminateCnt; + $("#total_vm").text(sumVmCnt); + $("#vm_status_running").text(sumVmRunningCnt); + $("#vm_status_stopped").text(sumVmStopCnt); + $("#vm_status_terminated").text(sumVmTerminateCnt); +} + + + +// VM 상태를 UI에서 표현하는 방식으로 변경 +function getVmStatusDisp(vmFullStatus) { + console.log("getVmStatusDisp " + vmFullStatus); + var returnVmStatus = vmFullStatus.toLowerCase() // 소문자로 변환 + + const VM_STATUS_RUNNING = "running" + const VM_STATUS_STOPPED = "stop" + const VM_STATUS_RESUMING = "resuming"; + const VM_STATUS_INCLUDE = "include" + const VM_STATUS_SUSPENDED = "suspended" + const VM_STATUS_TERMINATED = "terminated" + const VM_STATUS_FAILED = "failed" + + if (returnVmStatus == VM_STATUS_RUNNING) { + returnVmStatus = "running" + } else if (returnVmStatus == VM_STATUS_TERMINATED) { + returnVmStatus = "terminate" + } else if (returnVmStatus == VM_STATUS_FAILED) { + returnVmStatus = "terminate" + } else { + returnVmStatus = "stop" + } + return returnVmStatus +} + diff --git a/mc_web_console_front/assets/js/partials/operation/dashboard/mcisserver.js b/mc_web_console_front/assets/js/partials/operation/dashboard/mcisserver.js new file mode 100644 index 00000000..78e73f26 --- /dev/null +++ b/mc_web_console_front/assets/js/partials/operation/dashboard/mcisserver.js @@ -0,0 +1,330 @@ +console.log("mcicserver.js"); + +var totalMcisListObj = new Object(); +var totalMcisStatusMap = new Map(); +var totalVmStatusMap = new Map(); +var nsid = "" + +document.addEventListener("DOMContentLoaded", initMcisMngPage); + +// 모든 Page(화면)에서 1개의 initPage()를 만든다. +// 이유는 project변경 시 화면 재구성이 필요한 경우가 있기 때문 +async function initMcisMngPage() { + console.log("initMcisMngPage") + + // user의 workspace목록, project 목록 조회 + // workspace list 표시 + // let userWorkspaceProjectList = await webconsolejs["common/util"].getUserWorkspaceProjectList() + // console.log("user workspaceList ", userWorkspaceProjectList) + + let userWorkspaceList = await webconsolejs["common/util"].getWorkspaceListByUser() + console.log("user wslist ", userWorkspaceList) + + let curWorkspace = await webconsolejs["common/util"].getCurrentWorkspace() + let curWorkspaceId = ""; + //let curWorkspaceName = ""; + if (curWorkspace) { + curWorkspaceId = curWorkspace.Id; + //curWorkspaceName = curWorkspace.Name; + } + + webconsolejs["common/util"].setWorkspaceSelectBox(userWorkspaceList, curWorkspaceId) + + + // workspace, project 가 먼저 설정되어 있어야 한다. + //console.log("get workspace from session " , webconsolejs["common/util"].getCurrentWorkspace()) + console.log("curWorkspaceId", curWorkspaceId) + if (curWorkspaceId == "" || curWorkspaceId == undefined) { + console.log(" curWorkspaceId is not set ") + //alert("workspace 먼저 선택하시오"); + //return; + } else { + // workspace가 선택되어 있으면 project 목록도 표시 + let userProjectList = await webconsolejs["common/util"].getUserProjectList(curWorkspaceId) + console.log("userProjectList ", userProjectList) + + // project 목록이 있으면 cur project set + let curProjectId = await webconsolejs["common/util"].getCurrentProject()?.Id + console.log("curProjectId", curProjectId) + + webconsolejs["common/util"].setPrjSelectBox(userProjectList, curProjectId) + + // curWorkspace cur project가 모두 선택되어 있으면 mcisList 조회 + if (curProjectId != undefined && curProjectId != "") { + getMcisList(); + } + // var namespace = webconsolejs["common/util"].getCurrentProject() + } +} + +// project(namespace)를 받아와 McisList 호출 +async function getMcisList() { + console.log("getMcisList") + var projectId = $("#select-current-project").val() + var projectName = $('#select-current-project').find('option:selected').text(); + + console.log("projectId", projectId) + console.log("projectName", projectName) + nsid = projectName + + var data = { + pathParams: { + nsId: nsid, + }, + }; + //var controller = "targetController=getmcislist" + var controller = "/api/" + "getmcislist"; + const response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ) + + // if (response.response.data.status.code != 200 && response.response.data.status.code != 201) { + // alert(response.response.data.responseData.message) + // } else { + var mcisList = response.data.responseData; + console.log("mcisList : ", mcisList); + + // McisList 호출 성공 시 + getMcisListCallbackSuccess(nsid, mcisList); + // } +} +// MCIS 목록 조회 후 화면에 Set + + +// Mcis 목록 조회 성공시 호출하는 function +function getMcisListCallbackSuccess(caller, mcisList) { + console.log("getMcisListCallbackSuccess"); + + totalMcisListObj = mcisList.mcis; + + setToTalMcisStatus(); // mcis상태 표시 + setTotalVmStatus(); // mcis 의 vm들 상태표시 + // setTotalConnection();// Mcis의 provider별 connection 표시를 위해 필요 + + // displayMcisDashboard(); + + // // setMap();// MCIS를 가져와서 화면에 뿌려지면 vm정보가 있으므로 Map그리기 + + // AjaxLoadingShow(false); +} + +// 화면 표시용 mcis status set 화면표시는 display function에서 +function setToTalMcisStatus() { + console.log("setToTalMcisStatus"); + try { + for (var mcisIndex in totalMcisListObj) { + var aMcis = totalMcisListObj[mcisIndex]; + + var aMcisStatusCountMap = calculateMcisStatusCount(aMcis); + console.log("aMcis.id : ", aMcis.id); + console.log("mcisStatusMap ::: ", aMcisStatusCountMap); + totalMcisStatusMap.set(aMcis.id, aMcisStatusCountMap); + } + } catch (e) { + console.log("mcis status error", e); + } + displayMcisStatusArea(); +} + +// Mcis 목록에서 vmStatus만 처리 : 화면표시는 display function에서 +function setTotalVmStatus() { + try { + for (var mcisIndex in totalMcisListObj) { + var aMcis = totalMcisListObj[mcisIndex]; + console.log("aMcis : ", aMcis); + var vmStatusCountMap = calculateVmStatusCount(aMcis); + totalVmStatusMap.set(aMcis.id, vmStatusCountMap); + } + } catch (e) { + console.log("mcis status error"); + } + displayVmStatusArea(); +} + +// mcis 상태 별 상태 표시 +function displayMcisStatusArea() { + console.log("displayMcisStatusArea"); + var sumMcisCnt = 0; + var sumMcisRunningCnt = 0; + var sumMcisStopCnt = 0; + var sumMcisTerminateCnt = 0; + totalMcisStatusMap.forEach((value, key) => { + var statusRunning = value.get("running"); + var statusStop = value.get("stop"); + var statusTerminate = value.get("terminate"); + sumMcisRunningCnt += statusRunning; + sumMcisStopCnt += statusStop; + sumMcisTerminateCnt += statusTerminate; + console.log("totalMcisStatusMap :: ", key, value); + }); + sumMcisCnt = sumMcisRunningCnt + sumMcisStopCnt + sumMcisTerminateCnt; + + $("#total_mcis").text(sumMcisCnt); + $("#mcis_status_running").text(sumMcisRunningCnt); + $("#mcis_status_stopped").text(sumMcisStopCnt); + $("#mcis_status_terminated").text(sumMcisTerminateCnt); + console.log("displayMcisStatusArea "); + console.log("running status count ", $("#mcis_status_running").text()); +} + +// 해당 mcis에서 상태값들을 count : 1개 mcis의 상태는 1개만 있으므로 running, stop, terminate 중 1개만 1, 나머지는 0 +// dashboard, mcis 에서 사용 +function calculateMcisStatusCount(mcisData) { + + console.log("calculateMcisStatusCount"); + console.log("mcisData : ", mcisData); + var mcisStatusCountMap = new Map(); + mcisStatusCountMap.set("running", 0); + mcisStatusCountMap.set("stop", 0); // partial 도 stop으로 보고있음. + mcisStatusCountMap.set("terminate", 0); + try { + var mcisStatus = mcisData.status; + var mcisDispStatus = getMcisStatusDisp(mcisStatus); // 화면 표시용 status + + if (mcisStatus != "") { + // mcis status 가 없는 경우는 skip + if (mcisStatusCountMap.has(mcisDispStatus)) { + mcisStatusCountMap.set( + mcisDispStatus, + mcisStatusCountMap.get(mcisDispStatus) + 1 + ); + } + } + } catch (e) { + console.log("mcis status error", e); + } + + return mcisStatusCountMap; +} + +// vm의 상태별 count +function calculateVmStatusCount(aMcis) { + // console.log("calculateVmStatusCount") + // console.log(vmList) + var sumVmCnt = 0; + var vmStatusCountMap = new Map(); + vmStatusCountMap.set("running", 0); + vmStatusCountMap.set("stop", 0); // partial 도 stop으로 보고있음. + vmStatusCountMap.set("terminate", 0); + + try { + if (aMcis.statusCount) { + console.log("statusCount part", aMcis); + var statusCountObj = aMcis.statusCount; + console.log(statusCountObj); + var countCreating = statusCountObj.countCreating; + var countFailed = statusCountObj.countFailed; + var countRebooting = statusCountObj.countRebooting; + var countResuming = statusCountObj.countResuming; + var countRunning = statusCountObj.countRunning; + var countSuspended = statusCountObj.countSuspended; + var countSuspending = statusCountObj.countSuspending; + var countTerminated = statusCountObj.countTerminated; + var countTerminating = statusCountObj.countTerminating; + var countTotal = statusCountObj.countTotal; + var countUndefined = statusCountObj.countUndefined; + + var sumEtc = + Number(countCreating) + + Number(countFailed) + + Number(countRebooting) + + Number(countResuming) + + Number(countSuspending) + + Number(countTerminated) + + Number(countTerminating) + + Number(countUndefined); + + vmStatusCountMap.set("running", Number(countRunning)); + vmStatusCountMap.set("stop", Number(countSuspended)); // partial 도 stop으로 보고있음. + vmStatusCountMap.set("terminate", sumEtc); + } else if (aMcis.vm) { + console.log("statusCount part list part"); + vmList = aMcis.vm; + for (var vmIndex in vmList) { + var aVm = vmList[vmIndex]; + var vmStatus = aVm.status; + var vmDispStatus = getVmStatusDisp(vmStatus); + + if (vmStatus != "") { + // vm status 가 없는 경우는 skip + if (vmStatusCountMap.has(vmDispStatus)) { + vmStatusCountMap.set( + vmDispStatus, + vmStatusCountMap.get(vmDispStatus) + 1 + ); + } + } + } + } + } catch (e) { + console.log("mcis status error"); + } + return vmStatusCountMap; +} + +// mcis 상태 표시 +function getMcisStatusDisp(mcisFullStatus) { + console.log("getMcisStatus " + mcisFullStatus); + var statusArr = mcisFullStatus.split("-"); + var returnStatus = statusArr[0].toLowerCase(); + + if (mcisFullStatus.toLowerCase().indexOf("running") > -1) { + returnStatus = "running"; + } else if (mcisFullStatus.toLowerCase().indexOf("suspend") > -1) { + returnStatus = "stop"; + } else if (mcisFullStatus.toLowerCase().indexOf("terminate") > -1) { + returnStatus = "terminate"; + // TODO : partial도 있는데... 처리를 어떻게 하지?? + } else { + returnStatus = "terminate"; + } + console.log("after status " + returnStatus); + return returnStatus; +} + +// vm 화면 표시 +function displayVmStatusArea() { + var sumVmCnt = 0; + var sumVmRunningCnt = 0; + var sumVmStopCnt = 0; + var sumVmTerminateCnt = 0; + totalVmStatusMap.forEach((value, key) => { + var statusRunning = value.get("running"); + var statusStop = value.get("stop"); + var statusTerminate = value.get("terminate"); + sumVmRunningCnt += statusRunning; + sumVmStopCnt += statusStop; + sumVmTerminateCnt += statusTerminate; + }); + sumVmCnt = sumVmRunningCnt + sumVmStopCnt + sumVmTerminateCnt; + $("#total_vm").text(sumVmCnt); + $("#vm_status_running").text(sumVmRunningCnt); + $("#vm_status_stopped").text(sumVmStopCnt); + $("#vm_status_terminated").text(sumVmTerminateCnt); +} + +// VM 상태를 UI에서 표현하는 방식으로 변경 +function getVmStatusDisp(vmFullStatus) { + console.log("getVmStatusDisp " + vmFullStatus); + var returnVmStatus = vmFullStatus.toLowerCase() // 소문자로 변환 + + const VM_STATUS_RUNNING = "running" + const VM_STATUS_STOPPED = "stop" + const VM_STATUS_RESUMING = "resuming"; + const VM_STATUS_INCLUDE = "include" + const VM_STATUS_SUSPENDED = "suspended" + const VM_STATUS_TERMINATED = "terminated" + const VM_STATUS_FAILED = "failed" + + if (returnVmStatus == VM_STATUS_RUNNING) { + returnVmStatus = "running" + } else if (returnVmStatus == VM_STATUS_TERMINATED) { + returnVmStatus = "terminate" + } else if (returnVmStatus == VM_STATUS_FAILED) { + returnVmStatus = "terminate" + } else { + returnVmStatus = "stop" + } + return returnVmStatus +} \ No newline at end of file diff --git a/mc_web_console_front/assets/js/partials/operation/dashboard/mcisserverprint.js b/mc_web_console_front/assets/js/partials/operation/dashboard/mcisserverprint.js new file mode 100644 index 00000000..4131fff5 --- /dev/null +++ b/mc_web_console_front/assets/js/partials/operation/dashboard/mcisserverprint.js @@ -0,0 +1,415 @@ +console.log("mcisserverprint.js"); + + +function mcisLifeCycle(){ + +} + + +// message를 표현할 alert 창 +function commonAlert(alertMessage) { + console.log(alertMessage); + // $('#alertText').text(alertMessage); + $('#alertText').html(alertMessage); + $("#alertArea").modal(); +} +// alert창 닫기 +function commonAlertClose() { + $("#alertArea").modal("hide"); +} + + +// message를 표현할 alert 창 : 생성 결과를 표시하는 Alert로 commonAlert와 동일하나 닫힐 때 event처리를 할 수 있게 +// 사용할 화면에서 $('#alertResultArea').on('hidden.bs.modal', function () { // 수행할 일 또는 함수 호출 // }) +function commonResultAlert(alertMessage) { + console.log(alertMessage); + // $('#alertText').text(alertMessage); + $('#alertResultText').html(alertMessage); + $("#alertResultArea").modal(); +} +// alert창 닫기 +function commonResultAlertClose() { + $("#alertResultArea").modal("hide"); +} + +// 에러 메세지 alert 통일 용 +function commonErrorAlert(statusCode, message) { + commonAlert("Error(" + statusCode + ") : " + message); + +} + +// confirm modal창 보이기 modal창이 열릴 때 해당 창의 text 지정, close될 때 action 지정 +export function commonConfirmOpen(targetAction, caller) { + console.log("commonConfirmOpen : " + targetAction) + + // [ id , 문구] + let confirmModalTextMap = new Map( + [ + ["CreateSnapshot", "Would you like to Create Snapshot?"], + ["DeleteDataDisk", "Would you like to Delete Disk?"], + ["DeleteMyImage", "Would you like to Delete MyImage?"], + ["Logout", "Would you like to logout?"], + ["Config", "Would you like to set Cloud config ?"], + ["SDK", "Would you like to set Cloud Driver SDK ?"], + ["Credential", "Would you like to set Credential ?"], + ["Region", "Would you like to set Region ?"], + ["Provider", "Would you like to set Cloud Provider ?"], + + ["MoveToConnection", "Would you like to set Cloud config ?"], + ["ChangeConnection", "Would you like to change Cloud connection ?"], + ["DeleteCloudConnection", "Would you like to delete
    the Cloud connection? "], + + ["DeleteCredential", "Would you like to delete
    the Credential? "], + ["DeleteDriver", "Would you like to delete
    the Driver? "], + ["DeleteRegion", "Would you like to delete
    the Region? "], + + + // ["IdPassRequired", "ID/Password required !"], --. 이거는 confirm이 아니잖아 + ["idpwLost", "Illegal account / password 다시 입력 하시겠습니까?"], + ["ManageNS", "Would you like to manage
    Name Space?"], + ["NewNS", "Would you like to add a new Name Space?"], + ["AddNewNameSpace", "Would you like to register NameSpace
    Resource ?"], + ["NameSpace", "Would you like to move
    selected NameSpace?"], + ["ChangeNameSpace", "Would you like to move
    selected NameSpace?"], + ["DeleteNameSpace", "Would you like to delete
    selected NameSpace?"], + + ["AddNewVpc", "Would you like to create a new Network
    Resource ?"], + ["DeleteVpc", "Are you sure to delete this Network
    Resource ?"], + + ["AddNewSecurityGroup", "Would you like to create a new Security
    Resource ?"], + ["DeleteSecurityGroup", "Would you like to delete Security
    Resource ?"], + + ["AddNewSshKey", "Would you like to create a new SSH key
    Resource ?"], + ["DeleteSshKey", "Would you like to delete SSH key
    Resource ?"], + + ["AddNewVirtualMachineImage", "Would you like to register Image
    Resource ?"], + ["DeleteVirtualMachineImage", "Would you like to un-register Image
    Resource ?"], + ["FetchImages", "Would you like to fetch images
    to this NameSpace ?"], + + ["AddNewVmSpec", "Would you like to register Spec
    Resource ?"], + ["DeleteVmSpec", "Would you like to un-register Spec
    Resource ?"], + ["FetchSpecs", "Would you like to fetch Spec
    to this NameSpace ?"], + + ["GotoMonitoringPerformance", "Would you like to view performance
    for MCIS ?"], + ["GotoMonitoringFault", "Would you like to view fault
    for MCIS ?"], + ["GotoMonitoringCost", "Would you like to view cost
    for MCIS ?"], + ["GotoMonitoringUtilize", "Would you like to view utilize
    for MCIS ?"], + + ["McisLifeCycleReboot", "Would you like to reboot MCIS ?"],// mcis_life_cycle('reboot') + ["McisLifeCycleSuspend", "Would you like to suspend MCIS ?"],//onclick="mcis_life_cycle('suspend') + ["McisLifeCycleResume", "Would you like to resume MCIS ?"],//onclick="mcis_life_cycle('resume')" + ["McisLifeCycleTerminate", "Would you like to terminate MCIS ?"],//onclick="mcis_life_cycle('terminate') + ["McisManagement", "Would you like to manage MCIS ?"],// 해당 function 없음... + ["MoveToMcisManagement", "Would you like to manage MCIS ?"], + ["MoveToMcisManagementFromDashboard", "Would you like to manage MCIS ?"], + + ["AddNewMcis", "Would you like to create MCIS ?"], + ["AddNewMcisDynamic", "Would you like to create MCIS ?"], + ["DeleteMcis", "Are you sure to delete this MCIS? "], + ["ImportScriptOfMcis", "Would you like to import MCIS script? "], + ["ExportScriptOfMcis", "Would you like to export MCIS script? "], + ["ShowMonitoring", "Would you like to go to the Monitoring page?"], + + ["AddNewVmOfMcis", "Would you like to add a new VM to this MCIS ?"], + ["DeployServer", "Would you like to deploy?"], + + ["VmLifeCycle", "Would you like to view Server ?"], + ["VmLifeCycleReboot", "Would you like to reboot VM ?"], //onclick="vm_life_cycle('reboot')" + ["VmLifeCycleSuspend", "Would you like to suspend VM ?"], // onclick="vm_life_cycle('suspend')" + ["VmLifeCycleResume", "Would you like to resume VM ?"], // onclick="vm_life_cycle('resume')" + ["VmLifeCycleTerminate", "Would you like to terminate VM ?"], // onclick="vm_life_cycle('terminate')" + ["VmManagement", "Would you like to manage VM ?"], // 해당 function 없음 + ["AddNewVm", "Would you like to add VM ?"], //onclick="vm_add()" + ["ExportVmScriptOfMcis", "Would you like to export VM script ?"], //onclick="vm_add()" + + + ["DifferentConnection", "Do you want to set different connectionName?"], + ["DifferentConnectionAtSecurityGroup", "Do you want to set different connectionName?"], + ["DifferentConnectionAtAssistPopup", "Do you want to set different connectionName?"], + + ["AddMonitoringAlertPolicy", "Would you like to register Threshold ?"], + ["DeleteMonitoringAlertPolicy", "Are you sure to delete this Threshold ?"], + ["AddNewMcks", "Would you like to create MCKS ?"], + ["DeleteMcks", "Are you sure to delete this MCKS? "], + ["AddNewNodeOfMcks", "Would you like to add a new Node to this MCKS ?"], + ["DeleteNodeOfMcks", "Would you like to delete a Node of this MCKS ?"], + + + ["AddMonitoringAlertEventHandler", "Would you like to add
    Monitoring Alert Event-Handler ?"], + ["deleteMonitoringAlertEventHandler", "Are you sure to delete
    this Monitoring Alert Event-Handler?"], + + ["RegisterRecommendSpec", "현재 해당 connection에서 사용가능한 spec 이 없습니다. 등록 하시겠습니까?"], + + ["DeleteNlb", "Would you like to delete NLB ?"], + + ["AddNewPmks", "Would you like to create PMKS ?"], + ["DeletePmks", "Are you sure to delete this PMKS? "], + ["AddNewNodeGroupOfPmks", "Would you like to add a new NodeGroup to this PMKS ?"], + ["DeleteNodeGroupOfPmks", "Would you like to delete a NodeGroup of this PMKS ?"], + ] + ); + console.log(confirmModalTextMap.get(targetAction)); + try { + // $('#modalText').text(targetText);// text아니면 html로 해볼까? 태그있는 문구가 있어서 + //$('#modalText').text(confirmModalTextMap.get(targetAction)); + $('#confirmText').html(confirmModalTextMap.get(targetAction)); + $('#confirmOkAction').val(targetAction); + console.log("caller : ", caller); + $('#confirmCaller').val(caller); + + if (targetAction == "Region") { + // button에 target 지정 + // data-target="#Add_Region_Register" + // TODO : confirm 으로 물어본 뒤 OK버튼 클릭 시 targetDIV 지정하도록 + } + $('#confirmArea').modal(); + } catch (e) { + console.log(e); + alert(e); + } +} + +// confirm modal창 보이기 modal창이 열릴 때 해당 창의 text 지정, close될 때 action 지정, text 내용 전송. caller : 구분자 +function commonConfirmMsgOpen(targetAction, message, caller) { + console.log("commonConfirmMsgOpen : " + targetAction) + + try { + $('#confirmText').html(message); + $('#confirmOkAction').val(targetAction); + $('#confirmCaller').val(caller); + + $('#confirmArea').modal(); + } catch (e) { + console.log(e); + alert(e); + } +} + +// confirm modal창에서 ok버튼 클릭시 수행할 method 지정 +function commonConfirmOk() { + //modalArea + var targetAction = $('#confirmOkAction').val(); + var caller = $('#confirmCaller').val(); + if (targetAction == "Logout") { + // Logout처리하고 index화면으로 간다. Logout ==> cookie expire + // location.href="/logout" + var targetUrl = "/logout" + changePage(targetUrl) + + } else if (targetAction == "MoveToConnection") { + var targetUrl = "/setting/connections/cloudconnectionconfig/mngform" + changePage(targetUrl) + } else if (targetAction == "ChangeConnection") { // recommendvm에서 다른 connection 선택 시 + changeCloudConnection() + } else if (targetAction == "DeleteCloudConnection") { + deleteCloudConnection(); + } else if (targetAction == "Config") { + //id="Config" + console.log("commonConfirmOk " + targetAction); + } else if (targetAction == "SDK") { + //id="SDK" + console.log("commonConfirmOk " + targetAction); + } else if (targetAction == "DeleteCredential") { + deleteCredential(); + } else if (targetAction == "DeleteDriver") { + deleteDriver(); + } else if (targetAction == "DeleteRegion") { + deleteRegion(); + + } else if (targetAction == "Credential") { + //id="Credential" + console.log("commonConfirmOk " + targetAction); + } else if (targetAction == "Region") { + //id="Region" + console.log("commonConfirmOk " + targetAction); + } else if (targetAction == "Provider") { + //id="Provider" + console.log("commonConfirmOk " + targetAction); + } else if (targetAction == "required") {//-- IdPassRequired + console.log("commonConfirmOk " + targetAction); + } else if (targetAction == "idpwLost") {//-- + console.log("commonConfirmOk " + targetAction); + } else if (targetAction == "ManageNS") {//-- ManageNS + var targetUrl = "/setting/namespaces/namespace/mngform" + changePage(targetUrl) + } else if (targetAction == "NewNS") {//-- NewNS + var targetUrl = "/setting/namespaces/namespace/mngform" + changePage(targetUrl) + } else if (targetAction == "ChangeNameSpace") {//-- ChangeNameSpace + var changeNameSpaceID = $("#tempSelectedNameSpaceID").val(); + setDefaultNameSpace(changeNameSpaceID) + } else if (targetAction == "AddNewNameSpace") {//-- AddNewNameSpace + displayNameSpaceInfo("REG") + goFocus('ns_reg');// 해당 영역으로 scroll + } else if (targetAction == "DeleteNameSpace") { + deleteNameSpace() + } else if (targetAction == "AddNewVpc") { + displayVNetInfo("REG") + goFocus('vnetCreateBox'); + } else if (targetAction == "DeleteVpc") { + deleteVPC() + } else if (targetAction == "AddNewSecurityGroup") { + displaySecurityGroupInfo("REG") + goFocus('securityGroupCreateBox'); + } else if (targetAction == "DeleteSecurityGroup") { + deleteSecurityGroup() + } else if (targetAction == "AddNewSshKey") { + displaySshKeyInfo("REG") + goFocus('sshKeyCreateBox'); + } else if (targetAction == "DeleteSshKey") { + deleteSshKey() + } else if (targetAction == "AddNewVirtualMachineImage") { + displayVirtualMachineImageInfo("REG") + goFocus('virtualMachineImageCreateBox'); + } else if (targetAction == "DeleteVirtualMachineImage") { + deleteVirtualMachineImage() + } else if (targetAction == "FetchImages") { + getCommonFetchImages(); + } else if (targetAction == "AddNewVmSpec") { + displayVmSpecInfo("REG") + goFocus('vmSpecCreateBox'); + } else if (targetAction == "ExportVmScriptOfMcis") { + vmScriptExport(); + } else if (targetAction == "DeleteVmSpec") { + deleteVmSpec(); + } else if (targetAction == "FetchSpecs") { + var connectionName = $("#regConnectionName").val(); + putFetchSpecs(connectionName); + } else if (targetAction == "GotoMonitoringPerformance") { + // alert("모니터링으로 이동 GotoMonitoringPerformance") + // location.href ="";//../operation/Monitoring_Mcis.html + var targetUrl = "/operation/monitorings/mcismng/mngform" + changePage(targetUrl) + } else if (targetAction == "GotoMonitoringFault") { + // alert("모니터링으로 이동 GotoMonitoringFault") + // location.href ="";//../operation/Monitoring_Mcis.html + var targetUrl = "/operation/monitorings/mcismng/mngform" + changePage(targetUrl) + } else if (targetAction == "GotoMonitoringCost") { + // alert("모니터링으로 이동 GotoMonitoringCost") + // location.href ="";//../operation/Monitoring_Mcis.html + var targetUrl = "/operation/monitorings/mcismng/mngform" + changePage(targetUrl) + } else if (targetAction == "GotoMonitoringUtilize") { + // alert("모니터링으로 이동 GotoMonitoringUtilize") + // location.href ="";//../operation/Monitoring_Mcis.html + var targetUrl = "/operation/monitorings/mcismng/mngform" + changePage(targetUrl) + } else if (targetAction == "McisLifeCycleReboot") { + callMcisLifeCycle('reboot') + } else if (targetAction == "McisLifeCycleSuspend") { + callMcisLifeCycle('suspend') + } else if (targetAction == "McisLifeCycleResume") { + callMcisLifeCycle('resume') + } else if (targetAction == "McisLifeCycleTerminate") { + callMcisLifeCycle('terminate') + } else if (targetAction == "McisManagement") { + alert("수행할 function 정의되지 않음"); + } else if (targetAction == "MoveToMcisManagementFromDashboard") { + var mcisID = $("#mcis_id").val(); + var targetUrl = "/operation/manages/mcismng/mngform?mcisid=" + mcisID; + changePage(targetUrl) + } else if (targetAction == "MoveToMcisManagement") { + var targetUrl = "/operation/manages/mcismng/mngform"; + changePage(targetUrl) + } else if (targetAction == "AddNewMcis") { + // $('#loadingContainer').show(); + // location.href ="/operation/manages/mcis/regform/"; + var targetUrl = "/operation/manages/mcismng/regform"; + changePage(targetUrl) + } else if (targetAction == "DeleteMcis") { + deleteMCIS(); + } else if (targetAction == "DeployServer") { + btn_deploy(); + } else if (targetAction == "ImportScriptOfMcis") { + mcisScriptImport(); + } else if (targetAction == "ExportScriptOfMcis") { + mcisScriptExport(); + } else if (targetAction == "ShowMonitoring") { + var mcisID = $("#mcis_id").val(); + var targetUrl = "/operation/monitorings/mcismonitoring/mngform?mcisId=" + mcisID; + changePage(targetUrl) + } else if (targetAction == "VmLifeCycle") { + alert("수행할 function 정의되지 않음"); + } else if (targetAction == "VmLifeCycleReboot") { + vmLifeCycle('reboot') + } else if (targetAction == "VmLifeCycleSuspend") { + vmLifeCycle('suspend') + } else if (targetAction == "VmLifeCycleResume") { + vmLifeCycle('resume') + } else if (targetAction == "VmLifeCycleTerminate") { + vmLifeCycle('terminate') + } else if (targetAction == "VmManagement") { + alert("수행할 function 정의되지 않음"); + } else if (targetAction == "AddNewVm") { + addNewVirtualMachine() + } else if (targetAction == "AddNewVmOfMcis") { + addNewVirtualMachine() + } else if (targetAction == "ExportVmScriptOfMcis") { + vmScriptExport(); + } else if (targetAction == "--") { + addNewVirtualMachine() + } else if (targetAction == "monitoringConfigPolicyConfig") { + regMonitoringConfigPolicy() + } else if (targetAction == "DifferentConnection") { + setAndClearByDifferentConnectionName(caller); + } else if (targetAction == "DifferentConnectionAtSecurityGroup") { + uncheckDifferentConnectionAtSecurityGroup(); + } else if (targetAction == "DifferentConnectionAtAssistPopup") { + // connection이 다른데도 set 한다고 하면 이전에 설정한 값들을 초기화 한 후 set한다. + applyAssistValues(caller); + } else if (targetAction == "AddMonitoringAlertPolicy") { + addMonitoringAlertPolicy(); + } else if (targetAction == "DeleteMonitoringAlertPolicy") { + deleteMonitoringAlertPolicy(); + } else if (targetAction == "AddNewMcks") { + var targetUrl = "/operation/manages/mcksmng/regform"; + changePage(targetUrl) + } else if (targetAction == "AddNewNodeOfMcks") { + addNewNode(); + } else if (targetAction == "DeleteNodeOfMcks") { + deleteNodeOfMcks(); + } else if (targetAction == "AddMonitoringAlertEventHandler") { + addMonitoringAlertEventHandler(); + } else if (targetAction == "deleteMonitoringAlertEventHandler") { + deleteMonitoringAlertEventHandler(); + } else if (targetAction == "DeleteMcks") { + deleteMCKS(); + } else if (targetAction == "RegisterRecommendSpec") { + commonPromptOpen("RegisterRecommendSpec") + } else if (targetAction == "AddNewMcisDynamic") { + createMcisDynamic() + } else if (targetAction == "DeleteDataDisk") { + deleteDataDisk(); + + } else if (targetAction == "DeleteMyImage") { + deleteMyImageDisk(); + + } else if (targetAction == "CreateSnapshot") { + commonPromptOk + createSnapshot(); + + } else if (targetAction == "DeleteNlb") { + deleteNlb(); + } else if (targetAction == "AddNewPmks") { + changePage("PmksClusterRegForm"); + } else if (targetAction == "DeletePmks") { + deleteCluster(); + } else if (targetAction == "AddNewNodeGroupOfPmks") { + changePage("PmksNodeGroupRegForm"); + } else if (targetAction == "DeleteNodeGroupOfPmks") { + deleteNodeGroupOfPmks(); + } else { + alert("수행할 function 정의되지 않음 " + targetAction); + } + console.log("commonConfirmOk " + targetAction); + commonConfirmClose(); +} + +// confirm modal창 닫기. setting값 초기화 +function commonConfirmClose() { + $('#confirmText').text(''); + $('#confirmOkAction').val(''); + // $('#modalArea').hide(); + $("#confirmArea").modal("hide"); +} diff --git a/mc_web_console_front/assets/js/partials/operation/manage/mciscreate.js b/mc_web_console_front/assets/js/partials/operation/manage/mciscreate.js new file mode 100644 index 00000000..dfb184a7 --- /dev/null +++ b/mc_web_console_front/assets/js/partials/operation/manage/mciscreate.js @@ -0,0 +1,670 @@ +import { TabulatorFull as Tabulator } from "tabulator-tables"; +//import { selectedMcisObj } from "./mcis"; +//document.addEventListener("DOMContentLoaded", initMcisCreate) // page가 아닌 partials에서는 제거 + +// create page 가 load 될 때 실행해야 할 것들 정의 +export function initMcisCreate(){ + console.log("initMcisCreate") + + // partial init functions + + webconsolejs["partials/operation/manage/serverrecommandation"].initServerRecommandation(webconsolejs["partials/operation/manage/mciscreate"].callbackServerRecommandation);// recommand popup에서 사용하는 table 정의. +} + +// callback PopupData +export function callbackServerRecommandation(vmSpec){ + console.log("callbackServerRecommandation") + + $("#ep_provider").val(vmSpec.provider) + $("#ep_connectionName").val(vmSpec.connectionName) + $("#ep_specId").val(vmSpec.specName) + $("#ep_imageId").val(vmSpec.imageName) + $("#ep_commonSpecId").val(vmSpec.commonSpecId) + + getCommonLookupDiskInfo(vmSpec.provider, vmSpec.connectionName) +} + +var createMcisListObj = new Object(); +var isVm = false // mcis 생성(false) / vm 추가(true) +var Express_Server_Config_Arr = new Array(); +var express_data_cnt = 0 + + +// 서버 더하기버튼 클릭시 서버정보 입력area 보이기/숨기기 +// isExpert의 체크 여부에 따라 바뀜. +// newServers 와 simpleServers가 있음. +export function displayNewServerForm() { + + var div = document.getElementById("server_configuration"); + webconsolejs["partials/layout/navigatePages"].toggleElement(div) + + + // var expressServerConfig = $("#expressServerConfig"); + // var deploymentAlgo = $("#placement_algo").val(); + // var simpleServerConfig = $("#simpleServerConfig"); + // var expertServerConfig = $("#expertServerConfig"); + // var importServerConfig = $("#importServerConfig"); + // var expressServerConfig = $("#expressServerConfig"); + // console.log("is import = " + IsImport + " , deploymentAlgo " + deploymentAlgo) + // // if ($("#isImport").is(":checked")) { + // if (IsImport) { + // simpleServerConfig.removeClass("active"); + // expertServerConfig.removeClass("active"); + // importServerConfig.addClass("active"); + // expressServerConfig.removeClass("active"); + // } else if (deploymentAlgo == "expert") { + // simpleServerConfig.removeClass("active"); + // expertServerConfig.toggleClass("active");// + // importServerConfig.removeClass("active"); + // expressServerConfig.removeClass("active"); + // } else if (deploymentAlgo == "simple") { + // simpleServerConfig.toggleClass("active");// + // expertServerConfig.removeClass("active"); + // importServerConfig.removeClass("active"); + // expressServerConfig.removeClass("active"); + + // } else { + // //simpleServerConfig + // console.log("exp") + // simpleServerConfig.removeClass("active"); + // expertServerConfig.removeClass("active"); + // importServerConfig.removeClass("active"); + // expressServerConfig.toggleClass("active");// + // } +} + + +// express모드 -> Done버튼 클릭 시 +export function expressDone_btn() { + + console.log("hi") + + // express 는 common resource를 하므로 별도로 처리(connection, spec만) + $("#p_provider").val($("#ep_provider").val()) + $("#p_connectionName").val($("#ep_connectionName").val()) + $("#p_name").val($("#ep_name").val()) + $("#p_description").val($("#ep_description").val()) + $("#p_imageId").val($("#ep_imageId").val()) + + $("#p_commonImageId").val($("#ep_commonImageId").val()) + + $("#p_commonSpecId").val($("#ep_commonSpecId").val()) + $("#p_root_disk_type").val($("#ep_root_disk_type").val()) + $("#p_root_disk_size").val($("#ep_root_disk_size").val()) + + $("#p_specId").val($("#ep_specId").val()) + + $("#p_subGroupSize").val($("#ep_vm_add_cnt").val() + "") + $("#p_vm_cnt").val($("#ep_vm_add_cnt").val() + "") + + //var express_form = $("#express_form").serializeObject() + // commonSpec 으로 set 해야하므로 재설정 + var express_form = {} + express_form["name"] = $("#p_name").val(); + express_form["connectionName"] = $("#p_connectionName").val(); + express_form["description"] = $("#p_description").val(); + express_form["subGroupSize"] = $("#p_subGroupSize").val(); + express_form["image"] = $("#p_imageId").val(); + express_form["spec"] = $("#p_specId").val(); + express_form["rootDiskSize"] = $("#p_root_disk_size").val(); + express_form["rootDiskType"] = $("#p_root_disk_type").val(); + + // dynamic에서 commonImage를 param으로 받기 때문에 해당 값 설정 + express_form["commonImage"] = $("#p_commonImageId").val(); + express_form["commonSpec"] = $("#p_commonSpecId").val();// + + console.log("express_form form : ", express_form); + + var server_name = express_form.name + + var server_cnt = parseInt(express_form.subGroupSize) + console.log("server_cnt", server_cnt) + + var add_server_html = ""; + + Express_Server_Config_Arr.push(express_form) + + + var displayServerCnt = '(' + server_cnt + ')' + + add_server_html += '
  • ' + + + server_name + displayServerCnt + + + '
  • '; + + // } + // $(".section").removeClass("active"); + + // var div = document.getElementById("server_configuration"); + // webconsolejs["partials/layout/navigatePages"].toggleElement(div) + + var div = document.getElementById("server_configuration"); + webconsolejs["partials/layout/navigatePages"].toggleSubElement(div) + + // $("#mcis_server_list").prepend(add_server_html) + // $("#plusVmIcon").remove(); + // $("#mcis_server_list").prepend(getPlusVm()); + + + console.log("add server html"); + + var vmEleId = "vm" + if (!isVm) { + vmEleId = "mcis" + } + console.log("add vm") + $("#" + vmEleId + "_plusVmIcon").remove(); + $("#" + vmEleId + "_server_list").append(add_server_html) + $("#" + vmEleId + "_server_list").prepend(getPlusVm(vmEleId)); + + + console.log("express btn click and express form data : ", express_form) + console.log("express data array : ", Express_Server_Config_Arr); + express_data_cnt++; + $("#express_form").each(function () { + this.reset(); + }) + $("#ep_data_disk").val(""); + +} + +export function view_express(cnt) { + console.log('view simple cnt : ', cnt); + // var select_form_data = Simple_Server_Config_Arr[cnt] + // console.log('select_form_data : ', select_form_data); + // $(".express_servers_config").addClass("active") + // $(".simple_servers_config").removeClass("active") + // $(".expert_servers_config").removeClass("active") + // $(".import_servers_config").removeClass("active") + + var div = document.getElementById("server_configuration"); + webconsolejs["partials/layout/navigatePages"].toggleElement(div) + + +} + + +// Assist spec 클릭 시 +// 공통으로 뺄 것 + +var ROOT_DISK_MAX_VALUE = 0; +var ROOT_DISK_MIN_VALUE = 0; + +// Disk Type 선택 시 Disk Size Min/Max 설정 > 보완할 것 +export function changeDiskSize(type) { + var disk_size = DISK_SIZE; + + if (disk_size) { + disk_size.forEach(item => { + var temp_size = item.split("|") + var temp_type = temp_size[0]; + if (temp_type == type) { + ROOT_DISK_MAX_VALUE = temp_size[1] + ROOT_DISK_MIN_VALUE = temp_size[2] + } + }) + } + console.log("ROOT_DISK_MAX_VALUE : ", ROOT_DISK_MAX_VALUE) + console.log("ROOT_DISK_MIN_VALUE : ", ROOT_DISK_MIN_VALUE) + $("#s_rootDiskType").val(type); + $("#e_rootDiskType").val(type); + +} + + + +// 해당 provider, connection 으로 사용가능한 Disk의 Type 정보(type, min, max ) 조회 +// ex) AWS -> standard|1|1024, gp2|1|16384 +async function getCommonLookupDiskInfo(provider, connectionName) { + + const data = { + queryParams: { + "provider": provider, + "connectionName": connectionName + } + } + + var controller = "/api/" + "disklookup"; + const response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + console.log("lookup disk info", response) + var responseData = response.data.responseData + getCommonLookupDiskInfoSuccess(provider, responseData) +} + +var DISK_SIZE = []; +function getCommonLookupDiskInfoSuccess(provider, data) { + + console.log("getCommonLookupDiskInfoSuccess", data); + var providerId = provider.toUpperCase() + var root_disk_type = []; + var res_item = data; + res_item.forEach(item => { + console.log("item provider: ", item.providerId); + var temp_provider = item.providerId + if (temp_provider == providerId) { + root_disk_type = item.rootdisktype + DISK_SIZE = item.disksize + } + }) + // var temp_provider = res_item.providerId + // if(temp_provider == provider){ + // root_disk_type = res_item.rootdisktype + // DISK_SIZE = res_item.disksize + // } + + console.log("DISK_SIZE", DISK_SIZE) + var html = '' + console.log("root_disk_type : ", root_disk_type); + root_disk_type.forEach(item => { + html += '' + }) + //if(caller == "vmexpress"){ + $("#ep_root_disk_type").empty(); + $("#ep_root_disk_type").append(html); + //}else if(caller == "vmsimple"){ + // $("#ss_root_disk_type").empty(); + // $("#ss_root_disk_type").append(html); + //}else if(caller == "vmexpert"){ + // $("#tab_others_root_disk_type").empty() + // $("#tab_others_root_disk_type").append(html) + //} + console.log("const valie DISK_SIZE : ", DISK_SIZE) + + var myModalEl = document.getElementById('spec-search'); + var modal = bootstrap.Modal.getInstance(myModalEl); // Returns a Bootstrap modal instance + modal.hide(); + +} + + +// plus 버튼을 추가 +function getPlusVm(vmElementId) { + + var append = ""; + append = append + '
  • '; + append = append + "+" + append = append + '
  • '; + return append; +} +// 서버정보 입력 area에서 'DONE'버튼 클릭시 array에 담고 form을 초기화 + +var totalDeployServerCount = 0; +var TotalServerConfigArr = new Array();// 최종 생성할 서버 목록 +// deploy 버튼 클릭시 등록한 서버목록을 배포. +// function btn_deploy(){ +export function deployMcis() { + console.log("deployMcis") + createMcisDynamic() + // express 는 express 만, simple + expert + import 는 합쳐서 + // 두개의 mcis는 만들어 질 수 없으므로 + // var deploymentAlgo = $("#placement_algo").val() + // if (deploymentAlgo == "express") { + // createMcisDynamic() + // } + // else{ + // var mcis_name = $("#mcis_name").val(); + // if (!mcis_name) { + // commonAlert("Please Input MCIS Name!!!!!") + // return; + // } + // var mcis_desc = $("#mcis_desc").val(); + // var placement_algo = $("#placement_algo").val(); + // var installMonAgent = $("#installMonAgent").val(); + + // var new_obj = {} + + // var vm_len = 0; + + // if (IsImport) { + // // ImportedMcisScript.name = mcis_name; + // // ImportedMcisScript.description = mcis_desc; + // // ImportedMcisScript.installMonAgent = installMonAgent; + // // console.log(ImportedMcisScript); + // //var theJson = jQuery.parseJSON($(this).val()) + // //$("#mcisImportScriptPretty").val(fmt); + // new_obj = $("#mcisImportScriptPretty").val(); + // new_obj.id = "";// id는 비워준다. + // } else { + // // console.log(Simple_Server_Config_Arr) + + // // mcis 생성이므로 mcisID가 없음 + // new_obj['name'] = mcis_name + // new_obj['description'] = mcis_desc + // new_obj['installMonAgent'] = installMonAgent + + // // Express_Server_Config_Arr 은 별도처리 + + + // if (Simple_Server_Config_Arr) { + // vm_len = Simple_Server_Config_Arr.length; + // for (var i in Simple_Server_Config_Arr) { + // TotalServerConfigArr.push(Simple_Server_Config_Arr[i]); + // } + // } + + // if (Expert_Server_Config_Arr) { + // vm_len = Expert_Server_Config_Arr.length; + // for (var i in Expert_Server_Config_Arr) { + // TotalServerConfigArr.push(Expert_Server_Config_Arr[i]); + // } + // } + + // if (TotalServerConfigArr) { + // vm_len = TotalServerConfigArr.length; + // console.log("Server_Config_Arr length: ", vm_len); + // new_obj['vm'] = TotalServerConfigArr; + // console.log("new obj is : ", new_obj); + // } else { + // commonAlert("Please Input Servers"); + // $(".simple_servers_config").addClass("active"); + // $("#s_name").focus(); + // } + // } + + // var url = getWebToolUrl("McisRegProc") + // try { + // axios.post(url, new_obj, { + // // headers: { + // // 'Content-type': "application/json", + // // }, + // }).then(result => { + // console.log("MCIR Register data : ", result); + // console.log("Result Status : ", result.status); + // if (result.status == 201 || result.status == 200) { + // commonResultAlert("Register Requested") + // } else { + // commonAlert("Register Fail") + // } + // }).catch((error) => { + // // console.warn(error); + // console.log(error.response) + // var errorMessage = error.response.data.error; + // var statusCode = error.response.status; + // commonErrorAlert(statusCode, errorMessage) + + // }) + // } catch (error) { + // commonAlert(error); + // console.log(error); + // } + // } +} + +export async function createMcisDynamic() { + console.log("createMcisDynamic") + // var namespace = webconsolejs["common/util"].getCurrentProject() + // nsid = namespace.Name + + var projectId = $("#select-current-project").text() + var projectName = $('#select-current-project').find('option:selected').text(); + var nsId = projectName; + console.log("create ssss nsId ", projectName) + + var mcisName = $("#mcis_name").val() + var mcisDesc = $("#mcis_desc").val() + + + console.log("mcisName", mcisName) + console.log("mcisDesc", mcisDesc) + console.log("Express_Server_Config_Arr", Express_Server_Config_Arr) + + + + if (!mcis_name) { + commonAlert("Please Input MCIS Name!!!!!") + return; + } + + if (!mcisDesc) { + mcisDesc = "Made in CB-TB" + } + var obj = {} + obj['name'] = mcisName + obj['description'] = mcisDesc + obj['vm'] = Express_Server_Config_Arr + const data = { + pathParams: { + "nsId": nsId + }, + Request: { + "name": obj['name'], + "vm": obj['vm'], + } + } + + var controller = "/api/" + "createdynamicmcis"; + const response = webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + + //console.log("create dynamicMCIS : ", response) + + alert("생성요청 완료"); + var urlParamMap = new Map(); + + // 생성요청했으므로 결과를 기다리지 않고 mcisList로 보냄 + webconsolejs["common/util"].changePage("McisMng", urlParamMap) + // webconsolejs["common/util"].changePage("McisMng") +} + +export function addNewMcis() { + isVm = false + Express_Server_Config_Arr = new Array(); +} + +// ////////////// VM Handling /////////// +export function addNewVirtualMachine() { + console.log("addNewVirtualMachine") + Express_Server_Config_Arr = new Array(); + + var selectedMcis = webconsolejs["pages/operation/manage/mcis"].selectedMcisObj + console.log("selectedMcis", selectedMcis) + + var mcis_name = selectedMcis[0].name + $("#extend_mcis_name").val(mcis_name) + console.log("extend_mcis_name", mcis_name) + + isVm = true +} + +export async function btn_deploy() { + // var deploymentAlgo = $("#placement_algo").val() + // if (deploymentAlgo == "express") { + await createVmDynamic() + // }else{ + + // var mcis_name = $("#mcis_name").val(); + // var mcis_id = $("#mcis_id").val(); + // if (!mcis_id) { + // commonAlert("Please Select MCIS !!!!!") + // return; + // } + // totalDeployServerCount = 0;// deploy vm 개수 초기화 + // var new_obj = {}// vm이 담길 변수 + + // // Express 는 별도처리임. + + // if (Simple_Server_Config_Arr) { + // vm_len = Simple_Server_Config_Arr.length; + // for (var i in Simple_Server_Config_Arr) { + // TotalServerConfigArr.push(Simple_Server_Config_Arr[i]); + // } + // } + + // if (Expert_Server_Config_Arr) { + // vm_len = Expert_Server_Config_Arr.length; + // for (var i in Expert_Server_Config_Arr) { + // TotalServerConfigArr.push(Expert_Server_Config_Arr[i]); + // } + // } + + // //Import_Server_Config_Arr : import도 같이 추가 + // if (Import_Server_Config_Arr) { + // vm_len = Import_Server_Config_Arr.length; + // for (var i in Import_Server_Config_Arr) { + // TotalServerConfigArr.push(Import_Server_Config_Arr[i]); + // } + // } + + // if (TotalServerConfigArr) { + // vm_len = TotalServerConfigArr.length; + // console.log("Server_Config_Arr length: ", vm_len); + // new_obj['vm'] = TotalServerConfigArr; + // console.log("new obj is : ", new_obj); + // } else { + // commonAlert("Please Input Servers"); + // $(".simple_servers_config").addClass("active"); + // $("#s_name").focus(); + // } + + // //var url = "/operation/manages/mcismng/" + mcis_id + "/vm/reg/proc" + // var urlParamMap = new Map(); + // urlParamMap.set(":mcisID", mcis_id) + // var url = setUrlByParam("McisVmListRegProc", urlParamMap) + // //var url = getWebToolUrl("McisVmRegProc") + // try { + // axios.post(url, new_obj, { + // // headers: { + // // 'Content-type': "application/json", + // // }, + // }).then(result => { + // console.log("VM Register data : ", result); + // console.log("Result Status : ", result.status); + // if (result.status == 201 || result.status == 200) { + // commonResultAlert("Register Requested") + // } else { + // commonAlert("Register Fail") + // } + // }).catch((error) => { + // // console.warn(error); + // console.log(error.response) + // var errorMessage = error.response.data.error; + // var statusCode = error.response.status; + // commonErrorAlert(statusCode, errorMessage) + + // }) + // } catch (error) { + // commonAlert(error); + // console.log(error); + // } + // } +} + +var nsid = "" +export async function createVmDynamic() { + console.log("createVmDynamic") + console.log("Express_Server_Config_Arr", Express_Server_Config_Arr) + + + nsid = webconsolejs["pages/operation/manage/mcis"].nsid + console.log("selected projectId : ", nsid) + + var mcisid = webconsolejs["pages/operation/manage/mcis"].selectedMcisObj[0].id + console.log("selected mcisId : ", mcisid) + + // var commonImage = selectedMcisObj[0].vm[0]. + // var mcis_name = selectedMcis[0].name + + // var mcis_name = $("#mcis_name").val(); + // var mcis_id = $("#mcis_id").val(); + // if (!mcis_id) { + // commonAlert("Please Select MCIS !!!!!") + // return; + // } + + /// + var obj = {} + obj = Express_Server_Config_Arr[0] + const data = { + pathParams: { + nsId: nsid, + mcisId: mcisid, + }, + request: { + "commonImage": obj.commonImage, + "commonSpec": obj.commonSpec, + "connectionName": obj.connectionName, + "description": obj.description, + "label": "", + "name": obj.name, + "subGroupSize": obj.subGroupSize, + "rootDiskSize": obj.rootDiskSize, + "rootDiskType": obj.rootDiskType, + } + } + + + var controller = "/api/" + "createvmdynamic"; + const response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ) + console.log("create VMdynamic : ", response) +} + +// { +// "commonImage": "ubuntu18.04", +// "commonSpec": "aws+ap-northeast-2+t2.small", +// "connectionName": "string", +// "description": "Description", +// "label": "DynamicVM", +// "name": "g1-1", +// "rootDiskSize": "default, 30, 42, ...", +// "rootDiskType": "default, TYPE1, ...", +// "subGroupSize": "3", +// "vmUserPassword": "string" +// } + + + +/// + + + +// vm 생성 결과 표시 +// 여러개의 vm이 생성될 수 있으므로 각각 결과를 표시 +var resultVmCreateMap = new Map(); + +function vmCreateCallback(resultVmKey, resultStatus) { + resultVmCreateMap.set(resultVmKey, resultStatus) + var resultText = ""; + var createdServer = 0; + for (let key of resultVmCreateMap.keys()) { + console.log("vmCreateresult " + key + " : " + resultVmCreateMap.get(resultVmKey)); + resultText += key + " = " + resultVmCreateMap.get(resultVmKey) + "," + //totalDeployServerCount-- + createdServer++; + } + + // $("#serverRegistResult").text(resultText); + + if (resultStatus != "Success") { + // add된 항목 제거 해야 함. + + // array는 초기화 + Simple_Server_Config_Arr.length = 0; + simple_data_cnt = 0 + // TODO : expert 추가하면 주석 제거할 것 + Expert_Server_Config_Arr.length = 0; + expert_data_cnt = 0 + Import_Server_Config_Arr.length = 0; + import_data_cnt = 0 + } + + if (createdServer === totalDeployServerCount) { //모두 성공 + //getVmList(); + //commonResultAlert($("#serverRegistResult").text()); + + } else if (createdServer < totalDeployServerCount) { //일부 성공 + // commonResultAlert($("#serverRegistResult").text()); + + } else if (createdServer = 0) { //모두 실패 + //commonResultAlert($("#serverRegistResult").text()); + } + commonResultAlert("VM creation request completed"); +} diff --git a/mc_web_console_front/assets/js/partials/operation/manage/serverrecommandation.js b/mc_web_console_front/assets/js/partials/operation/manage/serverrecommandation.js new file mode 100644 index 00000000..b25ea7fb --- /dev/null +++ b/mc_web_console_front/assets/js/partials/operation/manage/serverrecommandation.js @@ -0,0 +1,380 @@ +import { TabulatorFull as Tabulator } from "tabulator-tables"; + +var returnFunction;// popup인 경우에는 callback function으로 param을 전달해야 한다. +var recommandTable; + +var recommandVmSpecListObj = new Object(); + + +export function initServerRecommandation(callbackfunction){ + console.log("initServerRecommandation ") + + initRecommandSpecTable(); + + // return function 정의 + if( callbackfunction != undefined){ + returnFunction = callbackfunction; + } +} + +function initRecommandSpecTable(){ + var tableObjParams = {}; + + var columns = [ + { + formatter: "rowSelection", + titleFormatter: "rowSelection", + vertAlign: "middle", + hozAlign: "center", + headerHozAlign: "center", + headerSort: false, + width: 60, + }, + { + title: "connectionName", + field: "connectionName", + headerSort: false, + visible: false + }, + { + title: "EVALUATIONSCORE", + field: "evaluationScore10", + headerSort: false, + visible: false + }, + { + title: "PROVIDER", + field: "providerName", + vertAlign: "middle", + hozAlign: "center", + headerHozAlign: "center", + headerSort: false, + maxWidth: 100, + }, + { + title: "REGION", + field: "regionName", + vertAlign: "middle" + }, + { + title: "PRICE", + field: "costPerHour", + vertAlign: "middle", + hozAlign: "center", + }, + { + title: "MEMORY", + field: "memoryGiB", + vertAlign: "middle", + hozAlign: "center", + maxWidth: 150, + }, + { + title: "VCPU", + field: "vCPU", + vertAlign: "middle", + hozAlign: "center", + headerHozAlign: "center", + maxWidth: 135, + } + ]; + + //recommandTable = setSpecTabulator("spec-table", tableObjParams, columns); + recommandTable = webconsolejs["common/util"].setTabulator("spec-table", tableObjParams, columns); + + recommandTable.on("rowSelectionChanged", function (data, rows) { + console.log("data", data) + + updateSelectedRows(data) + }); + + +} + +// function setSpecTabulator( +// tableObjId, +// tableObjParamMap, +// columnsParams, +// isMultiSelect +// ) { +// var placeholder = "No Data"; +// var pagination = "local"; +// var paginationSize = 5; +// var paginationSizeSelector = [5, 10, 15, 20]; +// var movableColumns = true; +// var columnHeaderVertAlign = "middle"; +// var paginationCounter = "rows"; +// var layout = "fitColumns"; + +// if (tableObjParamMap.hasOwnProperty("placeholder")) { +// placeholder = tableObjParamMap.placeholder; +// } + +// if (tableObjParamMap.hasOwnProperty("pagination")) { +// pagination = tableObjParamMap.pagination; +// } + +// if (tableObjParamMap.hasOwnProperty("paginationSize")) { +// paginationSize = tableObjParamMap.paginationSize; +// } + +// if (tableObjParamMap.hasOwnProperty("paginationSizeSelector")) { +// paginationSizeSelector = tableObjParamMap.paginationSizeSelector; +// } + +// if (tableObjParamMap.hasOwnProperty("movableColumns")) { +// movableColumns = tableObjParamMap.movableColumns; +// } + +// if (tableObjParamMap.hasOwnProperty("columnHeaderVertAlign")) { +// columnHeaderVertAlign = tableObjParamMap.columnHeaderVertAlign; +// } + +// if (tableObjParamMap.hasOwnProperty("paginationCounter")) { +// paginationCounter = tableObjParamMap.paginationCounter; +// } + +// if (tableObjParamMap.hasOwnProperty("layout")) { +// layout = tableObjParamMap.layout; +// } + +// var tabulatorTable = new Tabulator("#" + tableObjId, { +// //ajaxURL:"http://localhost:3000/operations/mcismng?option=status", +// placeholder, +// pagination, +// paginationSize, +// paginationSizeSelector, +// movableColumns, +// columnHeaderVertAlign, +// paginationCounter, +// layout, +// columns: columnsParams, +// selectableRows: isMultiSelect == false ? 1 : true, +// selectable: true, +// }); +// console.log("tabulator Table ", tabulatorTable) +// return tabulatorTable; +// } + +var recommendSpecs = []; + +function updateSelectedRows(data) { + recommendSpecs = []; // 선택된 행의 데이터를 초기화 + + data.forEach(function (rowData) { + recommendSpecs.push(rowData); + }); + + console.log("선택된 행 데이터:", recommendSpecs); +} + +// recommane Vm 조회 +export async function getRecommendVmInfo() { + console.log("hihi") + + // var max_cpu = $("#num_vCPU_max").val() + // var min_cpu = $("#num_vCPU_min").val() + // var max_mem = $("#num_memory_max").val() + // var min_mem = $("#num_memory_min").val() + // var max_cost = $("#num_cost_max").val() + // var min_cost = $("#num_cost_min").val() + // var limit = $("#recommendVmLimit").val() + // var lon = $("#longitude").val() + // var lat = $("#latitude").val() + + var memoryVal = $("#assist_num_memory").val() + var cpuVal = $("#assist_num_cpu").val() + var costVal = $("#assist_num_cost").val() + var lon = $("#longitude").val() + var lat = $("#latitude").val() + + const data = { + request: { + "filter": { + "policy": [ + { + "condition": [ + { + "operand": cpuVal, + "operator": "<=" + } + ], + "metric": "vCPU" + }, + { + "condition": [ + { + "operand": memoryVal, + "operator": "<=" + } + ], + "metric": "memoryGiB" + }, + { + "condition": [ + { + "operand": costVal, + "operator": "<=" + } + ], + "metric": "costPerHour" + } + ] + }, + "limit": "50", + "priority": { + "policy": [ + { + "metric": "location", + "parameter": [ + { + "key": "coordinateClose", + "val": [ + lon + "/" + lat + ] + } + ], + "weight": "0.3" + } + ] + } + } + } + + var controller = "/api/" + "mcisrecommendvm"; + const response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + + console.log("responseaaa", response.data.responseData) + var specList = response.data.responseData + + recommandVmSpecListObj = specList + + recommandTable.setData(recommandVmSpecListObj) + + // getSpecListCallBackSuccess(specList); + + + // var max_cpu = $("#num_vCPU_max").val() + // var min_cpu = $("#num_vCPU_min").val() + // var max_mem = $("#num_memory_max").val() + // var min_mem = $("#num_memory_min").val() + // var max_cost = $("#num_cost_max").val() + // var min_cost = $("#num_cost_min").val() + // var limit = $("#recommendVmLimit").val() + // var lon = $("#longitude").val() + // var lat = $("#latitude").val() + + // console.log(" lon " + lon + ", lat " + lat) + // if (lon == "" || lat == "") { + // commonAlert(" 지도에서 위치를 선택하세요 ") + // return; + // } + + // } else { + // var message = result.data.message; + // commonAlert("Fail Create Spec : " + message + "(" + statusCode + ")"); + + // } + +} + +// apply 클릭시 데이터 SET +// returnSpecInfo() +export async function applySpecInfo() { + console.log("array", recommendSpecs) + var selectedSpecs = recommendSpecs[0] + + // pre-release -> mode = express 고정 + //caller == "express" + + + var provider = selectedSpecs.providerName + var connectionName = selectedSpecs.connectionName + var specName = selectedSpecs.cspSpecName + var imageName = await availableVMImageBySpec(selectedSpecs.id) + var commonSpecId = selectedSpecs.id // common specid for create dynamic mcis + + console.log("commonSpecId", commonSpecId) + console.log("connectionName", selectedSpecs.connectionName) + console.log("providerName", selectedSpecs.providerName) + console.log("cspSpecName", selectedSpecs.cspSpecName) + console.log("123123123", imageName) + + // $("#ep_provider").val(provider) + // $("#ep_connectionName").val(connectionName) + // $("#ep_specId").val(specName) + // $("#ep_imageId").val(imageName) + // $("#ep_commonSpecId").val(commonSpecId) + // commonImage는 availableVMImageBySpec에서 조회 후 설정한다 (두 개 이상일 수 있음) + + var returnObject = {} + returnObject.provider = provider + returnObject.connectionName = connectionName + returnObject.specName = specName + returnObject.imageName = imageName + returnObject.commonSpecId = commonSpecId + + console.log("return to parent"); + console.log(returnFunction) + eval(returnFunction)(returnObject); + + + +} + +export function showRecommendSpecSetting(value) { + console.log("Selected coordinate : ", value) + if (value === "seoul") { + $("#latitude").val("37.532600") + $("#longitude").val("127.024612") + } else if (value === "london") { + $("#latitude").val("51.509865") + $("#longitude").val("-0.118092") + } else if (value === "newyork") { + $("#latitude").val("40.730610") + $("#longitude").val("-73.935242") + } +} + + +// TODO: 스펙 선택 시 사용가능한 이미지의 개수가 두개 이상일 때 선택하는 UI 추가 구현 필요 +async function availableVMImageBySpec(id) { + + var imageIds = [] + var commonimageId = [] // params for create dynamic mcis + + const data = { + request: { + "CommonSpec": [ + id + ] + + } + } + + var controller = "/api/" + "mcisdynamiccheckrequest"; + const response = await webconsolejs["common/api/http"].commonAPIPost( + controller, + data + ); + + // TODO: 스펙 선택 시 사용가능한 이미지의 개수가 두개 이상일 때 선택하는 UI 추가 구현 필요 + // image ID 추출 + response.data.responseData.reqCheck.forEach(function (req) { + req.image.forEach(function (img) { + console.log("reqCheckreqCheckreqCheck", img) + imageIds.push(img.guestOS); + commonimageId.push(img.id); + }); + }); + $("#ep_commonImageId").val(commonimageId[0]) + + console.log("Image IDs:", imageIds); + console.log("firstImageId", imageIds[0]) + console.log("commonImageid : ", commonimageId[0]) + + return imageIds[0] +} diff --git a/mc_web_console_front/assets/jsOld/auth/login/login.js b/mc_web_console_front/assets/jsOld/auth/login/login.js deleted file mode 100644 index 32acf43b..00000000 --- a/mc_web_console_front/assets/jsOld/auth/login/login.js +++ /dev/null @@ -1,20 +0,0 @@ -import axios from 'axios'; - -document.getElementById("loginbtn").addEventListener('click',async function () { - let csrfToken = document.getElementById("csrf-token").getAttribute('content'); - axios.defaults.headers.common['X-CSRF-TOKEN'] = csrfToken; - - const userData ={ - id: document.getElementById("id").value, - password: document.getElementById("password").value, - }; - const response = await webconsolejs["common/http/api"].commonAPIPost('/auth/login', userData) - if (response.status != 200){ - alert("LoginFail\n"+response.data) - document.getElementById("id").value = null - document.getElementById("password").value = null - }else{ - await webconsolejs["common/storage/sessionstorage"].updateSessionWorkspaceList() - window.location = response.data.redirect - } -}); \ No newline at end of file diff --git a/mc_web_console_front/assets/jsOld/common/http/api.js b/mc_web_console_front/assets/jsOld/common/http/api.js deleted file mode 100644 index 49242c02..00000000 --- a/mc_web_console_front/assets/jsOld/common/http/api.js +++ /dev/null @@ -1,30 +0,0 @@ -import axios from 'axios'; - -export async function commonAPIPost(url, data) { - console.log("#### commonAPIPost") - console.log("Request URL : ", url) - console.log("Request Data : ") - console.log(JSON.stringify(data)) - console.log("-----------------------") - - let csrfToken = document.getElementById("csrf-token").getAttribute('content'); - axios.defaults.headers.common['X-CSRF-TOKEN'] = csrfToken; - - const response = await axios.post(url, data) - .then(function (response) { - console.log("## commonAPIPost Response") - console.log("Response status : ", (response.status)) - console.log("Response Data : ") - console.log(JSON.stringify(response.data)) - console.log("----------------------------") - return response - }) - .catch(function (error) { - console.log("## commonAPIPost Response ERR") - console.log("error : ", (error)) - console.log("--------------------------------") - return error - }); - - return response -} \ No newline at end of file diff --git a/mc_web_console_front/assets/jsOld/common/storage/localstorage.js b/mc_web_console_front/assets/jsOld/common/storage/localstorage.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/common/storage/sessionstorage.js b/mc_web_console_front/assets/jsOld/common/storage/sessionstorage.js deleted file mode 100644 index 684cb487..00000000 --- a/mc_web_console_front/assets/jsOld/common/storage/sessionstorage.js +++ /dev/null @@ -1,42 +0,0 @@ -export function getSessionCurrentWorkspaceProjcet() { - let currentWorkspacProject = JSON.parse(sessionStorage.getItem('currentWorkspacProject')) - return currentWorkspacProject -} - -export function setSessionCurrentWorkspaceProjcet(workspaceId, projectId) { - let currentWorksppacProject = { - "currentWorkspace":workspaceId, - "currentProject":projectId - } - sessionStorage.setItem('currentWorkspacProject',JSON.stringify(currentWorksppacProject)) -} - -export async function getSessionWorkspaceList() { - let workspaceList = JSON.parse(sessionStorage.getItem('workspaceList')) - if (workspaceList == null){ - await webconsolejs["common/storage/sessionstorage"].updateSessionWorkspaceList() - workspaceList = webconsolejs["common/storage/sessionstorage"].getSessionWorkspaceList() - } - return workspaceList.Workspaces -} - -export function getSessionProjectList() { - let projectList = JSON.parse(sessionStorage.getItem('projectList')) - return projectList.Projects -} - -export async function updateSessionWorkspaceList() { - const response = await webconsolejs["common/http/api"].commonAPIPost('/api/workspacelistbyuser') - sessionStorage.setItem('workspaceList', JSON.stringify(response.data.responseData)); -} - -export async function updateSessionProjectListByWorkspaceId(workspaceId) { - let data = { - "requestData":{ - "userId":"mciamuser", - "workspaceId": workspaceId - } - } - const response = await webconsolejs["common/http/api"].commonAPIPost('/api/projectlistbyworkspaceid',data) - sessionStorage.setItem('projectList', JSON.stringify(response.data.responseData)); -} diff --git a/mc_web_console_front/assets/jsOld/common/tabler/tabler.js b/mc_web_console_front/assets/jsOld/common/tabler/tabler.js deleted file mode 100644 index c96bbe41..00000000 --- a/mc_web_console_front/assets/jsOld/common/tabler/tabler.js +++ /dev/null @@ -1,7544 +0,0 @@ -/*! -* Tabler v1.0.0-beta20 (https://tabler.io) -* @version 1.0.0-beta20 -* @link https://tabler.io -* Copyright 2018-2023 The Tabler Authors -* Copyright 2018-2023 codecalm.net Paweł Kuna -* Licensed under MIT (https://github.com/tabler/tabler/blob/master/LICENSE) -*/ -(function (factory) { - typeof define === 'function' && define.amd ? define(factory) : - factory(); -})((function () { - 'use strict'; - - var e = new Map; function t(t) { var o = e.get(t); o && o.destroy(); } function o(t) { var o = e.get(t); o && o.update(); } var r = null; "undefined" == typeof window ? ((r = function (e) { return e }).destroy = function (e) { return e }, r.update = function (e) { return e }) : ((r = function (t, o) { return t && Array.prototype.forEach.call(t.length ? t : [t], function (t) { return function (t) { if (t && t.nodeName && "TEXTAREA" === t.nodeName && !e.has(t)) { var o, r = null, n = window.getComputedStyle(t), i = (o = t.value, function () { a({ testForHeightReduction: "" === o || !t.value.startsWith(o), restoreTextAlign: null }), o = t.value; }), l = function (o) { t.removeEventListener("autosize:destroy", l), t.removeEventListener("autosize:update", s), t.removeEventListener("input", i), window.removeEventListener("resize", s), Object.keys(o).forEach(function (e) { return t.style[e] = o[e] }), e.delete(t); }.bind(t, { height: t.style.height, resize: t.style.resize, textAlign: t.style.textAlign, overflowY: t.style.overflowY, overflowX: t.style.overflowX, wordWrap: t.style.wordWrap }); t.addEventListener("autosize:destroy", l), t.addEventListener("autosize:update", s), t.addEventListener("input", i), window.addEventListener("resize", s), t.style.overflowX = "hidden", t.style.wordWrap = "break-word", e.set(t, { destroy: l, update: s }), s(); } function a(e) { var o, i, l = e.restoreTextAlign, s = void 0 === l ? null : l, d = e.testForHeightReduction, u = void 0 === d || d, c = n.overflowY; if (0 !== t.scrollHeight && ("vertical" === n.resize ? t.style.resize = "none" : "both" === n.resize && (t.style.resize = "horizontal"), u && (o = function (e) { for (var t = []; e && e.parentNode && e.parentNode instanceof Element;)e.parentNode.scrollTop && t.push([e.parentNode, e.parentNode.scrollTop]), e = e.parentNode; return function () { return t.forEach(function (e) { var t = e[0], o = e[1]; t.style.scrollBehavior = "auto", t.scrollTop = o, t.style.scrollBehavior = null; }) } }(t), t.style.height = ""), i = "content-box" === n.boxSizing ? t.scrollHeight - (parseFloat(n.paddingTop) + parseFloat(n.paddingBottom)) : t.scrollHeight + parseFloat(n.borderTopWidth) + parseFloat(n.borderBottomWidth), "none" !== n.maxHeight && i > parseFloat(n.maxHeight) ? ("hidden" === n.overflowY && (t.style.overflow = "scroll"), i = parseFloat(n.maxHeight)) : "hidden" !== n.overflowY && (t.style.overflow = "hidden"), t.style.height = i + "px", s && (t.style.textAlign = s), o && o(), r !== i && (t.dispatchEvent(new Event("autosize:resized", { bubbles: !0 })), r = i), c !== n.overflow && !s)) { var v = n.textAlign; "hidden" === n.overflow && (t.style.textAlign = "start" === v ? "end" : "start"), a({ restoreTextAlign: v, testForHeightReduction: !0 }); } } function s() { a({ testForHeightReduction: !0, restoreTextAlign: null }); } }(t) }), t }).destroy = function (e) { return e && Array.prototype.forEach.call(e.length ? e : [e], t), e }, r.update = function (e) { return e && Array.prototype.forEach.call(e.length ? e : [e], o), e }); var n = r; - - var elements = document.querySelectorAll('[data-bs-toggle="autosize"]'); - if (elements.length) { - elements.forEach(function (element) { - n(element); - }); - } - - function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - return target; - } - - function IMask(el) { - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - return new IMask.InputMask(el, opts); - } - - class ChangeDetails { - constructor(details) { - Object.assign(this, { - inserted: '', - rawInserted: '', - skip: false, - tailShift: 0 - }, details); - } - aggregate(details) { - this.rawInserted += details.rawInserted; - this.skip = this.skip || details.skip; - this.inserted += details.inserted; - this.tailShift += details.tailShift; - return this; - } - get offset() { - return this.tailShift + this.inserted.length; - } - } - IMask.ChangeDetails = ChangeDetails; - - function isString(str) { - return typeof str === 'string' || str instanceof String; - } - const DIRECTION = { - NONE: 'NONE', - LEFT: 'LEFT', - FORCE_LEFT: 'FORCE_LEFT', - RIGHT: 'RIGHT', - FORCE_RIGHT: 'FORCE_RIGHT' - }; - function forceDirection(direction) { - switch (direction) { - case DIRECTION.LEFT: - return DIRECTION.FORCE_LEFT; - case DIRECTION.RIGHT: - return DIRECTION.FORCE_RIGHT; - default: - return direction; - } - } - function escapeRegExp(str) { - return str.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); - } - function normalizePrepare(prep) { - return Array.isArray(prep) ? prep : [prep, new ChangeDetails()]; - } - function objectIncludes(b, a) { - if (a === b) return true; - var arrA = Array.isArray(a), - arrB = Array.isArray(b), - i; - if (arrA && arrB) { - if (a.length != b.length) return false; - for (i = 0; i < a.length; i++) if (!objectIncludes(a[i], b[i])) return false; - return true; - } - if (arrA != arrB) return false; - if (a && b && typeof a === 'object' && typeof b === 'object') { - var dateA = a instanceof Date, - dateB = b instanceof Date; - if (dateA && dateB) return a.getTime() == b.getTime(); - if (dateA != dateB) return false; - var regexpA = a instanceof RegExp, - regexpB = b instanceof RegExp; - if (regexpA && regexpB) return a.toString() == b.toString(); - if (regexpA != regexpB) return false; - var keys = Object.keys(a); - for (i = 0; i < keys.length; i++) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = 0; i < keys.length; i++) if (!objectIncludes(b[keys[i]], a[keys[i]])) return false; - return true; - } else if (a && b && typeof a === 'function' && typeof b === 'function') { - return a.toString() === b.toString(); - } - return false; - } - - class ActionDetails { - constructor(value, cursorPos, oldValue, oldSelection) { - this.value = value; - this.cursorPos = cursorPos; - this.oldValue = oldValue; - this.oldSelection = oldSelection; - while (this.value.slice(0, this.startChangePos) !== this.oldValue.slice(0, this.startChangePos)) { - --this.oldSelection.start; - } - } - get startChangePos() { - return Math.min(this.cursorPos, this.oldSelection.start); - } - get insertedCount() { - return this.cursorPos - this.startChangePos; - } - get inserted() { - return this.value.substr(this.startChangePos, this.insertedCount); - } - get removedCount() { - return Math.max(this.oldSelection.end - this.startChangePos || - this.oldValue.length - this.value.length, 0); - } - get removed() { - return this.oldValue.substr(this.startChangePos, this.removedCount); - } - get head() { - return this.value.substring(0, this.startChangePos); - } - get tail() { - return this.value.substring(this.startChangePos + this.insertedCount); - } - get removeDirection() { - if (!this.removedCount || this.insertedCount) return DIRECTION.NONE; - return (this.oldSelection.end === this.cursorPos || this.oldSelection.start === this.cursorPos) && - this.oldSelection.end === this.oldSelection.start ? DIRECTION.RIGHT : DIRECTION.LEFT; - } - } - - class ContinuousTailDetails { - constructor() { - let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; - let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - let stop = arguments.length > 2 ? arguments[2] : undefined; - this.value = value; - this.from = from; - this.stop = stop; - } - toString() { - return this.value; - } - extend(tail) { - this.value += String(tail); - } - appendTo(masked) { - return masked.append(this.toString(), { - tail: true - }).aggregate(masked._appendPlaceholder()); - } - get state() { - return { - value: this.value, - from: this.from, - stop: this.stop - }; - } - set state(state) { - Object.assign(this, state); - } - unshift(beforePos) { - if (!this.value.length || beforePos != null && this.from >= beforePos) return ''; - const shiftChar = this.value[0]; - this.value = this.value.slice(1); - return shiftChar; - } - shift() { - if (!this.value.length) return ''; - const shiftChar = this.value[this.value.length - 1]; - this.value = this.value.slice(0, -1); - return shiftChar; - } - } - - class Masked { - constructor(opts) { - this._value = ''; - this._update(Object.assign({}, Masked.DEFAULTS, opts)); - this.isInitialized = true; - } - updateOptions(opts) { - if (!Object.keys(opts).length) return; - this.withValueRefresh(this._update.bind(this, opts)); - } - _update(opts) { - Object.assign(this, opts); - } - get state() { - return { - _value: this.value - }; - } - set state(state) { - this._value = state._value; - } - reset() { - this._value = ''; - } - get value() { - return this._value; - } - set value(value) { - this.resolve(value); - } - resolve(value) { - this.reset(); - this.append(value, { - input: true - }, ''); - this.doCommit(); - return this.value; - } - get unmaskedValue() { - return this.value; - } - set unmaskedValue(value) { - this.reset(); - this.append(value, {}, ''); - this.doCommit(); - } - get typedValue() { - return this.doParse(this.value); - } - set typedValue(value) { - this.value = this.doFormat(value); - } - get rawInputValue() { - return this.extractInput(0, this.value.length, { - raw: true - }); - } - set rawInputValue(value) { - this.reset(); - this.append(value, { - raw: true - }, ''); - this.doCommit(); - } - get displayValue() { - return this.value; - } - get isComplete() { - return true; - } - get isFilled() { - return this.isComplete; - } - nearestInputPos(cursorPos, direction) { - return cursorPos; - } - totalInputPositions() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length; - return Math.min(this.value.length, toPos - fromPos); - } - extractInput() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length; - return this.value.slice(fromPos, toPos); - } - extractTail() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length; - return new ContinuousTailDetails(this.extractInput(fromPos, toPos), fromPos); - } - appendTail(tail) { - if (isString(tail)) tail = new ContinuousTailDetails(String(tail)); - return tail.appendTo(this); - } - _appendCharRaw(ch) { - if (!ch) return new ChangeDetails(); - this._value += ch; - return new ChangeDetails({ - inserted: ch, - rawInserted: ch - }); - } - _appendChar(ch) { - let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - let checkTail = arguments.length > 2 ? arguments[2] : undefined; - const consistentState = this.state; - let details; - [ch, details] = normalizePrepare(this.doPrepare(ch, flags)); - details = details.aggregate(this._appendCharRaw(ch, flags)); - if (details.inserted) { - let consistentTail; - let appended = this.doValidate(flags) !== false; - if (appended && checkTail != null) { - const beforeTailState = this.state; - if (this.overwrite === true) { - consistentTail = checkTail.state; - checkTail.unshift(this.value.length - details.tailShift); - } - let tailDetails = this.appendTail(checkTail); - appended = tailDetails.rawInserted === checkTail.toString(); - if (!(appended && tailDetails.inserted) && this.overwrite === 'shift') { - this.state = beforeTailState; - consistentTail = checkTail.state; - checkTail.shift(); - tailDetails = this.appendTail(checkTail); - appended = tailDetails.rawInserted === checkTail.toString(); - } - if (appended && tailDetails.inserted) this.state = beforeTailState; - } - if (!appended) { - details = new ChangeDetails(); - this.state = consistentState; - if (checkTail && consistentTail) checkTail.state = consistentTail; - } - } - return details; - } - _appendPlaceholder() { - return new ChangeDetails(); - } - _appendEager() { - return new ChangeDetails(); - } - append(str, flags, tail) { - if (!isString(str)) throw new Error('value should be string'); - const details = new ChangeDetails(); - const checkTail = isString(tail) ? new ContinuousTailDetails(String(tail)) : tail; - if (flags !== null && flags !== void 0 && flags.tail) flags._beforeTailState = this.state; - for (let ci = 0; ci < str.length; ++ci) { - const d = this._appendChar(str[ci], flags, checkTail); - if (!d.rawInserted && !this.doSkipInvalid(str[ci], flags, checkTail)) break; - details.aggregate(d); - } - if (checkTail != null) { - details.tailShift += this.appendTail(checkTail).tailShift; - } - if ((this.eager === true || this.eager === 'append') && flags !== null && flags !== void 0 && flags.input && str) { - details.aggregate(this._appendEager()); - } - return details; - } - remove() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length; - this._value = this.value.slice(0, fromPos) + this.value.slice(toPos); - return new ChangeDetails(); - } - withValueRefresh(fn) { - if (this._refreshing || !this.isInitialized) return fn(); - this._refreshing = true; - const rawInput = this.rawInputValue; - const value = this.value; - const ret = fn(); - this.rawInputValue = rawInput; - if (this.value && this.value !== value && value.indexOf(this.value) === 0) { - this.append(value.slice(this.value.length), {}, ''); - } - delete this._refreshing; - return ret; - } - runIsolated(fn) { - if (this._isolated || !this.isInitialized) return fn(this); - this._isolated = true; - const state = this.state; - const ret = fn(this); - this.state = state; - delete this._isolated; - return ret; - } - doSkipInvalid(ch) { - return this.skipInvalid; - } - doPrepare(str) { - let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - return this.prepare ? this.prepare(str, this, flags) : str; - } - doValidate(flags) { - return (!this.validate || this.validate(this.value, this, flags)) && (!this.parent || this.parent.doValidate(flags)); - } - doCommit() { - if (this.commit) this.commit(this.value, this); - } - doFormat(value) { - return this.format ? this.format(value, this) : value; - } - doParse(str) { - return this.parse ? this.parse(str, this) : str; - } - splice(start, deleteCount, inserted, removeDirection) { - let flags = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : { - input: true - }; - const tailPos = start + deleteCount; - const tail = this.extractTail(tailPos); - const eagerRemove = this.eager === true || this.eager === 'remove'; - let oldRawValue; - if (eagerRemove) { - removeDirection = forceDirection(removeDirection); - oldRawValue = this.extractInput(0, tailPos, { - raw: true - }); - } - let startChangePos = start; - const details = new ChangeDetails(); - if (removeDirection !== DIRECTION.NONE) { - startChangePos = this.nearestInputPos(start, deleteCount > 1 && start !== 0 && !eagerRemove ? DIRECTION.NONE : removeDirection); - details.tailShift = startChangePos - start; - } - details.aggregate(this.remove(startChangePos)); - if (eagerRemove && removeDirection !== DIRECTION.NONE && oldRawValue === this.rawInputValue) { - if (removeDirection === DIRECTION.FORCE_LEFT) { - let valLength; - while (oldRawValue === this.rawInputValue && (valLength = this.value.length)) { - details.aggregate(new ChangeDetails({ - tailShift: -1 - })).aggregate(this.remove(valLength - 1)); - } - } else if (removeDirection === DIRECTION.FORCE_RIGHT) { - tail.unshift(); - } - } - return details.aggregate(this.append(inserted, flags, tail)); - } - maskEquals(mask) { - return this.mask === mask; - } - typedValueEquals(value) { - const tval = this.typedValue; - return value === tval || Masked.EMPTY_VALUES.includes(value) && Masked.EMPTY_VALUES.includes(tval) || this.doFormat(value) === this.doFormat(this.typedValue); - } - } - Masked.DEFAULTS = { - format: String, - parse: v => v, - skipInvalid: true - }; - Masked.EMPTY_VALUES = [undefined, null, '']; - IMask.Masked = Masked; - - function maskedClass(mask) { - if (mask == null) { - throw new Error('mask property should be defined'); - } - if (mask instanceof RegExp) return IMask.MaskedRegExp; - if (isString(mask)) return IMask.MaskedPattern; - if (mask instanceof Date || mask === Date) return IMask.MaskedDate; - if (mask instanceof Number || typeof mask === 'number' || mask === Number) return IMask.MaskedNumber; - if (Array.isArray(mask) || mask === Array) return IMask.MaskedDynamic; - if (IMask.Masked && mask.prototype instanceof IMask.Masked) return mask; - if (mask instanceof IMask.Masked) return mask.constructor; - if (mask instanceof Function) return IMask.MaskedFunction; - console.warn('Mask not found for mask', mask); - return IMask.Masked; - } - function createMask(opts) { - if (IMask.Masked && opts instanceof IMask.Masked) return opts; - opts = Object.assign({}, opts); - const mask = opts.mask; - if (IMask.Masked && mask instanceof IMask.Masked) return mask; - const MaskedClass = maskedClass(mask); - if (!MaskedClass) throw new Error('Masked class is not found for provided mask, appropriate module needs to be import manually before creating mask.'); - return new MaskedClass(opts); - } - IMask.createMask = createMask; - - const _excluded$4 = ["parent", "isOptional", "placeholderChar", "displayChar", "lazy", "eager"]; - const DEFAULT_INPUT_DEFINITIONS = { - '0': /\d/, - 'a': /[\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/, - '*': /./ - }; - class PatternInputDefinition { - constructor(opts) { - const { - parent, - isOptional, - placeholderChar, - displayChar, - lazy, - eager - } = opts, - maskOpts = _objectWithoutPropertiesLoose(opts, _excluded$4); - this.masked = createMask(maskOpts); - Object.assign(this, { - parent, - isOptional, - placeholderChar, - displayChar, - lazy, - eager - }); - } - reset() { - this.isFilled = false; - this.masked.reset(); - } - remove() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length; - if (fromPos === 0 && toPos >= 1) { - this.isFilled = false; - return this.masked.remove(fromPos, toPos); - } - return new ChangeDetails(); - } - get value() { - return this.masked.value || (this.isFilled && !this.isOptional ? this.placeholderChar : ''); - } - get unmaskedValue() { - return this.masked.unmaskedValue; - } - get displayValue() { - return this.masked.value && this.displayChar || this.value; - } - get isComplete() { - return Boolean(this.masked.value) || this.isOptional; - } - _appendChar(ch) { - let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (this.isFilled) return new ChangeDetails(); - const state = this.masked.state; - const details = this.masked._appendChar(ch, flags); - if (details.inserted && this.doValidate(flags) === false) { - details.inserted = details.rawInserted = ''; - this.masked.state = state; - } - if (!details.inserted && !this.isOptional && !this.lazy && !flags.input) { - details.inserted = this.placeholderChar; - } - details.skip = !details.inserted && !this.isOptional; - this.isFilled = Boolean(details.inserted); - return details; - } - append() { - return this.masked.append(...arguments); - } - _appendPlaceholder() { - const details = new ChangeDetails(); - if (this.isFilled || this.isOptional) return details; - this.isFilled = true; - details.inserted = this.placeholderChar; - return details; - } - _appendEager() { - return new ChangeDetails(); - } - extractTail() { - return this.masked.extractTail(...arguments); - } - appendTail() { - return this.masked.appendTail(...arguments); - } - extractInput() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length; - let flags = arguments.length > 2 ? arguments[2] : undefined; - return this.masked.extractInput(fromPos, toPos, flags); - } - nearestInputPos(cursorPos) { - let direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DIRECTION.NONE; - const minPos = 0; - const maxPos = this.value.length; - const boundPos = Math.min(Math.max(cursorPos, minPos), maxPos); - switch (direction) { - case DIRECTION.LEFT: - case DIRECTION.FORCE_LEFT: - return this.isComplete ? boundPos : minPos; - case DIRECTION.RIGHT: - case DIRECTION.FORCE_RIGHT: - return this.isComplete ? boundPos : maxPos; - case DIRECTION.NONE: - default: - return boundPos; - } - } - totalInputPositions() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length; - return this.value.slice(fromPos, toPos).length; - } - doValidate() { - return this.masked.doValidate(...arguments) && (!this.parent || this.parent.doValidate(...arguments)); - } - doCommit() { - this.masked.doCommit(); - } - get state() { - return { - masked: this.masked.state, - isFilled: this.isFilled - }; - } - set state(state) { - this.masked.state = state.masked; - this.isFilled = state.isFilled; - } - } - - class PatternFixedDefinition { - constructor(opts) { - Object.assign(this, opts); - this._value = ''; - this.isFixed = true; - } - get value() { - return this._value; - } - get unmaskedValue() { - return this.isUnmasking ? this.value : ''; - } - get displayValue() { - return this.value; - } - reset() { - this._isRawInput = false; - this._value = ''; - } - remove() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this._value.length; - this._value = this._value.slice(0, fromPos) + this._value.slice(toPos); - if (!this._value) this._isRawInput = false; - return new ChangeDetails(); - } - nearestInputPos(cursorPos) { - let direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DIRECTION.NONE; - const minPos = 0; - const maxPos = this._value.length; - switch (direction) { - case DIRECTION.LEFT: - case DIRECTION.FORCE_LEFT: - return minPos; - case DIRECTION.NONE: - case DIRECTION.RIGHT: - case DIRECTION.FORCE_RIGHT: - default: - return maxPos; - } - } - totalInputPositions() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this._value.length; - return this._isRawInput ? toPos - fromPos : 0; - } - extractInput() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this._value.length; - let flags = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - return flags.raw && this._isRawInput && this._value.slice(fromPos, toPos) || ''; - } - get isComplete() { - return true; - } - get isFilled() { - return Boolean(this._value); - } - _appendChar(ch) { - let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - const details = new ChangeDetails(); - if (this.isFilled) return details; - const appendEager = this.eager === true || this.eager === 'append'; - const appended = this.char === ch; - const isResolved = appended && (this.isUnmasking || flags.input || flags.raw) && (!flags.raw || !appendEager) && !flags.tail; - if (isResolved) details.rawInserted = this.char; - this._value = details.inserted = this.char; - this._isRawInput = isResolved && (flags.raw || flags.input); - return details; - } - _appendEager() { - return this._appendChar(this.char, { - tail: true - }); - } - _appendPlaceholder() { - const details = new ChangeDetails(); - if (this.isFilled) return details; - this._value = details.inserted = this.char; - return details; - } - extractTail() { - arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length; - return new ContinuousTailDetails(''); - } - appendTail(tail) { - if (isString(tail)) tail = new ContinuousTailDetails(String(tail)); - return tail.appendTo(this); - } - append(str, flags, tail) { - const details = this._appendChar(str[0], flags); - if (tail != null) { - details.tailShift += this.appendTail(tail).tailShift; - } - return details; - } - doCommit() { } - get state() { - return { - _value: this._value, - _isRawInput: this._isRawInput - }; - } - set state(state) { - Object.assign(this, state); - } - } - - const _excluded$3 = ["chunks"]; - class ChunksTailDetails { - constructor() { - let chunks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - this.chunks = chunks; - this.from = from; - } - toString() { - return this.chunks.map(String).join(''); - } - extend(tailChunk) { - if (!String(tailChunk)) return; - if (isString(tailChunk)) tailChunk = new ContinuousTailDetails(String(tailChunk)); - const lastChunk = this.chunks[this.chunks.length - 1]; - const extendLast = lastChunk && ( - lastChunk.stop === tailChunk.stop || tailChunk.stop == null) && - tailChunk.from === lastChunk.from + lastChunk.toString().length; - if (tailChunk instanceof ContinuousTailDetails) { - if (extendLast) { - lastChunk.extend(tailChunk.toString()); - } else { - this.chunks.push(tailChunk); - } - } else if (tailChunk instanceof ChunksTailDetails) { - if (tailChunk.stop == null) { - let firstTailChunk; - while (tailChunk.chunks.length && tailChunk.chunks[0].stop == null) { - firstTailChunk = tailChunk.chunks.shift(); - firstTailChunk.from += tailChunk.from; - this.extend(firstTailChunk); - } - } - if (tailChunk.toString()) { - tailChunk.stop = tailChunk.blockIndex; - this.chunks.push(tailChunk); - } - } - } - appendTo(masked) { - if (!(masked instanceof IMask.MaskedPattern)) { - const tail = new ContinuousTailDetails(this.toString()); - return tail.appendTo(masked); - } - const details = new ChangeDetails(); - for (let ci = 0; ci < this.chunks.length && !details.skip; ++ci) { - const chunk = this.chunks[ci]; - const lastBlockIter = masked._mapPosToBlock(masked.value.length); - const stop = chunk.stop; - let chunkBlock; - if (stop != null && ( - !lastBlockIter || lastBlockIter.index <= stop)) { - if (chunk instanceof ChunksTailDetails || - masked._stops.indexOf(stop) >= 0) { - const phDetails = masked._appendPlaceholder(stop); - details.aggregate(phDetails); - } - chunkBlock = chunk instanceof ChunksTailDetails && masked._blocks[stop]; - } - if (chunkBlock) { - const tailDetails = chunkBlock.appendTail(chunk); - tailDetails.skip = false; - details.aggregate(tailDetails); - masked._value += tailDetails.inserted; - const remainChars = chunk.toString().slice(tailDetails.rawInserted.length); - if (remainChars) details.aggregate(masked.append(remainChars, { - tail: true - })); - } else { - details.aggregate(masked.append(chunk.toString(), { - tail: true - })); - } - } - return details; - } - get state() { - return { - chunks: this.chunks.map(c => c.state), - from: this.from, - stop: this.stop, - blockIndex: this.blockIndex - }; - } - set state(state) { - const { - chunks - } = state, - props = _objectWithoutPropertiesLoose(state, _excluded$3); - Object.assign(this, props); - this.chunks = chunks.map(cstate => { - const chunk = "chunks" in cstate ? new ChunksTailDetails() : new ContinuousTailDetails(); - chunk.state = cstate; - return chunk; - }); - } - unshift(beforePos) { - if (!this.chunks.length || beforePos != null && this.from >= beforePos) return ''; - const chunkShiftPos = beforePos != null ? beforePos - this.from : beforePos; - let ci = 0; - while (ci < this.chunks.length) { - const chunk = this.chunks[ci]; - const shiftChar = chunk.unshift(chunkShiftPos); - if (chunk.toString()) { - if (!shiftChar) break; - ++ci; - } else { - this.chunks.splice(ci, 1); - } - if (shiftChar) return shiftChar; - } - return ''; - } - shift() { - if (!this.chunks.length) return ''; - let ci = this.chunks.length - 1; - while (0 <= ci) { - const chunk = this.chunks[ci]; - const shiftChar = chunk.shift(); - if (chunk.toString()) { - if (!shiftChar) break; - --ci; - } else { - this.chunks.splice(ci, 1); - } - if (shiftChar) return shiftChar; - } - return ''; - } - } - - class PatternCursor { - constructor(masked, pos) { - this.masked = masked; - this._log = []; - const { - offset, - index - } = masked._mapPosToBlock(pos) || (pos < 0 ? - { - index: 0, - offset: 0 - } : - { - index: this.masked._blocks.length, - offset: 0 - }); - this.offset = offset; - this.index = index; - this.ok = false; - } - get block() { - return this.masked._blocks[this.index]; - } - get pos() { - return this.masked._blockStartPos(this.index) + this.offset; - } - get state() { - return { - index: this.index, - offset: this.offset, - ok: this.ok - }; - } - set state(s) { - Object.assign(this, s); - } - pushState() { - this._log.push(this.state); - } - popState() { - const s = this._log.pop(); - this.state = s; - return s; - } - bindBlock() { - if (this.block) return; - if (this.index < 0) { - this.index = 0; - this.offset = 0; - } - if (this.index >= this.masked._blocks.length) { - this.index = this.masked._blocks.length - 1; - this.offset = this.block.value.length; - } - } - _pushLeft(fn) { - this.pushState(); - for (this.bindBlock(); 0 <= this.index; --this.index, this.offset = ((_this$block = this.block) === null || _this$block === void 0 ? void 0 : _this$block.value.length) || 0) { - var _this$block; - if (fn()) return this.ok = true; - } - return this.ok = false; - } - _pushRight(fn) { - this.pushState(); - for (this.bindBlock(); this.index < this.masked._blocks.length; ++this.index, this.offset = 0) { - if (fn()) return this.ok = true; - } - return this.ok = false; - } - pushLeftBeforeFilled() { - return this._pushLeft(() => { - if (this.block.isFixed || !this.block.value) return; - this.offset = this.block.nearestInputPos(this.offset, DIRECTION.FORCE_LEFT); - if (this.offset !== 0) return true; - }); - } - pushLeftBeforeInput() { - return this._pushLeft(() => { - if (this.block.isFixed) return; - this.offset = this.block.nearestInputPos(this.offset, DIRECTION.LEFT); - return true; - }); - } - pushLeftBeforeRequired() { - return this._pushLeft(() => { - if (this.block.isFixed || this.block.isOptional && !this.block.value) return; - this.offset = this.block.nearestInputPos(this.offset, DIRECTION.LEFT); - return true; - }); - } - pushRightBeforeFilled() { - return this._pushRight(() => { - if (this.block.isFixed || !this.block.value) return; - this.offset = this.block.nearestInputPos(this.offset, DIRECTION.FORCE_RIGHT); - if (this.offset !== this.block.value.length) return true; - }); - } - pushRightBeforeInput() { - return this._pushRight(() => { - if (this.block.isFixed) return; - this.offset = this.block.nearestInputPos(this.offset, DIRECTION.NONE); - return true; - }); - } - pushRightBeforeRequired() { - return this._pushRight(() => { - if (this.block.isFixed || this.block.isOptional && !this.block.value) return; - this.offset = this.block.nearestInputPos(this.offset, DIRECTION.NONE); - return true; - }); - } - } - - class MaskedRegExp extends Masked { - _update(opts) { - if (opts.mask) opts.validate = value => value.search(opts.mask) >= 0; - super._update(opts); - } - } - IMask.MaskedRegExp = MaskedRegExp; - - const _excluded$2 = ["_blocks"]; - class MaskedPattern extends Masked { - constructor() { - let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - opts.definitions = Object.assign({}, DEFAULT_INPUT_DEFINITIONS, opts.definitions); - super(Object.assign({}, MaskedPattern.DEFAULTS, opts)); - } - _update() { - let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - opts.definitions = Object.assign({}, this.definitions, opts.definitions); - super._update(opts); - this._rebuildMask(); - } - _rebuildMask() { - const defs = this.definitions; - this._blocks = []; - this._stops = []; - this._maskedBlocks = {}; - let pattern = this.mask; - if (!pattern || !defs) return; - let unmaskingBlock = false; - let optionalBlock = false; - for (let i = 0; i < pattern.length; ++i) { - var _defs$char, _defs$char2; - if (this.blocks) { - const p = pattern.slice(i); - const bNames = Object.keys(this.blocks).filter(bName => p.indexOf(bName) === 0); - bNames.sort((a, b) => b.length - a.length); - const bName = bNames[0]; - if (bName) { - const maskedBlock = createMask(Object.assign({ - parent: this, - lazy: this.lazy, - eager: this.eager, - placeholderChar: this.placeholderChar, - displayChar: this.displayChar, - overwrite: this.overwrite - }, this.blocks[bName])); - if (maskedBlock) { - this._blocks.push(maskedBlock); - if (!this._maskedBlocks[bName]) this._maskedBlocks[bName] = []; - this._maskedBlocks[bName].push(this._blocks.length - 1); - } - i += bName.length - 1; - continue; - } - } - let char = pattern[i]; - let isInput = (char in defs); - if (char === MaskedPattern.STOP_CHAR) { - this._stops.push(this._blocks.length); - continue; - } - if (char === '{' || char === '}') { - unmaskingBlock = !unmaskingBlock; - continue; - } - if (char === '[' || char === ']') { - optionalBlock = !optionalBlock; - continue; - } - if (char === MaskedPattern.ESCAPE_CHAR) { - ++i; - char = pattern[i]; - if (!char) break; - isInput = false; - } - const maskOpts = (_defs$char = defs[char]) !== null && _defs$char !== void 0 && _defs$char.mask && !(((_defs$char2 = defs[char]) === null || _defs$char2 === void 0 ? void 0 : _defs$char2.mask.prototype) instanceof IMask.Masked) ? defs[char] : { - mask: defs[char] - }; - const def = isInput ? new PatternInputDefinition(Object.assign({ - parent: this, - isOptional: optionalBlock, - lazy: this.lazy, - eager: this.eager, - placeholderChar: this.placeholderChar, - displayChar: this.displayChar - }, maskOpts)) : new PatternFixedDefinition({ - char, - eager: this.eager, - isUnmasking: unmaskingBlock - }); - this._blocks.push(def); - } - } - get state() { - return Object.assign({}, super.state, { - _blocks: this._blocks.map(b => b.state) - }); - } - set state(state) { - const { - _blocks - } = state, - maskedState = _objectWithoutPropertiesLoose(state, _excluded$2); - this._blocks.forEach((b, bi) => b.state = _blocks[bi]); - super.state = maskedState; - } - reset() { - super.reset(); - this._blocks.forEach(b => b.reset()); - } - get isComplete() { - return this._blocks.every(b => b.isComplete); - } - get isFilled() { - return this._blocks.every(b => b.isFilled); - } - get isFixed() { - return this._blocks.every(b => b.isFixed); - } - get isOptional() { - return this._blocks.every(b => b.isOptional); - } - doCommit() { - this._blocks.forEach(b => b.doCommit()); - super.doCommit(); - } - get unmaskedValue() { - return this._blocks.reduce((str, b) => str += b.unmaskedValue, ''); - } - set unmaskedValue(unmaskedValue) { - super.unmaskedValue = unmaskedValue; - } - get value() { - return this._blocks.reduce((str, b) => str += b.value, ''); - } - set value(value) { - super.value = value; - } - get displayValue() { - return this._blocks.reduce((str, b) => str += b.displayValue, ''); - } - appendTail(tail) { - return super.appendTail(tail).aggregate(this._appendPlaceholder()); - } - _appendEager() { - var _this$_mapPosToBlock; - const details = new ChangeDetails(); - let startBlockIndex = (_this$_mapPosToBlock = this._mapPosToBlock(this.value.length)) === null || _this$_mapPosToBlock === void 0 ? void 0 : _this$_mapPosToBlock.index; - if (startBlockIndex == null) return details; - if (this._blocks[startBlockIndex].isFilled) ++startBlockIndex; - for (let bi = startBlockIndex; bi < this._blocks.length; ++bi) { - const d = this._blocks[bi]._appendEager(); - if (!d.inserted) break; - details.aggregate(d); - } - return details; - } - _appendCharRaw(ch) { - let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - const blockIter = this._mapPosToBlock(this.value.length); - const details = new ChangeDetails(); - if (!blockIter) return details; - for (let bi = blockIter.index; ; ++bi) { - var _flags$_beforeTailSta, _flags$_beforeTailSta2; - const block = this._blocks[bi]; - if (!block) break; - const blockDetails = block._appendChar(ch, Object.assign({}, flags, { - _beforeTailState: (_flags$_beforeTailSta = flags._beforeTailState) === null || _flags$_beforeTailSta === void 0 ? void 0 : (_flags$_beforeTailSta2 = _flags$_beforeTailSta._blocks) === null || _flags$_beforeTailSta2 === void 0 ? void 0 : _flags$_beforeTailSta2[bi] - })); - const skip = blockDetails.skip; - details.aggregate(blockDetails); - if (skip || blockDetails.rawInserted) break; - } - return details; - } - extractTail() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length; - const chunkTail = new ChunksTailDetails(); - if (fromPos === toPos) return chunkTail; - this._forEachBlocksInRange(fromPos, toPos, (b, bi, bFromPos, bToPos) => { - const blockChunk = b.extractTail(bFromPos, bToPos); - blockChunk.stop = this._findStopBefore(bi); - blockChunk.from = this._blockStartPos(bi); - if (blockChunk instanceof ChunksTailDetails) blockChunk.blockIndex = bi; - chunkTail.extend(blockChunk); - }); - return chunkTail; - } - extractInput() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length; - let flags = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - if (fromPos === toPos) return ''; - let input = ''; - this._forEachBlocksInRange(fromPos, toPos, (b, _, fromPos, toPos) => { - input += b.extractInput(fromPos, toPos, flags); - }); - return input; - } - _findStopBefore(blockIndex) { - let stopBefore; - for (let si = 0; si < this._stops.length; ++si) { - const stop = this._stops[si]; - if (stop <= blockIndex) stopBefore = stop; else break; - } - return stopBefore; - } - _appendPlaceholder(toBlockIndex) { - const details = new ChangeDetails(); - if (this.lazy && toBlockIndex == null) return details; - const startBlockIter = this._mapPosToBlock(this.value.length); - if (!startBlockIter) return details; - const startBlockIndex = startBlockIter.index; - const endBlockIndex = toBlockIndex != null ? toBlockIndex : this._blocks.length; - this._blocks.slice(startBlockIndex, endBlockIndex).forEach(b => { - if (!b.lazy || toBlockIndex != null) { - const args = b._blocks != null ? [b._blocks.length] : []; - const bDetails = b._appendPlaceholder(...args); - this._value += bDetails.inserted; - details.aggregate(bDetails); - } - }); - return details; - } - _mapPosToBlock(pos) { - let accVal = ''; - for (let bi = 0; bi < this._blocks.length; ++bi) { - const block = this._blocks[bi]; - const blockStartPos = accVal.length; - accVal += block.value; - if (pos <= accVal.length) { - return { - index: bi, - offset: pos - blockStartPos - }; - } - } - } - _blockStartPos(blockIndex) { - return this._blocks.slice(0, blockIndex).reduce((pos, b) => pos += b.value.length, 0); - } - _forEachBlocksInRange(fromPos) { - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length; - let fn = arguments.length > 2 ? arguments[2] : undefined; - const fromBlockIter = this._mapPosToBlock(fromPos); - if (fromBlockIter) { - const toBlockIter = this._mapPosToBlock(toPos); - const isSameBlock = toBlockIter && fromBlockIter.index === toBlockIter.index; - const fromBlockStartPos = fromBlockIter.offset; - const fromBlockEndPos = toBlockIter && isSameBlock ? toBlockIter.offset : this._blocks[fromBlockIter.index].value.length; - fn(this._blocks[fromBlockIter.index], fromBlockIter.index, fromBlockStartPos, fromBlockEndPos); - if (toBlockIter && !isSameBlock) { - for (let bi = fromBlockIter.index + 1; bi < toBlockIter.index; ++bi) { - fn(this._blocks[bi], bi, 0, this._blocks[bi].value.length); - } - fn(this._blocks[toBlockIter.index], toBlockIter.index, 0, toBlockIter.offset); - } - } - } - remove() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length; - const removeDetails = super.remove(fromPos, toPos); - this._forEachBlocksInRange(fromPos, toPos, (b, _, bFromPos, bToPos) => { - removeDetails.aggregate(b.remove(bFromPos, bToPos)); - }); - return removeDetails; - } - nearestInputPos(cursorPos) { - let direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DIRECTION.NONE; - if (!this._blocks.length) return 0; - const cursor = new PatternCursor(this, cursorPos); - if (direction === DIRECTION.NONE) { - if (cursor.pushRightBeforeInput()) return cursor.pos; - cursor.popState(); - if (cursor.pushLeftBeforeInput()) return cursor.pos; - return this.value.length; - } - if (direction === DIRECTION.LEFT || direction === DIRECTION.FORCE_LEFT) { - if (direction === DIRECTION.LEFT) { - cursor.pushRightBeforeFilled(); - if (cursor.ok && cursor.pos === cursorPos) return cursorPos; - cursor.popState(); - } - cursor.pushLeftBeforeInput(); - cursor.pushLeftBeforeRequired(); - cursor.pushLeftBeforeFilled(); - if (direction === DIRECTION.LEFT) { - cursor.pushRightBeforeInput(); - cursor.pushRightBeforeRequired(); - if (cursor.ok && cursor.pos <= cursorPos) return cursor.pos; - cursor.popState(); - if (cursor.ok && cursor.pos <= cursorPos) return cursor.pos; - cursor.popState(); - } - if (cursor.ok) return cursor.pos; - if (direction === DIRECTION.FORCE_LEFT) return 0; - cursor.popState(); - if (cursor.ok) return cursor.pos; - cursor.popState(); - if (cursor.ok) return cursor.pos; - return 0; - } - if (direction === DIRECTION.RIGHT || direction === DIRECTION.FORCE_RIGHT) { - cursor.pushRightBeforeInput(); - cursor.pushRightBeforeRequired(); - if (cursor.pushRightBeforeFilled()) return cursor.pos; - if (direction === DIRECTION.FORCE_RIGHT) return this.value.length; - cursor.popState(); - if (cursor.ok) return cursor.pos; - cursor.popState(); - if (cursor.ok) return cursor.pos; - return this.nearestInputPos(cursorPos, DIRECTION.LEFT); - } - return cursorPos; - } - totalInputPositions() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length; - let total = 0; - this._forEachBlocksInRange(fromPos, toPos, (b, _, bFromPos, bToPos) => { - total += b.totalInputPositions(bFromPos, bToPos); - }); - return total; - } - maskedBlock(name) { - return this.maskedBlocks(name)[0]; - } - maskedBlocks(name) { - const indices = this._maskedBlocks[name]; - if (!indices) return []; - return indices.map(gi => this._blocks[gi]); - } - } - MaskedPattern.DEFAULTS = { - lazy: true, - placeholderChar: '_' - }; - MaskedPattern.STOP_CHAR = '`'; - MaskedPattern.ESCAPE_CHAR = '\\'; - MaskedPattern.InputDefinition = PatternInputDefinition; - MaskedPattern.FixedDefinition = PatternFixedDefinition; - IMask.MaskedPattern = MaskedPattern; - - class MaskedRange extends MaskedPattern { - get _matchFrom() { - return this.maxLength - String(this.from).length; - } - _update(opts) { - opts = Object.assign({ - to: this.to || 0, - from: this.from || 0, - maxLength: this.maxLength || 0 - }, opts); - let maxLength = String(opts.to).length; - if (opts.maxLength != null) maxLength = Math.max(maxLength, opts.maxLength); - opts.maxLength = maxLength; - const fromStr = String(opts.from).padStart(maxLength, '0'); - const toStr = String(opts.to).padStart(maxLength, '0'); - let sameCharsCount = 0; - while (sameCharsCount < toStr.length && toStr[sameCharsCount] === fromStr[sameCharsCount]) ++sameCharsCount; - opts.mask = toStr.slice(0, sameCharsCount).replace(/0/g, '\\0') + '0'.repeat(maxLength - sameCharsCount); - super._update(opts); - } - get isComplete() { - return super.isComplete && Boolean(this.value); - } - boundaries(str) { - let minstr = ''; - let maxstr = ''; - const [, placeholder, num] = str.match(/^(\D*)(\d*)(\D*)/) || []; - if (num) { - minstr = '0'.repeat(placeholder.length) + num; - maxstr = '9'.repeat(placeholder.length) + num; - } - minstr = minstr.padEnd(this.maxLength, '0'); - maxstr = maxstr.padEnd(this.maxLength, '9'); - return [minstr, maxstr]; - } - doPrepare(ch) { - let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - let details; - [ch, details] = normalizePrepare(super.doPrepare(ch.replace(/\D/g, ''), flags)); - if (!this.autofix || !ch) return ch; - const fromStr = String(this.from).padStart(this.maxLength, '0'); - const toStr = String(this.to).padStart(this.maxLength, '0'); - let nextVal = this.value + ch; - if (nextVal.length > this.maxLength) return ''; - const [minstr, maxstr] = this.boundaries(nextVal); - if (Number(maxstr) < this.from) return fromStr[nextVal.length - 1]; - if (Number(minstr) > this.to) { - if (this.autofix === 'pad' && nextVal.length < this.maxLength) { - return ['', details.aggregate(this.append(fromStr[nextVal.length - 1] + ch, flags))]; - } - return toStr[nextVal.length - 1]; - } - return ch; - } - doValidate() { - const str = this.value; - const firstNonZero = str.search(/[^0]/); - if (firstNonZero === -1 && str.length <= this._matchFrom) return true; - const [minstr, maxstr] = this.boundaries(str); - return this.from <= Number(maxstr) && Number(minstr) <= this.to && super.doValidate(...arguments); - } - } - IMask.MaskedRange = MaskedRange; - - class MaskedDate extends MaskedPattern { - constructor(opts) { - super(Object.assign({}, MaskedDate.DEFAULTS, opts)); - } - _update(opts) { - if (opts.mask === Date) delete opts.mask; - if (opts.pattern) opts.mask = opts.pattern; - const blocks = opts.blocks; - opts.blocks = Object.assign({}, MaskedDate.GET_DEFAULT_BLOCKS()); - if (opts.min) opts.blocks.Y.from = opts.min.getFullYear(); - if (opts.max) opts.blocks.Y.to = opts.max.getFullYear(); - if (opts.min && opts.max && opts.blocks.Y.from === opts.blocks.Y.to) { - opts.blocks.m.from = opts.min.getMonth() + 1; - opts.blocks.m.to = opts.max.getMonth() + 1; - if (opts.blocks.m.from === opts.blocks.m.to) { - opts.blocks.d.from = opts.min.getDate(); - opts.blocks.d.to = opts.max.getDate(); - } - } - Object.assign(opts.blocks, this.blocks, blocks); - Object.keys(opts.blocks).forEach(bk => { - const b = opts.blocks[bk]; - if (!('autofix' in b) && 'autofix' in opts) b.autofix = opts.autofix; - }); - super._update(opts); - } - doValidate() { - const date = this.date; - return super.doValidate(...arguments) && (!this.isComplete || this.isDateExist(this.value) && date != null && (this.min == null || this.min <= date) && (this.max == null || date <= this.max)); - } - isDateExist(str) { - return this.format(this.parse(str, this), this).indexOf(str) >= 0; - } - get date() { - return this.typedValue; - } - set date(date) { - this.typedValue = date; - } - get typedValue() { - return this.isComplete ? super.typedValue : null; - } - set typedValue(value) { - super.typedValue = value; - } - maskEquals(mask) { - return mask === Date || super.maskEquals(mask); - } - } - MaskedDate.DEFAULTS = { - pattern: 'd{.}`m{.}`Y', - format: date => { - if (!date) return ''; - const day = String(date.getDate()).padStart(2, '0'); - const month = String(date.getMonth() + 1).padStart(2, '0'); - const year = date.getFullYear(); - return [day, month, year].join('.'); - }, - parse: str => { - const [day, month, year] = str.split('.'); - return new Date(year, month - 1, day); - } - }; - MaskedDate.GET_DEFAULT_BLOCKS = () => ({ - d: { - mask: MaskedRange, - from: 1, - to: 31, - maxLength: 2 - }, - m: { - mask: MaskedRange, - from: 1, - to: 12, - maxLength: 2 - }, - Y: { - mask: MaskedRange, - from: 1900, - to: 9999 - } - }); - IMask.MaskedDate = MaskedDate; - - class MaskElement { - get selectionStart() { - let start; - try { - start = this._unsafeSelectionStart; - } catch (e) { } - return start != null ? start : this.value.length; - } - get selectionEnd() { - let end; - try { - end = this._unsafeSelectionEnd; - } catch (e) { } - return end != null ? end : this.value.length; - } - select(start, end) { - if (start == null || end == null || start === this.selectionStart && end === this.selectionEnd) return; - try { - this._unsafeSelect(start, end); - } catch (e) { } - } - _unsafeSelect(start, end) { } - get isActive() { - return false; - } - bindEvents(handlers) { } - unbindEvents() { } - } - IMask.MaskElement = MaskElement; - - class HTMLMaskElement extends MaskElement { - constructor(input) { - super(); - this.input = input; - this._handlers = {}; - } - get rootElement() { - var _this$input$getRootNo, _this$input$getRootNo2, _this$input; - return (_this$input$getRootNo = (_this$input$getRootNo2 = (_this$input = this.input).getRootNode) === null || _this$input$getRootNo2 === void 0 ? void 0 : _this$input$getRootNo2.call(_this$input)) !== null && _this$input$getRootNo !== void 0 ? _this$input$getRootNo : document; - } - get isActive() { - return this.input === this.rootElement.activeElement; - } - get _unsafeSelectionStart() { - return this.input.selectionStart; - } - get _unsafeSelectionEnd() { - return this.input.selectionEnd; - } - _unsafeSelect(start, end) { - this.input.setSelectionRange(start, end); - } - get value() { - return this.input.value; - } - set value(value) { - this.input.value = value; - } - bindEvents(handlers) { - Object.keys(handlers).forEach(event => this._toggleEventHandler(HTMLMaskElement.EVENTS_MAP[event], handlers[event])); - } - unbindEvents() { - Object.keys(this._handlers).forEach(event => this._toggleEventHandler(event)); - } - _toggleEventHandler(event, handler) { - if (this._handlers[event]) { - this.input.removeEventListener(event, this._handlers[event]); - delete this._handlers[event]; - } - if (handler) { - this.input.addEventListener(event, handler); - this._handlers[event] = handler; - } - } - } - HTMLMaskElement.EVENTS_MAP = { - selectionChange: 'keydown', - input: 'input', - drop: 'drop', - click: 'click', - focus: 'focus', - commit: 'blur' - }; - IMask.HTMLMaskElement = HTMLMaskElement; - - class HTMLContenteditableMaskElement extends HTMLMaskElement { - get _unsafeSelectionStart() { - const root = this.rootElement; - const selection = root.getSelection && root.getSelection(); - const anchorOffset = selection && selection.anchorOffset; - const focusOffset = selection && selection.focusOffset; - if (focusOffset == null || anchorOffset == null || anchorOffset < focusOffset) { - return anchorOffset; - } - return focusOffset; - } - get _unsafeSelectionEnd() { - const root = this.rootElement; - const selection = root.getSelection && root.getSelection(); - const anchorOffset = selection && selection.anchorOffset; - const focusOffset = selection && selection.focusOffset; - if (focusOffset == null || anchorOffset == null || anchorOffset > focusOffset) { - return anchorOffset; - } - return focusOffset; - } - _unsafeSelect(start, end) { - if (!this.rootElement.createRange) return; - const range = this.rootElement.createRange(); - range.setStart(this.input.firstChild || this.input, start); - range.setEnd(this.input.lastChild || this.input, end); - const root = this.rootElement; - const selection = root.getSelection && root.getSelection(); - if (selection) { - selection.removeAllRanges(); - selection.addRange(range); - } - } - get value() { - return this.input.textContent; - } - set value(value) { - this.input.textContent = value; - } - } - IMask.HTMLContenteditableMaskElement = HTMLContenteditableMaskElement; - - const _excluded$1 = ["mask"]; - class InputMask { - constructor(el, opts) { - this.el = el instanceof MaskElement ? el : el.isContentEditable && el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA' ? new HTMLContenteditableMaskElement(el) : new HTMLMaskElement(el); - this.masked = createMask(opts); - this._listeners = {}; - this._value = ''; - this._unmaskedValue = ''; - this._saveSelection = this._saveSelection.bind(this); - this._onInput = this._onInput.bind(this); - this._onChange = this._onChange.bind(this); - this._onDrop = this._onDrop.bind(this); - this._onFocus = this._onFocus.bind(this); - this._onClick = this._onClick.bind(this); - this.alignCursor = this.alignCursor.bind(this); - this.alignCursorFriendly = this.alignCursorFriendly.bind(this); - this._bindEvents(); - this.updateValue(); - this._onChange(); - } - get mask() { - return this.masked.mask; - } - maskEquals(mask) { - var _this$masked; - return mask == null || ((_this$masked = this.masked) === null || _this$masked === void 0 ? void 0 : _this$masked.maskEquals(mask)); - } - set mask(mask) { - if (this.maskEquals(mask)) return; - if (!(mask instanceof IMask.Masked) && this.masked.constructor === maskedClass(mask)) { - this.masked.updateOptions({ - mask - }); - return; - } - const masked = createMask({ - mask - }); - masked.unmaskedValue = this.masked.unmaskedValue; - this.masked = masked; - } - get value() { - return this._value; - } - set value(str) { - if (this.value === str) return; - this.masked.value = str; - this.updateControl(); - this.alignCursor(); - } - get unmaskedValue() { - return this._unmaskedValue; - } - set unmaskedValue(str) { - if (this.unmaskedValue === str) return; - this.masked.unmaskedValue = str; - this.updateControl(); - this.alignCursor(); - } - get typedValue() { - return this.masked.typedValue; - } - set typedValue(val) { - if (this.masked.typedValueEquals(val)) return; - this.masked.typedValue = val; - this.updateControl(); - this.alignCursor(); - } - get displayValue() { - return this.masked.displayValue; - } - _bindEvents() { - this.el.bindEvents({ - selectionChange: this._saveSelection, - input: this._onInput, - drop: this._onDrop, - click: this._onClick, - focus: this._onFocus, - commit: this._onChange - }); - } - _unbindEvents() { - if (this.el) this.el.unbindEvents(); - } - _fireEvent(ev) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - const listeners = this._listeners[ev]; - if (!listeners) return; - listeners.forEach(l => l(...args)); - } - get selectionStart() { - return this._cursorChanging ? this._changingCursorPos : this.el.selectionStart; - } - get cursorPos() { - return this._cursorChanging ? this._changingCursorPos : this.el.selectionEnd; - } - set cursorPos(pos) { - if (!this.el || !this.el.isActive) return; - this.el.select(pos, pos); - this._saveSelection(); - } - _saveSelection( - ) { - if (this.displayValue !== this.el.value) { - console.warn('Element value was changed outside of mask. Syncronize mask using `mask.updateValue()` to work properly.'); - } - this._selection = { - start: this.selectionStart, - end: this.cursorPos - }; - } - updateValue() { - this.masked.value = this.el.value; - this._value = this.masked.value; - } - updateControl() { - const newUnmaskedValue = this.masked.unmaskedValue; - const newValue = this.masked.value; - const newDisplayValue = this.displayValue; - const isChanged = this.unmaskedValue !== newUnmaskedValue || this.value !== newValue; - this._unmaskedValue = newUnmaskedValue; - this._value = newValue; - if (this.el.value !== newDisplayValue) this.el.value = newDisplayValue; - if (isChanged) this._fireChangeEvents(); - } - updateOptions(opts) { - const { - mask - } = opts, - restOpts = _objectWithoutPropertiesLoose(opts, _excluded$1); - const updateMask = !this.maskEquals(mask); - const updateOpts = !objectIncludes(this.masked, restOpts); - if (updateMask) this.mask = mask; - if (updateOpts) this.masked.updateOptions(restOpts); - if (updateMask || updateOpts) this.updateControl(); - } - updateCursor(cursorPos) { - if (cursorPos == null) return; - this.cursorPos = cursorPos; - this._delayUpdateCursor(cursorPos); - } - _delayUpdateCursor(cursorPos) { - this._abortUpdateCursor(); - this._changingCursorPos = cursorPos; - this._cursorChanging = setTimeout(() => { - if (!this.el) return; - this.cursorPos = this._changingCursorPos; - this._abortUpdateCursor(); - }, 10); - } - _fireChangeEvents() { - this._fireEvent('accept', this._inputEvent); - if (this.masked.isComplete) this._fireEvent('complete', this._inputEvent); - } - _abortUpdateCursor() { - if (this._cursorChanging) { - clearTimeout(this._cursorChanging); - delete this._cursorChanging; - } - } - alignCursor() { - this.cursorPos = this.masked.nearestInputPos(this.masked.nearestInputPos(this.cursorPos, DIRECTION.LEFT)); - } - alignCursorFriendly() { - if (this.selectionStart !== this.cursorPos) return; - this.alignCursor(); - } - on(ev, handler) { - if (!this._listeners[ev]) this._listeners[ev] = []; - this._listeners[ev].push(handler); - return this; - } - off(ev, handler) { - if (!this._listeners[ev]) return this; - if (!handler) { - delete this._listeners[ev]; - return this; - } - const hIndex = this._listeners[ev].indexOf(handler); - if (hIndex >= 0) this._listeners[ev].splice(hIndex, 1); - return this; - } - _onInput(e) { - this._inputEvent = e; - this._abortUpdateCursor(); - if (!this._selection) return this.updateValue(); - const details = new ActionDetails( - this.el.value, this.cursorPos, - this.displayValue, this._selection); - const oldRawValue = this.masked.rawInputValue; - const offset = this.masked.splice(details.startChangePos, details.removed.length, details.inserted, details.removeDirection, { - input: true, - raw: true - }).offset; - const removeDirection = oldRawValue === this.masked.rawInputValue ? details.removeDirection : DIRECTION.NONE; - let cursorPos = this.masked.nearestInputPos(details.startChangePos + offset, removeDirection); - if (removeDirection !== DIRECTION.NONE) cursorPos = this.masked.nearestInputPos(cursorPos, DIRECTION.NONE); - this.updateControl(); - this.updateCursor(cursorPos); - delete this._inputEvent; - } - _onChange() { - if (this.displayValue !== this.el.value) { - this.updateValue(); - } - this.masked.doCommit(); - this.updateControl(); - this._saveSelection(); - } - _onDrop(ev) { - ev.preventDefault(); - ev.stopPropagation(); - } - _onFocus(ev) { - this.alignCursorFriendly(); - } - _onClick(ev) { - this.alignCursorFriendly(); - } - destroy() { - this._unbindEvents(); - this._listeners.length = 0; - delete this.el; - } - } - IMask.InputMask = InputMask; - - class MaskedEnum extends MaskedPattern { - _update(opts) { - if (opts.enum) opts.mask = '*'.repeat(opts.enum[0].length); - super._update(opts); - } - doValidate() { - return this.enum.some(e => e.indexOf(this.unmaskedValue) >= 0) && super.doValidate(...arguments); - } - } - IMask.MaskedEnum = MaskedEnum; - - class MaskedNumber extends Masked { - constructor(opts) { - super(Object.assign({}, MaskedNumber.DEFAULTS, opts)); - } - _update(opts) { - super._update(opts); - this._updateRegExps(); - } - _updateRegExps() { - let start = '^' + (this.allowNegative ? '[+|\\-]?' : ''); - let mid = '\\d*'; - let end = (this.scale ? "(".concat(escapeRegExp(this.radix), "\\d{0,").concat(this.scale, "})?") : '') + '$'; - this._numberRegExp = new RegExp(start + mid + end); - this._mapToRadixRegExp = new RegExp("[".concat(this.mapToRadix.map(escapeRegExp).join(''), "]"), 'g'); - this._thousandsSeparatorRegExp = new RegExp(escapeRegExp(this.thousandsSeparator), 'g'); - } - _removeThousandsSeparators(value) { - return value.replace(this._thousandsSeparatorRegExp, ''); - } - _insertThousandsSeparators(value) { - const parts = value.split(this.radix); - parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, this.thousandsSeparator); - return parts.join(this.radix); - } - doPrepare(ch) { - let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - ch = this._removeThousandsSeparators(this.scale && this.mapToRadix.length && ( - flags.input && flags.raw || !flags.input && !flags.raw) ? ch.replace(this._mapToRadixRegExp, this.radix) : ch); - const [prepCh, details] = normalizePrepare(super.doPrepare(ch, flags)); - if (ch && !prepCh) details.skip = true; - return [prepCh, details]; - } - _separatorsCount(to) { - let extendOnSeparators = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - let count = 0; - for (let pos = 0; pos < to; ++pos) { - if (this._value.indexOf(this.thousandsSeparator, pos) === pos) { - ++count; - if (extendOnSeparators) to += this.thousandsSeparator.length; - } - } - return count; - } - _separatorsCountFromSlice() { - let slice = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this._value; - return this._separatorsCount(this._removeThousandsSeparators(slice).length, true); - } - extractInput() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length; - let flags = arguments.length > 2 ? arguments[2] : undefined; - [fromPos, toPos] = this._adjustRangeWithSeparators(fromPos, toPos); - return this._removeThousandsSeparators(super.extractInput(fromPos, toPos, flags)); - } - _appendCharRaw(ch) { - let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (!this.thousandsSeparator) return super._appendCharRaw(ch, flags); - const prevBeforeTailValue = flags.tail && flags._beforeTailState ? flags._beforeTailState._value : this._value; - const prevBeforeTailSeparatorsCount = this._separatorsCountFromSlice(prevBeforeTailValue); - this._value = this._removeThousandsSeparators(this.value); - const appendDetails = super._appendCharRaw(ch, flags); - this._value = this._insertThousandsSeparators(this._value); - const beforeTailValue = flags.tail && flags._beforeTailState ? flags._beforeTailState._value : this._value; - const beforeTailSeparatorsCount = this._separatorsCountFromSlice(beforeTailValue); - appendDetails.tailShift += (beforeTailSeparatorsCount - prevBeforeTailSeparatorsCount) * this.thousandsSeparator.length; - appendDetails.skip = !appendDetails.rawInserted && ch === this.thousandsSeparator; - return appendDetails; - } - _findSeparatorAround(pos) { - if (this.thousandsSeparator) { - const searchFrom = pos - this.thousandsSeparator.length + 1; - const separatorPos = this.value.indexOf(this.thousandsSeparator, searchFrom); - if (separatorPos <= pos) return separatorPos; - } - return -1; - } - _adjustRangeWithSeparators(from, to) { - const separatorAroundFromPos = this._findSeparatorAround(from); - if (separatorAroundFromPos >= 0) from = separatorAroundFromPos; - const separatorAroundToPos = this._findSeparatorAround(to); - if (separatorAroundToPos >= 0) to = separatorAroundToPos + this.thousandsSeparator.length; - return [from, to]; - } - remove() { - let fromPos = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - let toPos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.value.length; - [fromPos, toPos] = this._adjustRangeWithSeparators(fromPos, toPos); - const valueBeforePos = this.value.slice(0, fromPos); - const valueAfterPos = this.value.slice(toPos); - const prevBeforeTailSeparatorsCount = this._separatorsCount(valueBeforePos.length); - this._value = this._insertThousandsSeparators(this._removeThousandsSeparators(valueBeforePos + valueAfterPos)); - const beforeTailSeparatorsCount = this._separatorsCountFromSlice(valueBeforePos); - return new ChangeDetails({ - tailShift: (beforeTailSeparatorsCount - prevBeforeTailSeparatorsCount) * this.thousandsSeparator.length - }); - } - nearestInputPos(cursorPos, direction) { - if (!this.thousandsSeparator) return cursorPos; - switch (direction) { - case DIRECTION.NONE: - case DIRECTION.LEFT: - case DIRECTION.FORCE_LEFT: - { - const separatorAtLeftPos = this._findSeparatorAround(cursorPos - 1); - if (separatorAtLeftPos >= 0) { - const separatorAtLeftEndPos = separatorAtLeftPos + this.thousandsSeparator.length; - if (cursorPos < separatorAtLeftEndPos || this.value.length <= separatorAtLeftEndPos || direction === DIRECTION.FORCE_LEFT) { - return separatorAtLeftPos; - } - } - break; - } - case DIRECTION.RIGHT: - case DIRECTION.FORCE_RIGHT: - { - const separatorAtRightPos = this._findSeparatorAround(cursorPos); - if (separatorAtRightPos >= 0) { - return separatorAtRightPos + this.thousandsSeparator.length; - } - } - } - return cursorPos; - } - doValidate(flags) { - let valid = Boolean(this._removeThousandsSeparators(this.value).match(this._numberRegExp)); - if (valid) { - const number = this.number; - valid = valid && !isNaN(number) && ( - this.min == null || this.min >= 0 || this.min <= this.number) && ( - this.max == null || this.max <= 0 || this.number <= this.max); - } - return valid && super.doValidate(flags); - } - doCommit() { - if (this.value) { - const number = this.number; - let validnum = number; - if (this.min != null) validnum = Math.max(validnum, this.min); - if (this.max != null) validnum = Math.min(validnum, this.max); - if (validnum !== number) this.unmaskedValue = this.doFormat(validnum); - let formatted = this.value; - if (this.normalizeZeros) formatted = this._normalizeZeros(formatted); - if (this.padFractionalZeros && this.scale > 0) formatted = this._padFractionalZeros(formatted); - this._value = formatted; - } - super.doCommit(); - } - _normalizeZeros(value) { - const parts = this._removeThousandsSeparators(value).split(this.radix); - parts[0] = parts[0].replace(/^(\D*)(0*)(\d*)/, (match, sign, zeros, num) => sign + num); - if (value.length && !/\d$/.test(parts[0])) parts[0] = parts[0] + '0'; - if (parts.length > 1) { - parts[1] = parts[1].replace(/0*$/, ''); - if (!parts[1].length) parts.length = 1; - } - return this._insertThousandsSeparators(parts.join(this.radix)); - } - _padFractionalZeros(value) { - if (!value) return value; - const parts = value.split(this.radix); - if (parts.length < 2) parts.push(''); - parts[1] = parts[1].padEnd(this.scale, '0'); - return parts.join(this.radix); - } - doSkipInvalid(ch) { - let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - let checkTail = arguments.length > 2 ? arguments[2] : undefined; - const dropFractional = this.scale === 0 && ch !== this.thousandsSeparator && (ch === this.radix || ch === MaskedNumber.UNMASKED_RADIX || this.mapToRadix.includes(ch)); - return super.doSkipInvalid(ch, flags, checkTail) && !dropFractional; - } - get unmaskedValue() { - return this._removeThousandsSeparators(this._normalizeZeros(this.value)).replace(this.radix, MaskedNumber.UNMASKED_RADIX); - } - set unmaskedValue(unmaskedValue) { - super.unmaskedValue = unmaskedValue; - } - get typedValue() { - return this.doParse(this.unmaskedValue); - } - set typedValue(n) { - this.rawInputValue = this.doFormat(n).replace(MaskedNumber.UNMASKED_RADIX, this.radix); - } - get number() { - return this.typedValue; - } - set number(number) { - this.typedValue = number; - } - get allowNegative() { - return this.signed || this.min != null && this.min < 0 || this.max != null && this.max < 0; - } - typedValueEquals(value) { - return (super.typedValueEquals(value) || MaskedNumber.EMPTY_VALUES.includes(value) && MaskedNumber.EMPTY_VALUES.includes(this.typedValue)) && !(value === 0 && this.value === ''); - } - } - MaskedNumber.UNMASKED_RADIX = '.'; - MaskedNumber.DEFAULTS = { - radix: ',', - thousandsSeparator: '', - mapToRadix: [MaskedNumber.UNMASKED_RADIX], - scale: 2, - signed: false, - normalizeZeros: true, - padFractionalZeros: false, - parse: Number, - format: n => n.toLocaleString('en-US', { - useGrouping: false, - maximumFractionDigits: 20 - }) - }; - MaskedNumber.EMPTY_VALUES = [...Masked.EMPTY_VALUES, 0]; - IMask.MaskedNumber = MaskedNumber; - - class MaskedFunction extends Masked { - _update(opts) { - if (opts.mask) opts.validate = opts.mask; - super._update(opts); - } - } - IMask.MaskedFunction = MaskedFunction; - - const _excluded = ["compiledMasks", "currentMaskRef", "currentMask"], - _excluded2 = ["mask"]; - class MaskedDynamic extends Masked { - constructor(opts) { - super(Object.assign({}, MaskedDynamic.DEFAULTS, opts)); - this.currentMask = null; - } - _update(opts) { - super._update(opts); - if ('mask' in opts) { - this.compiledMasks = Array.isArray(opts.mask) ? opts.mask.map(m => createMask(m)) : []; - } - } - _appendCharRaw(ch) { - let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - const details = this._applyDispatch(ch, flags); - if (this.currentMask) { - details.aggregate(this.currentMask._appendChar(ch, this.currentMaskFlags(flags))); - } - return details; - } - _applyDispatch() { - let appended = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; - let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - let tail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; - const prevValueBeforeTail = flags.tail && flags._beforeTailState != null ? flags._beforeTailState._value : this.value; - const inputValue = this.rawInputValue; - const insertValue = flags.tail && flags._beforeTailState != null ? - flags._beforeTailState._rawInputValue : inputValue; - const tailValue = inputValue.slice(insertValue.length); - const prevMask = this.currentMask; - const details = new ChangeDetails(); - const prevMaskState = prevMask === null || prevMask === void 0 ? void 0 : prevMask.state; - this.currentMask = this.doDispatch(appended, Object.assign({}, flags), tail); - if (this.currentMask) { - if (this.currentMask !== prevMask) { - this.currentMask.reset(); - if (insertValue) { - const d = this.currentMask.append(insertValue, { - raw: true - }); - details.tailShift = d.inserted.length - prevValueBeforeTail.length; - } - if (tailValue) { - details.tailShift += this.currentMask.append(tailValue, { - raw: true, - tail: true - }).tailShift; - } - } else { - this.currentMask.state = prevMaskState; - } - } - return details; - } - _appendPlaceholder() { - const details = this._applyDispatch(...arguments); - if (this.currentMask) { - details.aggregate(this.currentMask._appendPlaceholder()); - } - return details; - } - _appendEager() { - const details = this._applyDispatch(...arguments); - if (this.currentMask) { - details.aggregate(this.currentMask._appendEager()); - } - return details; - } - appendTail(tail) { - const details = new ChangeDetails(); - if (tail) details.aggregate(this._applyDispatch('', {}, tail)); - return details.aggregate(this.currentMask ? this.currentMask.appendTail(tail) : super.appendTail(tail)); - } - currentMaskFlags(flags) { - var _flags$_beforeTailSta, _flags$_beforeTailSta2; - return Object.assign({}, flags, { - _beforeTailState: ((_flags$_beforeTailSta = flags._beforeTailState) === null || _flags$_beforeTailSta === void 0 ? void 0 : _flags$_beforeTailSta.currentMaskRef) === this.currentMask && ((_flags$_beforeTailSta2 = flags._beforeTailState) === null || _flags$_beforeTailSta2 === void 0 ? void 0 : _flags$_beforeTailSta2.currentMask) || flags._beforeTailState - }); - } - doDispatch(appended) { - let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - let tail = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; - return this.dispatch(appended, this, flags, tail); - } - doValidate(flags) { - return super.doValidate(flags) && (!this.currentMask || this.currentMask.doValidate(this.currentMaskFlags(flags))); - } - doPrepare(str) { - let flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - let [s, details] = normalizePrepare(super.doPrepare(str, flags)); - if (this.currentMask) { - let currentDetails; - [s, currentDetails] = normalizePrepare(super.doPrepare(s, this.currentMaskFlags(flags))); - details = details.aggregate(currentDetails); - } - return [s, details]; - } - reset() { - var _this$currentMask; - (_this$currentMask = this.currentMask) === null || _this$currentMask === void 0 ? void 0 : _this$currentMask.reset(); - this.compiledMasks.forEach(m => m.reset()); - } - get value() { - return this.currentMask ? this.currentMask.value : ''; - } - set value(value) { - super.value = value; - } - get unmaskedValue() { - return this.currentMask ? this.currentMask.unmaskedValue : ''; - } - set unmaskedValue(unmaskedValue) { - super.unmaskedValue = unmaskedValue; - } - get typedValue() { - return this.currentMask ? this.currentMask.typedValue : ''; - } - set typedValue(value) { - let unmaskedValue = String(value); - if (this.currentMask) { - this.currentMask.typedValue = value; - unmaskedValue = this.currentMask.unmaskedValue; - } - this.unmaskedValue = unmaskedValue; - } - get displayValue() { - return this.currentMask ? this.currentMask.displayValue : ''; - } - get isComplete() { - var _this$currentMask2; - return Boolean((_this$currentMask2 = this.currentMask) === null || _this$currentMask2 === void 0 ? void 0 : _this$currentMask2.isComplete); - } - get isFilled() { - var _this$currentMask3; - return Boolean((_this$currentMask3 = this.currentMask) === null || _this$currentMask3 === void 0 ? void 0 : _this$currentMask3.isFilled); - } - remove() { - const details = new ChangeDetails(); - if (this.currentMask) { - details.aggregate(this.currentMask.remove(...arguments)) - .aggregate(this._applyDispatch()); - } - return details; - } - get state() { - var _this$currentMask4; - return Object.assign({}, super.state, { - _rawInputValue: this.rawInputValue, - compiledMasks: this.compiledMasks.map(m => m.state), - currentMaskRef: this.currentMask, - currentMask: (_this$currentMask4 = this.currentMask) === null || _this$currentMask4 === void 0 ? void 0 : _this$currentMask4.state - }); - } - set state(state) { - const { - compiledMasks, - currentMaskRef, - currentMask - } = state, - maskedState = _objectWithoutPropertiesLoose(state, _excluded); - this.compiledMasks.forEach((m, mi) => m.state = compiledMasks[mi]); - if (currentMaskRef != null) { - this.currentMask = currentMaskRef; - this.currentMask.state = currentMask; - } - super.state = maskedState; - } - extractInput() { - return this.currentMask ? this.currentMask.extractInput(...arguments) : ''; - } - extractTail() { - return this.currentMask ? this.currentMask.extractTail(...arguments) : super.extractTail(...arguments); - } - doCommit() { - if (this.currentMask) this.currentMask.doCommit(); - super.doCommit(); - } - nearestInputPos() { - return this.currentMask ? this.currentMask.nearestInputPos(...arguments) : super.nearestInputPos(...arguments); - } - get overwrite() { - return this.currentMask ? this.currentMask.overwrite : super.overwrite; - } - set overwrite(overwrite) { - console.warn('"overwrite" option is not available in dynamic mask, use this option in siblings'); - } - get eager() { - return this.currentMask ? this.currentMask.eager : super.eager; - } - set eager(eager) { - console.warn('"eager" option is not available in dynamic mask, use this option in siblings'); - } - get skipInvalid() { - return this.currentMask ? this.currentMask.skipInvalid : super.skipInvalid; - } - set skipInvalid(skipInvalid) { - if (this.isInitialized || skipInvalid !== Masked.DEFAULTS.skipInvalid) { - console.warn('"skipInvalid" option is not available in dynamic mask, use this option in siblings'); - } - } - maskEquals(mask) { - return Array.isArray(mask) && this.compiledMasks.every((m, mi) => { - if (!mask[mi]) return; - const _mask$mi = mask[mi], - { - mask: oldMask - } = _mask$mi, - restOpts = _objectWithoutPropertiesLoose(_mask$mi, _excluded2); - return objectIncludes(m, restOpts) && m.maskEquals(oldMask); - }); - } - typedValueEquals(value) { - var _this$currentMask5; - return Boolean((_this$currentMask5 = this.currentMask) === null || _this$currentMask5 === void 0 ? void 0 : _this$currentMask5.typedValueEquals(value)); - } - } - MaskedDynamic.DEFAULTS = { - dispatch: (appended, masked, flags, tail) => { - if (!masked.compiledMasks.length) return; - const inputValue = masked.rawInputValue; - const inputs = masked.compiledMasks.map((m, index) => { - const isCurrent = masked.currentMask === m; - const startInputPos = isCurrent ? m.value.length : m.nearestInputPos(m.value.length, DIRECTION.FORCE_LEFT); - if (m.rawInputValue !== inputValue) { - m.reset(); - m.append(inputValue, { - raw: true - }); - } else if (!isCurrent) { - m.remove(startInputPos); - } - m.append(appended, masked.currentMaskFlags(flags)); - m.appendTail(tail); - return { - index, - weight: m.rawInputValue.length, - totalInputPositions: m.totalInputPositions(0, Math.max(startInputPos, m.nearestInputPos(m.value.length, DIRECTION.FORCE_LEFT))) - }; - }); - inputs.sort((i1, i2) => i2.weight - i1.weight || i2.totalInputPositions - i1.totalInputPositions); - return masked.compiledMasks[inputs[0].index]; - } - }; - IMask.MaskedDynamic = MaskedDynamic; - - const PIPE_TYPE = { - MASKED: 'value', - UNMASKED: 'unmaskedValue', - TYPED: 'typedValue' - }; - function createPipe(mask) { - let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : PIPE_TYPE.MASKED; - let to = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : PIPE_TYPE.MASKED; - const masked = createMask(mask); - return value => masked.runIsolated(m => { - m[from] = value; - return m[to]; - }); - } - function pipe(value) { - for (var _len = arguments.length, pipeArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - pipeArgs[_key - 1] = arguments[_key]; - } - return createPipe(...pipeArgs)(value); - } - IMask.PIPE_TYPE = PIPE_TYPE; - IMask.createPipe = createPipe; - IMask.pipe = pipe; - - try { - globalThis.IMask = IMask; - } catch (e) { } - - var maskElementList = [].slice.call(document.querySelectorAll('[data-mask]')); - maskElementList.map(function (maskEl) { - return new IMask(maskEl, { - mask: maskEl.dataset.mask, - lazy: maskEl.dataset['mask-visible'] === 'true' - }); - }); - - var top = 'top'; - var bottom = 'bottom'; - var right = 'right'; - var left = 'left'; - var auto = 'auto'; - var basePlacements = [top, bottom, right, left]; - var start = 'start'; - var end = 'end'; - var clippingParents = 'clippingParents'; - var viewport = 'viewport'; - var popper = 'popper'; - var reference = 'reference'; - var variationPlacements = basePlacements.reduce(function (acc, placement) { - return acc.concat([placement + "-" + start, placement + "-" + end]); - }, []); - var placements = [].concat(basePlacements, [auto]).reduce(function (acc, placement) { - return acc.concat([placement, placement + "-" + start, placement + "-" + end]); - }, []); - var beforeRead = 'beforeRead'; - var read = 'read'; - var afterRead = 'afterRead'; - var beforeMain = 'beforeMain'; - var main = 'main'; - var afterMain = 'afterMain'; - var beforeWrite = 'beforeWrite'; - var write = 'write'; - var afterWrite = 'afterWrite'; - var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite]; - - function getNodeName(element) { - return element ? (element.nodeName || '').toLowerCase() : null; - } - - function getWindow(node) { - if (node == null) { - return window; - } - if (node.toString() !== '[object Window]') { - var ownerDocument = node.ownerDocument; - return ownerDocument ? ownerDocument.defaultView || window : window; - } - return node; - } - - function isElement$1(node) { - var OwnElement = getWindow(node).Element; - return node instanceof OwnElement || node instanceof Element; - } - function isHTMLElement(node) { - var OwnElement = getWindow(node).HTMLElement; - return node instanceof OwnElement || node instanceof HTMLElement; - } - function isShadowRoot(node) { - if (typeof ShadowRoot === 'undefined') { - return false; - } - var OwnElement = getWindow(node).ShadowRoot; - return node instanceof OwnElement || node instanceof ShadowRoot; - } - - function applyStyles(_ref) { - var state = _ref.state; - Object.keys(state.elements).forEach(function (name) { - var style = state.styles[name] || {}; - var attributes = state.attributes[name] || {}; - var element = state.elements[name]; - if (!isHTMLElement(element) || !getNodeName(element)) { - return; - } - Object.assign(element.style, style); - Object.keys(attributes).forEach(function (name) { - var value = attributes[name]; - if (value === false) { - element.removeAttribute(name); - } else { - element.setAttribute(name, value === true ? '' : value); - } - }); - }); - } - function effect$2(_ref2) { - var state = _ref2.state; - var initialStyles = { - popper: { - position: state.options.strategy, - left: '0', - top: '0', - margin: '0' - }, - arrow: { - position: 'absolute' - }, - reference: {} - }; - Object.assign(state.elements.popper.style, initialStyles.popper); - state.styles = initialStyles; - if (state.elements.arrow) { - Object.assign(state.elements.arrow.style, initialStyles.arrow); - } - return function () { - Object.keys(state.elements).forEach(function (name) { - var element = state.elements[name]; - var attributes = state.attributes[name] || {}; - var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); - var style = styleProperties.reduce(function (style, property) { - style[property] = ''; - return style; - }, {}); - if (!isHTMLElement(element) || !getNodeName(element)) { - return; - } - Object.assign(element.style, style); - Object.keys(attributes).forEach(function (attribute) { - element.removeAttribute(attribute); - }); - }); - }; - } - var applyStyles$1 = { - name: 'applyStyles', - enabled: true, - phase: 'write', - fn: applyStyles, - effect: effect$2, - requires: ['computeStyles'] - }; - - function getBasePlacement(placement) { - return placement.split('-')[0]; - } - - var max = Math.max; - var min = Math.min; - var round = Math.round; - - function getUAString() { - var uaData = navigator.userAgentData; - if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) { - return uaData.brands.map(function (item) { - return item.brand + "/" + item.version; - }).join(' '); - } - return navigator.userAgent; - } - - function isLayoutViewport() { - return !/^((?!chrome|android).)*safari/i.test(getUAString()); - } - - function getBoundingClientRect(element, includeScale, isFixedStrategy) { - if (includeScale === void 0) { - includeScale = false; - } - if (isFixedStrategy === void 0) { - isFixedStrategy = false; - } - var clientRect = element.getBoundingClientRect(); - var scaleX = 1; - var scaleY = 1; - if (includeScale && isHTMLElement(element)) { - scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1; - scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1; - } - var _ref = isElement$1(element) ? getWindow(element) : window, - visualViewport = _ref.visualViewport; - var addVisualOffsets = !isLayoutViewport() && isFixedStrategy; - var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX; - var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY; - var width = clientRect.width / scaleX; - var height = clientRect.height / scaleY; - return { - width: width, - height: height, - top: y, - right: x + width, - bottom: y + height, - left: x, - x: x, - y: y - }; - } - - function getLayoutRect(element) { - var clientRect = getBoundingClientRect(element); - var width = element.offsetWidth; - var height = element.offsetHeight; - if (Math.abs(clientRect.width - width) <= 1) { - width = clientRect.width; - } - if (Math.abs(clientRect.height - height) <= 1) { - height = clientRect.height; - } - return { - x: element.offsetLeft, - y: element.offsetTop, - width: width, - height: height - }; - } - - function contains(parent, child) { - var rootNode = child.getRootNode && child.getRootNode(); - if (parent.contains(child)) { - return true; - } - else if (rootNode && isShadowRoot(rootNode)) { - var next = child; - do { - if (next && parent.isSameNode(next)) { - return true; - } - next = next.parentNode || next.host; - } while (next); - } - return false; - } - - function getComputedStyle$1(element) { - return getWindow(element).getComputedStyle(element); - } - - function isTableElement(element) { - return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0; - } - - function getDocumentElement(element) { - return ((isElement$1(element) ? element.ownerDocument : - element.document) || window.document).documentElement; - } - - function getParentNode(element) { - if (getNodeName(element) === 'html') { - return element; - } - return ( - element.assignedSlot || - element.parentNode || ( - isShadowRoot(element) ? element.host : null) || - getDocumentElement(element) - ); - } - - function getTrueOffsetParent(element) { - if (!isHTMLElement(element) || - getComputedStyle$1(element).position === 'fixed') { - return null; - } - return element.offsetParent; - } - function getContainingBlock(element) { - var isFirefox = /firefox/i.test(getUAString()); - var isIE = /Trident/i.test(getUAString()); - if (isIE && isHTMLElement(element)) { - var elementCss = getComputedStyle$1(element); - if (elementCss.position === 'fixed') { - return null; - } - } - var currentNode = getParentNode(element); - if (isShadowRoot(currentNode)) { - currentNode = currentNode.host; - } - while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) { - var css = getComputedStyle$1(currentNode); - if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') { - return currentNode; - } else { - currentNode = currentNode.parentNode; - } - } - return null; - } - function getOffsetParent(element) { - var window = getWindow(element); - var offsetParent = getTrueOffsetParent(element); - while (offsetParent && isTableElement(offsetParent) && getComputedStyle$1(offsetParent).position === 'static') { - offsetParent = getTrueOffsetParent(offsetParent); - } - if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle$1(offsetParent).position === 'static')) { - return window; - } - return offsetParent || getContainingBlock(element) || window; - } - - function getMainAxisFromPlacement(placement) { - return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y'; - } - - function within(min$1, value, max$1) { - return max(min$1, min(value, max$1)); - } - function withinMaxClamp(min, value, max) { - var v = within(min, value, max); - return v > max ? max : v; - } - - function getFreshSideObject() { - return { - top: 0, - right: 0, - bottom: 0, - left: 0 - }; - } - - function mergePaddingObject(paddingObject) { - return Object.assign({}, getFreshSideObject(), paddingObject); - } - - function expandToHashMap(value, keys) { - return keys.reduce(function (hashMap, key) { - hashMap[key] = value; - return hashMap; - }, {}); - } - - var toPaddingObject = function toPaddingObject(padding, state) { - padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, { - placement: state.placement - })) : padding; - return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements)); - }; - function arrow(_ref) { - var _state$modifiersData$; - var state = _ref.state, - name = _ref.name, - options = _ref.options; - var arrowElement = state.elements.arrow; - var popperOffsets = state.modifiersData.popperOffsets; - var basePlacement = getBasePlacement(state.placement); - var axis = getMainAxisFromPlacement(basePlacement); - var isVertical = [left, right].indexOf(basePlacement) >= 0; - var len = isVertical ? 'height' : 'width'; - if (!arrowElement || !popperOffsets) { - return; - } - var paddingObject = toPaddingObject(options.padding, state); - var arrowRect = getLayoutRect(arrowElement); - var minProp = axis === 'y' ? top : left; - var maxProp = axis === 'y' ? bottom : right; - var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len]; - var startDiff = popperOffsets[axis] - state.rects.reference[axis]; - var arrowOffsetParent = getOffsetParent(arrowElement); - var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0; - var centerToReference = endDiff / 2 - startDiff / 2; - var min = paddingObject[minProp]; - var max = clientSize - arrowRect[len] - paddingObject[maxProp]; - var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference; - var offset = within(min, center, max); - var axisProp = axis; - state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$); - } - function effect$1(_ref2) { - var state = _ref2.state, - options = _ref2.options; - var _options$element = options.element, - arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element; - if (arrowElement == null) { - return; - } - if (typeof arrowElement === 'string') { - arrowElement = state.elements.popper.querySelector(arrowElement); - if (!arrowElement) { - return; - } - } - if (!contains(state.elements.popper, arrowElement)) { - return; - } - state.elements.arrow = arrowElement; - } - var arrow$1 = { - name: 'arrow', - enabled: true, - phase: 'main', - fn: arrow, - effect: effect$1, - requires: ['popperOffsets'], - requiresIfExists: ['preventOverflow'] - }; - - function getVariation(placement) { - return placement.split('-')[1]; - } - - var unsetSides = { - top: 'auto', - right: 'auto', - bottom: 'auto', - left: 'auto' - }; - function roundOffsetsByDPR(_ref, win) { - var x = _ref.x, - y = _ref.y; - var dpr = win.devicePixelRatio || 1; - return { - x: round(x * dpr) / dpr || 0, - y: round(y * dpr) / dpr || 0 - }; - } - function mapToStyles(_ref2) { - var _Object$assign2; - var popper = _ref2.popper, - popperRect = _ref2.popperRect, - placement = _ref2.placement, - variation = _ref2.variation, - offsets = _ref2.offsets, - position = _ref2.position, - gpuAcceleration = _ref2.gpuAcceleration, - adaptive = _ref2.adaptive, - roundOffsets = _ref2.roundOffsets, - isFixed = _ref2.isFixed; - var _offsets$x = offsets.x, - x = _offsets$x === void 0 ? 0 : _offsets$x, - _offsets$y = offsets.y, - y = _offsets$y === void 0 ? 0 : _offsets$y; - var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({ - x: x, - y: y - }) : { - x: x, - y: y - }; - x = _ref3.x; - y = _ref3.y; - var hasX = offsets.hasOwnProperty('x'); - var hasY = offsets.hasOwnProperty('y'); - var sideX = left; - var sideY = top; - var win = window; - if (adaptive) { - var offsetParent = getOffsetParent(popper); - var heightProp = 'clientHeight'; - var widthProp = 'clientWidth'; - if (offsetParent === getWindow(popper)) { - offsetParent = getDocumentElement(popper); - if (getComputedStyle$1(offsetParent).position !== 'static' && position === 'absolute') { - heightProp = 'scrollHeight'; - widthProp = 'scrollWidth'; - } - } - offsetParent = offsetParent; - if (placement === top || (placement === left || placement === right) && variation === end) { - sideY = bottom; - var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : - offsetParent[heightProp]; - y -= offsetY - popperRect.height; - y *= gpuAcceleration ? 1 : -1; - } - if (placement === left || (placement === top || placement === bottom) && variation === end) { - sideX = right; - var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : - offsetParent[widthProp]; - x -= offsetX - popperRect.width; - x *= gpuAcceleration ? 1 : -1; - } - } - var commonStyles = Object.assign({ - position: position - }, adaptive && unsetSides); - var _ref4 = roundOffsets === true ? roundOffsetsByDPR({ - x: x, - y: y - }, getWindow(popper)) : { - x: x, - y: y - }; - x = _ref4.x; - y = _ref4.y; - if (gpuAcceleration) { - var _Object$assign; - return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign)); - } - return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2)); - } - function computeStyles(_ref5) { - var state = _ref5.state, - options = _ref5.options; - var _options$gpuAccelerat = options.gpuAcceleration, - gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, - _options$adaptive = options.adaptive, - adaptive = _options$adaptive === void 0 ? true : _options$adaptive, - _options$roundOffsets = options.roundOffsets, - roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets; - var commonStyles = { - placement: getBasePlacement(state.placement), - variation: getVariation(state.placement), - popper: state.elements.popper, - popperRect: state.rects.popper, - gpuAcceleration: gpuAcceleration, - isFixed: state.options.strategy === 'fixed' - }; - if (state.modifiersData.popperOffsets != null) { - state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, { - offsets: state.modifiersData.popperOffsets, - position: state.options.strategy, - adaptive: adaptive, - roundOffsets: roundOffsets - }))); - } - if (state.modifiersData.arrow != null) { - state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, { - offsets: state.modifiersData.arrow, - position: 'absolute', - adaptive: false, - roundOffsets: roundOffsets - }))); - } - state.attributes.popper = Object.assign({}, state.attributes.popper, { - 'data-popper-placement': state.placement - }); - } - var computeStyles$1 = { - name: 'computeStyles', - enabled: true, - phase: 'beforeWrite', - fn: computeStyles, - data: {} - }; - - var passive = { - passive: true - }; - function effect(_ref) { - var state = _ref.state, - instance = _ref.instance, - options = _ref.options; - var _options$scroll = options.scroll, - scroll = _options$scroll === void 0 ? true : _options$scroll, - _options$resize = options.resize, - resize = _options$resize === void 0 ? true : _options$resize; - var window = getWindow(state.elements.popper); - var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper); - if (scroll) { - scrollParents.forEach(function (scrollParent) { - scrollParent.addEventListener('scroll', instance.update, passive); - }); - } - if (resize) { - window.addEventListener('resize', instance.update, passive); - } - return function () { - if (scroll) { - scrollParents.forEach(function (scrollParent) { - scrollParent.removeEventListener('scroll', instance.update, passive); - }); - } - if (resize) { - window.removeEventListener('resize', instance.update, passive); - } - }; - } - var eventListeners = { - name: 'eventListeners', - enabled: true, - phase: 'write', - fn: function fn() { }, - effect: effect, - data: {} - }; - - var hash$1 = { - left: 'right', - right: 'left', - bottom: 'top', - top: 'bottom' - }; - function getOppositePlacement(placement) { - return placement.replace(/left|right|bottom|top/g, function (matched) { - return hash$1[matched]; - }); - } - - var hash = { - start: 'end', - end: 'start' - }; - function getOppositeVariationPlacement(placement) { - return placement.replace(/start|end/g, function (matched) { - return hash[matched]; - }); - } - - function getWindowScroll(node) { - var win = getWindow(node); - var scrollLeft = win.pageXOffset; - var scrollTop = win.pageYOffset; - return { - scrollLeft: scrollLeft, - scrollTop: scrollTop - }; - } - - function getWindowScrollBarX(element) { - return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft; - } - - function getViewportRect(element, strategy) { - var win = getWindow(element); - var html = getDocumentElement(element); - var visualViewport = win.visualViewport; - var width = html.clientWidth; - var height = html.clientHeight; - var x = 0; - var y = 0; - if (visualViewport) { - width = visualViewport.width; - height = visualViewport.height; - var layoutViewport = isLayoutViewport(); - if (layoutViewport || !layoutViewport && strategy === 'fixed') { - x = visualViewport.offsetLeft; - y = visualViewport.offsetTop; - } - } - return { - width: width, - height: height, - x: x + getWindowScrollBarX(element), - y: y - }; - } - - function getDocumentRect(element) { - var _element$ownerDocumen; - var html = getDocumentElement(element); - var winScroll = getWindowScroll(element); - var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body; - var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0); - var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0); - var x = -winScroll.scrollLeft + getWindowScrollBarX(element); - var y = -winScroll.scrollTop; - if (getComputedStyle$1(body || html).direction === 'rtl') { - x += max(html.clientWidth, body ? body.clientWidth : 0) - width; - } - return { - width: width, - height: height, - x: x, - y: y - }; - } - - function isScrollParent(element) { - var _getComputedStyle = getComputedStyle$1(element), - overflow = _getComputedStyle.overflow, - overflowX = _getComputedStyle.overflowX, - overflowY = _getComputedStyle.overflowY; - return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX); - } - - function getScrollParent(node) { - if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) { - return node.ownerDocument.body; - } - if (isHTMLElement(node) && isScrollParent(node)) { - return node; - } - return getScrollParent(getParentNode(node)); - } - - function listScrollParents(element, list) { - var _element$ownerDocumen; - if (list === void 0) { - list = []; - } - var scrollParent = getScrollParent(element); - var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body); - var win = getWindow(scrollParent); - var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent; - var updatedList = list.concat(target); - return isBody ? updatedList : - updatedList.concat(listScrollParents(getParentNode(target))); - } - - function rectToClientRect(rect) { - return Object.assign({}, rect, { - left: rect.x, - top: rect.y, - right: rect.x + rect.width, - bottom: rect.y + rect.height - }); - } - - function getInnerBoundingClientRect(element, strategy) { - var rect = getBoundingClientRect(element, false, strategy === 'fixed'); - rect.top = rect.top + element.clientTop; - rect.left = rect.left + element.clientLeft; - rect.bottom = rect.top + element.clientHeight; - rect.right = rect.left + element.clientWidth; - rect.width = element.clientWidth; - rect.height = element.clientHeight; - rect.x = rect.left; - rect.y = rect.top; - return rect; - } - function getClientRectFromMixedType(element, clippingParent, strategy) { - return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement$1(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element))); - } - function getClippingParents(element) { - var clippingParents = listScrollParents(getParentNode(element)); - var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle$1(element).position) >= 0; - var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element; - if (!isElement$1(clipperElement)) { - return []; - } - return clippingParents.filter(function (clippingParent) { - return isElement$1(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body'; - }); - } - function getClippingRect(element, boundary, rootBoundary, strategy) { - var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary); - var clippingParents = [].concat(mainClippingParents, [rootBoundary]); - var firstClippingParent = clippingParents[0]; - var clippingRect = clippingParents.reduce(function (accRect, clippingParent) { - var rect = getClientRectFromMixedType(element, clippingParent, strategy); - accRect.top = max(rect.top, accRect.top); - accRect.right = min(rect.right, accRect.right); - accRect.bottom = min(rect.bottom, accRect.bottom); - accRect.left = max(rect.left, accRect.left); - return accRect; - }, getClientRectFromMixedType(element, firstClippingParent, strategy)); - clippingRect.width = clippingRect.right - clippingRect.left; - clippingRect.height = clippingRect.bottom - clippingRect.top; - clippingRect.x = clippingRect.left; - clippingRect.y = clippingRect.top; - return clippingRect; - } - - function computeOffsets(_ref) { - var reference = _ref.reference, - element = _ref.element, - placement = _ref.placement; - var basePlacement = placement ? getBasePlacement(placement) : null; - var variation = placement ? getVariation(placement) : null; - var commonX = reference.x + reference.width / 2 - element.width / 2; - var commonY = reference.y + reference.height / 2 - element.height / 2; - var offsets; - switch (basePlacement) { - case top: - offsets = { - x: commonX, - y: reference.y - element.height - }; - break; - case bottom: - offsets = { - x: commonX, - y: reference.y + reference.height - }; - break; - case right: - offsets = { - x: reference.x + reference.width, - y: commonY - }; - break; - case left: - offsets = { - x: reference.x - element.width, - y: commonY - }; - break; - default: - offsets = { - x: reference.x, - y: reference.y - }; - } - var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null; - if (mainAxis != null) { - var len = mainAxis === 'y' ? 'height' : 'width'; - switch (variation) { - case start: - offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2); - break; - case end: - offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2); - break; - } - } - return offsets; - } - - function detectOverflow(state, options) { - if (options === void 0) { - options = {}; - } - var _options = options, - _options$placement = _options.placement, - placement = _options$placement === void 0 ? state.placement : _options$placement, - _options$strategy = _options.strategy, - strategy = _options$strategy === void 0 ? state.strategy : _options$strategy, - _options$boundary = _options.boundary, - boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, - _options$rootBoundary = _options.rootBoundary, - rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, - _options$elementConte = _options.elementContext, - elementContext = _options$elementConte === void 0 ? popper : _options$elementConte, - _options$altBoundary = _options.altBoundary, - altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary, - _options$padding = _options.padding, - padding = _options$padding === void 0 ? 0 : _options$padding; - var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements)); - var altContext = elementContext === popper ? reference : popper; - var popperRect = state.rects.popper; - var element = state.elements[altBoundary ? altContext : elementContext]; - var clippingClientRect = getClippingRect(isElement$1(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy); - var referenceClientRect = getBoundingClientRect(state.elements.reference); - var popperOffsets = computeOffsets({ - reference: referenceClientRect, - element: popperRect, - strategy: 'absolute', - placement: placement - }); - var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets)); - var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; - var overflowOffsets = { - top: clippingClientRect.top - elementClientRect.top + paddingObject.top, - bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom, - left: clippingClientRect.left - elementClientRect.left + paddingObject.left, - right: elementClientRect.right - clippingClientRect.right + paddingObject.right - }; - var offsetData = state.modifiersData.offset; - if (elementContext === popper && offsetData) { - var offset = offsetData[placement]; - Object.keys(overflowOffsets).forEach(function (key) { - var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1; - var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x'; - overflowOffsets[key] += offset[axis] * multiply; - }); - } - return overflowOffsets; - } - - function computeAutoPlacement(state, options) { - if (options === void 0) { - options = {}; - } - var _options = options, - placement = _options.placement, - boundary = _options.boundary, - rootBoundary = _options.rootBoundary, - padding = _options.padding, - flipVariations = _options.flipVariations, - _options$allowedAutoP = _options.allowedAutoPlacements, - allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP; - var variation = getVariation(placement); - var placements$1 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) { - return getVariation(placement) === variation; - }) : basePlacements; - var allowedPlacements = placements$1.filter(function (placement) { - return allowedAutoPlacements.indexOf(placement) >= 0; - }); - if (allowedPlacements.length === 0) { - allowedPlacements = placements$1; - } - var overflows = allowedPlacements.reduce(function (acc, placement) { - acc[placement] = detectOverflow(state, { - placement: placement, - boundary: boundary, - rootBoundary: rootBoundary, - padding: padding - })[getBasePlacement(placement)]; - return acc; - }, {}); - return Object.keys(overflows).sort(function (a, b) { - return overflows[a] - overflows[b]; - }); - } - - function getExpandedFallbackPlacements(placement) { - if (getBasePlacement(placement) === auto) { - return []; - } - var oppositePlacement = getOppositePlacement(placement); - return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)]; - } - function flip(_ref) { - var state = _ref.state, - options = _ref.options, - name = _ref.name; - if (state.modifiersData[name]._skip) { - return; - } - var _options$mainAxis = options.mainAxis, - checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, - _options$altAxis = options.altAxis, - checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, - specifiedFallbackPlacements = options.fallbackPlacements, - padding = options.padding, - boundary = options.boundary, - rootBoundary = options.rootBoundary, - altBoundary = options.altBoundary, - _options$flipVariatio = options.flipVariations, - flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio, - allowedAutoPlacements = options.allowedAutoPlacements; - var preferredPlacement = state.options.placement; - var basePlacement = getBasePlacement(preferredPlacement); - var isBasePlacement = basePlacement === preferredPlacement; - var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement)); - var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) { - return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, { - placement: placement, - boundary: boundary, - rootBoundary: rootBoundary, - padding: padding, - flipVariations: flipVariations, - allowedAutoPlacements: allowedAutoPlacements - }) : placement); - }, []); - var referenceRect = state.rects.reference; - var popperRect = state.rects.popper; - var checksMap = new Map(); - var makeFallbackChecks = true; - var firstFittingPlacement = placements[0]; - for (var i = 0; i < placements.length; i++) { - var placement = placements[i]; - var _basePlacement = getBasePlacement(placement); - var isStartVariation = getVariation(placement) === start; - var isVertical = [top, bottom].indexOf(_basePlacement) >= 0; - var len = isVertical ? 'width' : 'height'; - var overflow = detectOverflow(state, { - placement: placement, - boundary: boundary, - rootBoundary: rootBoundary, - altBoundary: altBoundary, - padding: padding - }); - var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top; - if (referenceRect[len] > popperRect[len]) { - mainVariationSide = getOppositePlacement(mainVariationSide); - } - var altVariationSide = getOppositePlacement(mainVariationSide); - var checks = []; - if (checkMainAxis) { - checks.push(overflow[_basePlacement] <= 0); - } - if (checkAltAxis) { - checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0); - } - if (checks.every(function (check) { - return check; - })) { - firstFittingPlacement = placement; - makeFallbackChecks = false; - break; - } - checksMap.set(placement, checks); - } - if (makeFallbackChecks) { - var numberOfChecks = flipVariations ? 3 : 1; - var _loop = function _loop(_i) { - var fittingPlacement = placements.find(function (placement) { - var checks = checksMap.get(placement); - if (checks) { - return checks.slice(0, _i).every(function (check) { - return check; - }); - } - }); - if (fittingPlacement) { - firstFittingPlacement = fittingPlacement; - return "break"; - } - }; - for (var _i = numberOfChecks; _i > 0; _i--) { - var _ret = _loop(_i); - if (_ret === "break") break; - } - } - if (state.placement !== firstFittingPlacement) { - state.modifiersData[name]._skip = true; - state.placement = firstFittingPlacement; - state.reset = true; - } - } - var flip$1 = { - name: 'flip', - enabled: true, - phase: 'main', - fn: flip, - requiresIfExists: ['offset'], - data: { - _skip: false - } - }; - - function getSideOffsets(overflow, rect, preventedOffsets) { - if (preventedOffsets === void 0) { - preventedOffsets = { - x: 0, - y: 0 - }; - } - return { - top: overflow.top - rect.height - preventedOffsets.y, - right: overflow.right - rect.width + preventedOffsets.x, - bottom: overflow.bottom - rect.height + preventedOffsets.y, - left: overflow.left - rect.width - preventedOffsets.x - }; - } - function isAnySideFullyClipped(overflow) { - return [top, right, bottom, left].some(function (side) { - return overflow[side] >= 0; - }); - } - function hide(_ref) { - var state = _ref.state, - name = _ref.name; - var referenceRect = state.rects.reference; - var popperRect = state.rects.popper; - var preventedOffsets = state.modifiersData.preventOverflow; - var referenceOverflow = detectOverflow(state, { - elementContext: 'reference' - }); - var popperAltOverflow = detectOverflow(state, { - altBoundary: true - }); - var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect); - var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets); - var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets); - var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets); - state.modifiersData[name] = { - referenceClippingOffsets: referenceClippingOffsets, - popperEscapeOffsets: popperEscapeOffsets, - isReferenceHidden: isReferenceHidden, - hasPopperEscaped: hasPopperEscaped - }; - state.attributes.popper = Object.assign({}, state.attributes.popper, { - 'data-popper-reference-hidden': isReferenceHidden, - 'data-popper-escaped': hasPopperEscaped - }); - } - var hide$1 = { - name: 'hide', - enabled: true, - phase: 'main', - requiresIfExists: ['preventOverflow'], - fn: hide - }; - - function distanceAndSkiddingToXY(placement, rects, offset) { - var basePlacement = getBasePlacement(placement); - var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1; - var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, { - placement: placement - })) : offset, - skidding = _ref[0], - distance = _ref[1]; - skidding = skidding || 0; - distance = (distance || 0) * invertDistance; - return [left, right].indexOf(basePlacement) >= 0 ? { - x: distance, - y: skidding - } : { - x: skidding, - y: distance - }; - } - function offset(_ref2) { - var state = _ref2.state, - options = _ref2.options, - name = _ref2.name; - var _options$offset = options.offset, - offset = _options$offset === void 0 ? [0, 0] : _options$offset; - var data = placements.reduce(function (acc, placement) { - acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset); - return acc; - }, {}); - var _data$state$placement = data[state.placement], - x = _data$state$placement.x, - y = _data$state$placement.y; - if (state.modifiersData.popperOffsets != null) { - state.modifiersData.popperOffsets.x += x; - state.modifiersData.popperOffsets.y += y; - } - state.modifiersData[name] = data; - } - var offset$1 = { - name: 'offset', - enabled: true, - phase: 'main', - requires: ['popperOffsets'], - fn: offset - }; - - function popperOffsets(_ref) { - var state = _ref.state, - name = _ref.name; - state.modifiersData[name] = computeOffsets({ - reference: state.rects.reference, - element: state.rects.popper, - strategy: 'absolute', - placement: state.placement - }); - } - var popperOffsets$1 = { - name: 'popperOffsets', - enabled: true, - phase: 'read', - fn: popperOffsets, - data: {} - }; - - function getAltAxis(axis) { - return axis === 'x' ? 'y' : 'x'; - } - - function preventOverflow(_ref) { - var state = _ref.state, - options = _ref.options, - name = _ref.name; - var _options$mainAxis = options.mainAxis, - checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, - _options$altAxis = options.altAxis, - checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, - boundary = options.boundary, - rootBoundary = options.rootBoundary, - altBoundary = options.altBoundary, - padding = options.padding, - _options$tether = options.tether, - tether = _options$tether === void 0 ? true : _options$tether, - _options$tetherOffset = options.tetherOffset, - tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset; - var overflow = detectOverflow(state, { - boundary: boundary, - rootBoundary: rootBoundary, - padding: padding, - altBoundary: altBoundary - }); - var basePlacement = getBasePlacement(state.placement); - var variation = getVariation(state.placement); - var isBasePlacement = !variation; - var mainAxis = getMainAxisFromPlacement(basePlacement); - var altAxis = getAltAxis(mainAxis); - var popperOffsets = state.modifiersData.popperOffsets; - var referenceRect = state.rects.reference; - var popperRect = state.rects.popper; - var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, { - placement: state.placement - })) : tetherOffset; - var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? { - mainAxis: tetherOffsetValue, - altAxis: tetherOffsetValue - } : Object.assign({ - mainAxis: 0, - altAxis: 0 - }, tetherOffsetValue); - var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null; - var data = { - x: 0, - y: 0 - }; - if (!popperOffsets) { - return; - } - if (checkMainAxis) { - var _offsetModifierState$; - var mainSide = mainAxis === 'y' ? top : left; - var altSide = mainAxis === 'y' ? bottom : right; - var len = mainAxis === 'y' ? 'height' : 'width'; - var offset = popperOffsets[mainAxis]; - var min$1 = offset + overflow[mainSide]; - var max$1 = offset - overflow[altSide]; - var additive = tether ? -popperRect[len] / 2 : 0; - var minLen = variation === start ? referenceRect[len] : popperRect[len]; - var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; - var arrowElement = state.elements.arrow; - var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : { - width: 0, - height: 0 - }; - var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject(); - var arrowPaddingMin = arrowPaddingObject[mainSide]; - var arrowPaddingMax = arrowPaddingObject[altSide]; - var arrowLen = within(0, referenceRect[len], arrowRect[len]); - var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis; - var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis; - var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow); - var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0; - var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0; - var tetherMin = offset + minOffset - offsetModifierValue - clientOffset; - var tetherMax = offset + maxOffset - offsetModifierValue; - var preventedOffset = within(tether ? min(min$1, tetherMin) : min$1, offset, tether ? max(max$1, tetherMax) : max$1); - popperOffsets[mainAxis] = preventedOffset; - data[mainAxis] = preventedOffset - offset; - } - if (checkAltAxis) { - var _offsetModifierState$2; - var _mainSide = mainAxis === 'x' ? top : left; - var _altSide = mainAxis === 'x' ? bottom : right; - var _offset = popperOffsets[altAxis]; - var _len = altAxis === 'y' ? 'height' : 'width'; - var _min = _offset + overflow[_mainSide]; - var _max = _offset - overflow[_altSide]; - var isOriginSide = [top, left].indexOf(basePlacement) !== -1; - var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0; - var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis; - var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max; - var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max); - popperOffsets[altAxis] = _preventedOffset; - data[altAxis] = _preventedOffset - _offset; - } - state.modifiersData[name] = data; - } - var preventOverflow$1 = { - name: 'preventOverflow', - enabled: true, - phase: 'main', - fn: preventOverflow, - requiresIfExists: ['offset'] - }; - - function getHTMLElementScroll(element) { - return { - scrollLeft: element.scrollLeft, - scrollTop: element.scrollTop - }; - } - - function getNodeScroll(node) { - if (node === getWindow(node) || !isHTMLElement(node)) { - return getWindowScroll(node); - } else { - return getHTMLElementScroll(node); - } - } - - function isElementScaled(element) { - var rect = element.getBoundingClientRect(); - var scaleX = round(rect.width) / element.offsetWidth || 1; - var scaleY = round(rect.height) / element.offsetHeight || 1; - return scaleX !== 1 || scaleY !== 1; - } - function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) { - if (isFixed === void 0) { - isFixed = false; - } - var isOffsetParentAnElement = isHTMLElement(offsetParent); - var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent); - var documentElement = getDocumentElement(offsetParent); - var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed); - var scroll = { - scrollLeft: 0, - scrollTop: 0 - }; - var offsets = { - x: 0, - y: 0 - }; - if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { - if (getNodeName(offsetParent) !== 'body' || - isScrollParent(documentElement)) { - scroll = getNodeScroll(offsetParent); - } - if (isHTMLElement(offsetParent)) { - offsets = getBoundingClientRect(offsetParent, true); - offsets.x += offsetParent.clientLeft; - offsets.y += offsetParent.clientTop; - } else if (documentElement) { - offsets.x = getWindowScrollBarX(documentElement); - } - } - return { - x: rect.left + scroll.scrollLeft - offsets.x, - y: rect.top + scroll.scrollTop - offsets.y, - width: rect.width, - height: rect.height - }; - } - - function order(modifiers) { - var map = new Map(); - var visited = new Set(); - var result = []; - modifiers.forEach(function (modifier) { - map.set(modifier.name, modifier); - }); - function sort(modifier) { - visited.add(modifier.name); - var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []); - requires.forEach(function (dep) { - if (!visited.has(dep)) { - var depModifier = map.get(dep); - if (depModifier) { - sort(depModifier); - } - } - }); - result.push(modifier); - } - modifiers.forEach(function (modifier) { - if (!visited.has(modifier.name)) { - sort(modifier); - } - }); - return result; - } - function orderModifiers(modifiers) { - var orderedModifiers = order(modifiers); - return modifierPhases.reduce(function (acc, phase) { - return acc.concat(orderedModifiers.filter(function (modifier) { - return modifier.phase === phase; - })); - }, []); - } - - function debounce(fn) { - var pending; - return function () { - if (!pending) { - pending = new Promise(function (resolve) { - Promise.resolve().then(function () { - pending = undefined; - resolve(fn()); - }); - }); - } - return pending; - }; - } - - function mergeByName(modifiers) { - var merged = modifiers.reduce(function (merged, current) { - var existing = merged[current.name]; - merged[current.name] = existing ? Object.assign({}, existing, current, { - options: Object.assign({}, existing.options, current.options), - data: Object.assign({}, existing.data, current.data) - }) : current; - return merged; - }, {}); - return Object.keys(merged).map(function (key) { - return merged[key]; - }); - } - - var DEFAULT_OPTIONS = { - placement: 'bottom', - modifiers: [], - strategy: 'absolute' - }; - function areValidElements() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - return !args.some(function (element) { - return !(element && typeof element.getBoundingClientRect === 'function'); - }); - } - function popperGenerator(generatorOptions) { - if (generatorOptions === void 0) { - generatorOptions = {}; - } - var _generatorOptions = generatorOptions, - _generatorOptions$def = _generatorOptions.defaultModifiers, - defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, - _generatorOptions$def2 = _generatorOptions.defaultOptions, - defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2; - return function createPopper(reference, popper, options) { - if (options === void 0) { - options = defaultOptions; - } - var state = { - placement: 'bottom', - orderedModifiers: [], - options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions), - modifiersData: {}, - elements: { - reference: reference, - popper: popper - }, - attributes: {}, - styles: {} - }; - var effectCleanupFns = []; - var isDestroyed = false; - var instance = { - state: state, - setOptions: function setOptions(setOptionsAction) { - var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction; - cleanupModifierEffects(); - state.options = Object.assign({}, defaultOptions, state.options, options); - state.scrollParents = { - reference: isElement$1(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [], - popper: listScrollParents(popper) - }; - var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); - state.orderedModifiers = orderedModifiers.filter(function (m) { - return m.enabled; - }); - runModifierEffects(); - return instance.update(); - }, - forceUpdate: function forceUpdate() { - if (isDestroyed) { - return; - } - var _state$elements = state.elements, - reference = _state$elements.reference, - popper = _state$elements.popper; - if (!areValidElements(reference, popper)) { - return; - } - state.rects = { - reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'), - popper: getLayoutRect(popper) - }; - state.reset = false; - state.placement = state.options.placement; - state.orderedModifiers.forEach(function (modifier) { - return state.modifiersData[modifier.name] = Object.assign({}, modifier.data); - }); - for (var index = 0; index < state.orderedModifiers.length; index++) { - if (state.reset === true) { - state.reset = false; - index = -1; - continue; - } - var _state$orderedModifie = state.orderedModifiers[index], - fn = _state$orderedModifie.fn, - _state$orderedModifie2 = _state$orderedModifie.options, - _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, - name = _state$orderedModifie.name; - if (typeof fn === 'function') { - state = fn({ - state: state, - options: _options, - name: name, - instance: instance - }) || state; - } - } - }, - update: debounce(function () { - return new Promise(function (resolve) { - instance.forceUpdate(); - resolve(state); - }); - }), - destroy: function destroy() { - cleanupModifierEffects(); - isDestroyed = true; - } - }; - if (!areValidElements(reference, popper)) { - return instance; - } - instance.setOptions(options).then(function (state) { - if (!isDestroyed && options.onFirstUpdate) { - options.onFirstUpdate(state); - } - }); - function runModifierEffects() { - state.orderedModifiers.forEach(function (_ref) { - var name = _ref.name, - _ref$options = _ref.options, - options = _ref$options === void 0 ? {} : _ref$options, - effect = _ref.effect; - if (typeof effect === 'function') { - var cleanupFn = effect({ - state: state, - name: name, - instance: instance, - options: options - }); - var noopFn = function noopFn() { }; - effectCleanupFns.push(cleanupFn || noopFn); - } - }); - } - function cleanupModifierEffects() { - effectCleanupFns.forEach(function (fn) { - return fn(); - }); - effectCleanupFns = []; - } - return instance; - }; - } - var createPopper$2 = popperGenerator(); - - var defaultModifiers$1 = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1]; - var createPopper$1 = popperGenerator({ - defaultModifiers: defaultModifiers$1 - }); - - var defaultModifiers = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1, offset$1, flip$1, preventOverflow$1, arrow$1, hide$1]; - var createPopper = popperGenerator({ - defaultModifiers: defaultModifiers - }); - - var Popper = /*#__PURE__*/Object.freeze({ - __proto__: null, - popperGenerator: popperGenerator, - detectOverflow: detectOverflow, - createPopperBase: createPopper$2, - createPopper: createPopper, - createPopperLite: createPopper$1, - top: top, - bottom: bottom, - right: right, - left: left, - auto: auto, - basePlacements: basePlacements, - start: start, - end: end, - clippingParents: clippingParents, - viewport: viewport, - popper: popper, - reference: reference, - variationPlacements: variationPlacements, - placements: placements, - beforeRead: beforeRead, - read: read, - afterRead: afterRead, - beforeMain: beforeMain, - main: main, - afterMain: afterMain, - beforeWrite: beforeWrite, - write: write, - afterWrite: afterWrite, - modifierPhases: modifierPhases, - applyStyles: applyStyles$1, - arrow: arrow$1, - computeStyles: computeStyles$1, - eventListeners: eventListeners, - flip: flip$1, - hide: hide$1, - offset: offset$1, - popperOffsets: popperOffsets$1, - preventOverflow: preventOverflow$1 - }); - - /*! - * Bootstrap v5.3.1 (https://getbootstrap.com/) - * Copyright 2011-2023 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors) - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) - */ - const elementMap = new Map(); - const Data = { - set(element, key, instance) { - if (!elementMap.has(element)) { - elementMap.set(element, new Map()); - } - const instanceMap = elementMap.get(element); - if (!instanceMap.has(key) && instanceMap.size !== 0) { - console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(instanceMap.keys())[0]}.`); - return; - } - instanceMap.set(key, instance); - }, - get(element, key) { - if (elementMap.has(element)) { - return elementMap.get(element).get(key) || null; - } - return null; - }, - remove(element, key) { - if (!elementMap.has(element)) { - return; - } - const instanceMap = elementMap.get(element); - instanceMap.delete(key); - if (instanceMap.size === 0) { - elementMap.delete(element); - } - } - }; - const MAX_UID = 1000000; - const MILLISECONDS_MULTIPLIER = 1000; - const TRANSITION_END = 'transitionend'; - const parseSelector = selector => { - if (selector && window.CSS && window.CSS.escape) { - selector = selector.replace(/#([^\s"#']+)/g, (match, id) => `#${CSS.escape(id)}`); - } - return selector; - }; - const toType = object => { - if (object === null || object === undefined) { - return `${object}`; - } - return Object.prototype.toString.call(object).match(/\s([a-z]+)/i)[1].toLowerCase(); - }; - const getUID = prefix => { - do { - prefix += Math.floor(Math.random() * MAX_UID); - } while (document.getElementById(prefix)); - return prefix; - }; - const getTransitionDurationFromElement = element => { - if (!element) { - return 0; - } - let { - transitionDuration, - transitionDelay - } = window.getComputedStyle(element); - const floatTransitionDuration = Number.parseFloat(transitionDuration); - const floatTransitionDelay = Number.parseFloat(transitionDelay); - if (!floatTransitionDuration && !floatTransitionDelay) { - return 0; - } - transitionDuration = transitionDuration.split(',')[0]; - transitionDelay = transitionDelay.split(',')[0]; - return (Number.parseFloat(transitionDuration) + Number.parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER; - }; - const triggerTransitionEnd = element => { - element.dispatchEvent(new Event(TRANSITION_END)); - }; - const isElement = object => { - if (!object || typeof object !== 'object') { - return false; - } - if (typeof object.jquery !== 'undefined') { - object = object[0]; - } - return typeof object.nodeType !== 'undefined'; - }; - const getElement = object => { - if (isElement(object)) { - return object.jquery ? object[0] : object; - } - if (typeof object === 'string' && object.length > 0) { - return document.querySelector(parseSelector(object)); - } - return null; - }; - const isVisible = element => { - if (!isElement(element) || element.getClientRects().length === 0) { - return false; - } - const elementIsVisible = getComputedStyle(element).getPropertyValue('visibility') === 'visible'; - const closedDetails = element.closest('details:not([open])'); - if (!closedDetails) { - return elementIsVisible; - } - if (closedDetails !== element) { - const summary = element.closest('summary'); - if (summary && summary.parentNode !== closedDetails) { - return false; - } - if (summary === null) { - return false; - } - } - return elementIsVisible; - }; - const isDisabled = element => { - if (!element || element.nodeType !== Node.ELEMENT_NODE) { - return true; - } - if (element.classList.contains('disabled')) { - return true; - } - if (typeof element.disabled !== 'undefined') { - return element.disabled; - } - return element.hasAttribute('disabled') && element.getAttribute('disabled') !== 'false'; - }; - const findShadowRoot = element => { - if (!document.documentElement.attachShadow) { - return null; - } - if (typeof element.getRootNode === 'function') { - const root = element.getRootNode(); - return root instanceof ShadowRoot ? root : null; - } - if (element instanceof ShadowRoot) { - return element; - } - if (!element.parentNode) { - return null; - } - return findShadowRoot(element.parentNode); - }; - const noop = () => { }; - const reflow = element => { - element.offsetHeight; - }; - const getjQuery = () => { - if (window.jQuery && !document.body.hasAttribute('data-bs-no-jquery')) { - return window.jQuery; - } - return null; - }; - const DOMContentLoadedCallbacks = []; - const onDOMContentLoaded = callback => { - if (document.readyState === 'loading') { - if (!DOMContentLoadedCallbacks.length) { - document.addEventListener('DOMContentLoaded', () => { - for (const callback of DOMContentLoadedCallbacks) { - callback(); - } - }); - } - DOMContentLoadedCallbacks.push(callback); - } else { - callback(); - } - }; - const isRTL = () => document.documentElement.dir === 'rtl'; - const defineJQueryPlugin = plugin => { - onDOMContentLoaded(() => { - const $ = getjQuery(); - if ($) { - const name = plugin.NAME; - const JQUERY_NO_CONFLICT = $.fn[name]; - $.fn[name] = plugin.jQueryInterface; - $.fn[name].Constructor = plugin; - $.fn[name].noConflict = () => { - $.fn[name] = JQUERY_NO_CONFLICT; - return plugin.jQueryInterface; - }; - } - }); - }; - const execute = (possibleCallback, args = [], defaultValue = possibleCallback) => { - return typeof possibleCallback === 'function' ? possibleCallback(...args) : defaultValue; - }; - const executeAfterTransition = (callback, transitionElement, waitForTransition = true) => { - if (!waitForTransition) { - execute(callback); - return; - } - const durationPadding = 5; - const emulatedDuration = getTransitionDurationFromElement(transitionElement) + durationPadding; - let called = false; - const handler = ({ - target - }) => { - if (target !== transitionElement) { - return; - } - called = true; - transitionElement.removeEventListener(TRANSITION_END, handler); - execute(callback); - }; - transitionElement.addEventListener(TRANSITION_END, handler); - setTimeout(() => { - if (!called) { - triggerTransitionEnd(transitionElement); - } - }, emulatedDuration); - }; - const getNextActiveElement = (list, activeElement, shouldGetNext, isCycleAllowed) => { - const listLength = list.length; - let index = list.indexOf(activeElement); - if (index === -1) { - return !shouldGetNext && isCycleAllowed ? list[listLength - 1] : list[0]; - } - index += shouldGetNext ? 1 : -1; - if (isCycleAllowed) { - index = (index + listLength) % listLength; - } - return list[Math.max(0, Math.min(index, listLength - 1))]; - }; - const namespaceRegex = /[^.]*(?=\..*)\.|.*/; - const stripNameRegex = /\..*/; - const stripUidRegex = /::\d+$/; - const eventRegistry = {}; - let uidEvent = 1; - const customEvents = { - mouseenter: 'mouseover', - mouseleave: 'mouseout' - }; - const nativeEvents = new Set(['click', 'dblclick', 'mouseup', 'mousedown', 'contextmenu', 'mousewheel', 'DOMMouseScroll', 'mouseover', 'mouseout', 'mousemove', 'selectstart', 'selectend', 'keydown', 'keypress', 'keyup', 'orientationchange', 'touchstart', 'touchmove', 'touchend', 'touchcancel', 'pointerdown', 'pointermove', 'pointerup', 'pointerleave', 'pointercancel', 'gesturestart', 'gesturechange', 'gestureend', 'focus', 'blur', 'change', 'reset', 'select', 'submit', 'focusin', 'focusout', 'load', 'unload', 'beforeunload', 'resize', 'move', 'DOMContentLoaded', 'readystatechange', 'error', 'abort', 'scroll']); - function makeEventUid(element, uid) { - return uid && `${uid}::${uidEvent++}` || element.uidEvent || uidEvent++; - } - function getElementEvents(element) { - const uid = makeEventUid(element); - element.uidEvent = uid; - eventRegistry[uid] = eventRegistry[uid] || {}; - return eventRegistry[uid]; - } - function bootstrapHandler(element, fn) { - return function handler(event) { - hydrateObj(event, { - delegateTarget: element - }); - if (handler.oneOff) { - EventHandler.off(element, event.type, fn); - } - return fn.apply(element, [event]); - }; - } - function bootstrapDelegationHandler(element, selector, fn) { - return function handler(event) { - const domElements = element.querySelectorAll(selector); - for (let { - target - } = event; target && target !== this; target = target.parentNode) { - for (const domElement of domElements) { - if (domElement !== target) { - continue; - } - hydrateObj(event, { - delegateTarget: target - }); - if (handler.oneOff) { - EventHandler.off(element, event.type, selector, fn); - } - return fn.apply(target, [event]); - } - } - }; - } - function findHandler(events, callable, delegationSelector = null) { - return Object.values(events).find(event => event.callable === callable && event.delegationSelector === delegationSelector); - } - function normalizeParameters(originalTypeEvent, handler, delegationFunction) { - const isDelegated = typeof handler === 'string'; - const callable = isDelegated ? delegationFunction : handler || delegationFunction; - let typeEvent = getTypeEvent(originalTypeEvent); - if (!nativeEvents.has(typeEvent)) { - typeEvent = originalTypeEvent; - } - return [isDelegated, callable, typeEvent]; - } - function addHandler(element, originalTypeEvent, handler, delegationFunction, oneOff) { - if (typeof originalTypeEvent !== 'string' || !element) { - return; - } - let [isDelegated, callable, typeEvent] = normalizeParameters(originalTypeEvent, handler, delegationFunction); - if (originalTypeEvent in customEvents) { - const wrapFunction = fn => { - return function (event) { - if (!event.relatedTarget || event.relatedTarget !== event.delegateTarget && !event.delegateTarget.contains(event.relatedTarget)) { - return fn.call(this, event); - } - }; - }; - callable = wrapFunction(callable); - } - const events = getElementEvents(element); - const handlers = events[typeEvent] || (events[typeEvent] = {}); - const previousFunction = findHandler(handlers, callable, isDelegated ? handler : null); - if (previousFunction) { - previousFunction.oneOff = previousFunction.oneOff && oneOff; - return; - } - const uid = makeEventUid(callable, originalTypeEvent.replace(namespaceRegex, '')); - const fn = isDelegated ? bootstrapDelegationHandler(element, handler, callable) : bootstrapHandler(element, callable); - fn.delegationSelector = isDelegated ? handler : null; - fn.callable = callable; - fn.oneOff = oneOff; - fn.uidEvent = uid; - handlers[uid] = fn; - element.addEventListener(typeEvent, fn, isDelegated); - } - function removeHandler(element, events, typeEvent, handler, delegationSelector) { - const fn = findHandler(events[typeEvent], handler, delegationSelector); - if (!fn) { - return; - } - element.removeEventListener(typeEvent, fn, Boolean(delegationSelector)); - delete events[typeEvent][fn.uidEvent]; - } - function removeNamespacedHandlers(element, events, typeEvent, namespace) { - const storeElementEvent = events[typeEvent] || {}; - for (const [handlerKey, event] of Object.entries(storeElementEvent)) { - if (handlerKey.includes(namespace)) { - removeHandler(element, events, typeEvent, event.callable, event.delegationSelector); - } - } - } - function getTypeEvent(event) { - event = event.replace(stripNameRegex, ''); - return customEvents[event] || event; - } - const EventHandler = { - on(element, event, handler, delegationFunction) { - addHandler(element, event, handler, delegationFunction, false); - }, - one(element, event, handler, delegationFunction) { - addHandler(element, event, handler, delegationFunction, true); - }, - off(element, originalTypeEvent, handler, delegationFunction) { - if (typeof originalTypeEvent !== 'string' || !element) { - return; - } - const [isDelegated, callable, typeEvent] = normalizeParameters(originalTypeEvent, handler, delegationFunction); - const inNamespace = typeEvent !== originalTypeEvent; - const events = getElementEvents(element); - const storeElementEvent = events[typeEvent] || {}; - const isNamespace = originalTypeEvent.startsWith('.'); - if (typeof callable !== 'undefined') { - if (!Object.keys(storeElementEvent).length) { - return; - } - removeHandler(element, events, typeEvent, callable, isDelegated ? handler : null); - return; - } - if (isNamespace) { - for (const elementEvent of Object.keys(events)) { - removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.slice(1)); - } - } - for (const [keyHandlers, event] of Object.entries(storeElementEvent)) { - const handlerKey = keyHandlers.replace(stripUidRegex, ''); - if (!inNamespace || originalTypeEvent.includes(handlerKey)) { - removeHandler(element, events, typeEvent, event.callable, event.delegationSelector); - } - } - }, - trigger(element, event, args) { - if (typeof event !== 'string' || !element) { - return null; - } - const $ = getjQuery(); - const typeEvent = getTypeEvent(event); - const inNamespace = event !== typeEvent; - let jQueryEvent = null; - let bubbles = true; - let nativeDispatch = true; - let defaultPrevented = false; - if (inNamespace && $) { - jQueryEvent = $.Event(event, args); - $(element).trigger(jQueryEvent); - bubbles = !jQueryEvent.isPropagationStopped(); - nativeDispatch = !jQueryEvent.isImmediatePropagationStopped(); - defaultPrevented = jQueryEvent.isDefaultPrevented(); - } - const evt = hydrateObj(new Event(event, { - bubbles, - cancelable: true - }), args); - if (defaultPrevented) { - evt.preventDefault(); - } - if (nativeDispatch) { - element.dispatchEvent(evt); - } - if (evt.defaultPrevented && jQueryEvent) { - jQueryEvent.preventDefault(); - } - return evt; - } - }; - function hydrateObj(obj, meta = {}) { - for (const [key, value] of Object.entries(meta)) { - try { - obj[key] = value; - } catch (_unused) { - Object.defineProperty(obj, key, { - configurable: true, - get() { - return value; - } - }); - } - } - return obj; - } - function normalizeData(value) { - if (value === 'true') { - return true; - } - if (value === 'false') { - return false; - } - if (value === Number(value).toString()) { - return Number(value); - } - if (value === '' || value === 'null') { - return null; - } - if (typeof value !== 'string') { - return value; - } - try { - return JSON.parse(decodeURIComponent(value)); - } catch (_unused) { - return value; - } - } - function normalizeDataKey(key) { - return key.replace(/[A-Z]/g, chr => `-${chr.toLowerCase()}`); - } - const Manipulator = { - setDataAttribute(element, key, value) { - element.setAttribute(`data-bs-${normalizeDataKey(key)}`, value); - }, - removeDataAttribute(element, key) { - element.removeAttribute(`data-bs-${normalizeDataKey(key)}`); - }, - getDataAttributes(element) { - if (!element) { - return {}; - } - const attributes = {}; - const bsKeys = Object.keys(element.dataset).filter(key => key.startsWith('bs') && !key.startsWith('bsConfig')); - for (const key of bsKeys) { - let pureKey = key.replace(/^bs/, ''); - pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length); - attributes[pureKey] = normalizeData(element.dataset[key]); - } - return attributes; - }, - getDataAttribute(element, key) { - return normalizeData(element.getAttribute(`data-bs-${normalizeDataKey(key)}`)); - } - }; - class Config { - static get Default() { - return {}; - } - static get DefaultType() { - return {}; - } - static get NAME() { - throw new Error('You have to implement the static method "NAME", for each component!'); - } - _getConfig(config) { - config = this._mergeConfigObj(config); - config = this._configAfterMerge(config); - this._typeCheckConfig(config); - return config; - } - _configAfterMerge(config) { - return config; - } - _mergeConfigObj(config, element) { - const jsonConfig = isElement(element) ? Manipulator.getDataAttribute(element, 'config') : {}; - return { - ...this.constructor.Default, - ...(typeof jsonConfig === 'object' ? jsonConfig : {}), - ...(isElement(element) ? Manipulator.getDataAttributes(element) : {}), - ...(typeof config === 'object' ? config : {}) - }; - } - _typeCheckConfig(config, configTypes = this.constructor.DefaultType) { - for (const [property, expectedTypes] of Object.entries(configTypes)) { - const value = config[property]; - const valueType = isElement(value) ? 'element' : toType(value); - if (!new RegExp(expectedTypes).test(valueType)) { - throw new TypeError(`${this.constructor.NAME.toUpperCase()}: Option "${property}" provided type "${valueType}" but expected type "${expectedTypes}".`); - } - } - } - } - const VERSION = '5.3.1'; - class BaseComponent extends Config { - constructor(element, config) { - super(); - element = getElement(element); - if (!element) { - return; - } - this._element = element; - this._config = this._getConfig(config); - Data.set(this._element, this.constructor.DATA_KEY, this); - } - dispose() { - Data.remove(this._element, this.constructor.DATA_KEY); - EventHandler.off(this._element, this.constructor.EVENT_KEY); - for (const propertyName of Object.getOwnPropertyNames(this)) { - this[propertyName] = null; - } - } - _queueCallback(callback, element, isAnimated = true) { - executeAfterTransition(callback, element, isAnimated); - } - _getConfig(config) { - config = this._mergeConfigObj(config, this._element); - config = this._configAfterMerge(config); - this._typeCheckConfig(config); - return config; - } - static getInstance(element) { - return Data.get(getElement(element), this.DATA_KEY); - } - static getOrCreateInstance(element, config = {}) { - return this.getInstance(element) || new this(element, typeof config === 'object' ? config : null); - } - static get VERSION() { - return VERSION; - } - static get DATA_KEY() { - return `bs.${this.NAME}`; - } - static get EVENT_KEY() { - return `.${this.DATA_KEY}`; - } - static eventName(name) { - return `${name}${this.EVENT_KEY}`; - } - } - const getSelector = element => { - let selector = element.getAttribute('data-bs-target'); - if (!selector || selector === '#') { - let hrefAttribute = element.getAttribute('href'); - if (!hrefAttribute || !hrefAttribute.includes('#') && !hrefAttribute.startsWith('.')) { - return null; - } - if (hrefAttribute.includes('#') && !hrefAttribute.startsWith('#')) { - hrefAttribute = `#${hrefAttribute.split('#')[1]}`; - } - selector = hrefAttribute && hrefAttribute !== '#' ? hrefAttribute.trim() : null; - } - return parseSelector(selector); - }; - const SelectorEngine = { - find(selector, element = document.documentElement) { - return [].concat(...Element.prototype.querySelectorAll.call(element, selector)); - }, - findOne(selector, element = document.documentElement) { - return Element.prototype.querySelector.call(element, selector); - }, - children(element, selector) { - return [].concat(...element.children).filter(child => child.matches(selector)); - }, - parents(element, selector) { - const parents = []; - let ancestor = element.parentNode.closest(selector); - while (ancestor) { - parents.push(ancestor); - ancestor = ancestor.parentNode.closest(selector); - } - return parents; - }, - prev(element, selector) { - let previous = element.previousElementSibling; - while (previous) { - if (previous.matches(selector)) { - return [previous]; - } - previous = previous.previousElementSibling; - } - return []; - }, - next(element, selector) { - let next = element.nextElementSibling; - while (next) { - if (next.matches(selector)) { - return [next]; - } - next = next.nextElementSibling; - } - return []; - }, - focusableChildren(element) { - const focusables = ['a', 'button', 'input', 'textarea', 'select', 'details', '[tabindex]', '[contenteditable="true"]'].map(selector => `${selector}:not([tabindex^="-"])`).join(','); - return this.find(focusables, element).filter(el => !isDisabled(el) && isVisible(el)); - }, - getSelectorFromElement(element) { - const selector = getSelector(element); - if (selector) { - return SelectorEngine.findOne(selector) ? selector : null; - } - return null; - }, - getElementFromSelector(element) { - const selector = getSelector(element); - return selector ? SelectorEngine.findOne(selector) : null; - }, - getMultipleElementsFromSelector(element) { - const selector = getSelector(element); - return selector ? SelectorEngine.find(selector) : []; - } - }; - const enableDismissTrigger = (component, method = 'hide') => { - const clickEvent = `click.dismiss${component.EVENT_KEY}`; - const name = component.NAME; - EventHandler.on(document, clickEvent, `[data-bs-dismiss="${name}"]`, function (event) { - if (['A', 'AREA'].includes(this.tagName)) { - event.preventDefault(); - } - if (isDisabled(this)) { - return; - } - const target = SelectorEngine.getElementFromSelector(this) || this.closest(`.${name}`); - const instance = component.getOrCreateInstance(target); - instance[method](); - }); - }; - const NAME$f = 'alert'; - const DATA_KEY$a = 'bs.alert'; - const EVENT_KEY$b = `.${DATA_KEY$a}`; - const EVENT_CLOSE = `close${EVENT_KEY$b}`; - const EVENT_CLOSED = `closed${EVENT_KEY$b}`; - const CLASS_NAME_FADE$5 = 'fade'; - const CLASS_NAME_SHOW$8 = 'show'; - class Alert extends BaseComponent { - static get NAME() { - return NAME$f; - } - close() { - const closeEvent = EventHandler.trigger(this._element, EVENT_CLOSE); - if (closeEvent.defaultPrevented) { - return; - } - this._element.classList.remove(CLASS_NAME_SHOW$8); - const isAnimated = this._element.classList.contains(CLASS_NAME_FADE$5); - this._queueCallback(() => this._destroyElement(), this._element, isAnimated); - } - _destroyElement() { - this._element.remove(); - EventHandler.trigger(this._element, EVENT_CLOSED); - this.dispose(); - } - static jQueryInterface(config) { - return this.each(function () { - const data = Alert.getOrCreateInstance(this); - if (typeof config !== 'string') { - return; - } - if (data[config] === undefined || config.startsWith('_') || config === 'constructor') { - throw new TypeError(`No method named "${config}"`); - } - data[config](this); - }); - } - } - enableDismissTrigger(Alert, 'close'); - defineJQueryPlugin(Alert); - const NAME$e = 'button'; - const DATA_KEY$9 = 'bs.button'; - const EVENT_KEY$a = `.${DATA_KEY$9}`; - const DATA_API_KEY$6 = '.data-api'; - const CLASS_NAME_ACTIVE$3 = 'active'; - const SELECTOR_DATA_TOGGLE$5 = '[data-bs-toggle="button"]'; - const EVENT_CLICK_DATA_API$6 = `click${EVENT_KEY$a}${DATA_API_KEY$6}`; - class Button extends BaseComponent { - static get NAME() { - return NAME$e; - } - toggle() { - this._element.setAttribute('aria-pressed', this._element.classList.toggle(CLASS_NAME_ACTIVE$3)); - } - static jQueryInterface(config) { - return this.each(function () { - const data = Button.getOrCreateInstance(this); - if (config === 'toggle') { - data[config](); - } - }); - } - } - EventHandler.on(document, EVENT_CLICK_DATA_API$6, SELECTOR_DATA_TOGGLE$5, event => { - event.preventDefault(); - const button = event.target.closest(SELECTOR_DATA_TOGGLE$5); - const data = Button.getOrCreateInstance(button); - data.toggle(); - }); - defineJQueryPlugin(Button); - const NAME$d = 'swipe'; - const EVENT_KEY$9 = '.bs.swipe'; - const EVENT_TOUCHSTART = `touchstart${EVENT_KEY$9}`; - const EVENT_TOUCHMOVE = `touchmove${EVENT_KEY$9}`; - const EVENT_TOUCHEND = `touchend${EVENT_KEY$9}`; - const EVENT_POINTERDOWN = `pointerdown${EVENT_KEY$9}`; - const EVENT_POINTERUP = `pointerup${EVENT_KEY$9}`; - const POINTER_TYPE_TOUCH = 'touch'; - const POINTER_TYPE_PEN = 'pen'; - const CLASS_NAME_POINTER_EVENT = 'pointer-event'; - const SWIPE_THRESHOLD = 40; - const Default$c = { - endCallback: null, - leftCallback: null, - rightCallback: null - }; - const DefaultType$c = { - endCallback: '(function|null)', - leftCallback: '(function|null)', - rightCallback: '(function|null)' - }; - class Swipe extends Config { - constructor(element, config) { - super(); - this._element = element; - if (!element || !Swipe.isSupported()) { - return; - } - this._config = this._getConfig(config); - this._deltaX = 0; - this._supportPointerEvents = Boolean(window.PointerEvent); - this._initEvents(); - } - static get Default() { - return Default$c; - } - static get DefaultType() { - return DefaultType$c; - } - static get NAME() { - return NAME$d; - } - dispose() { - EventHandler.off(this._element, EVENT_KEY$9); - } - _start(event) { - if (!this._supportPointerEvents) { - this._deltaX = event.touches[0].clientX; - return; - } - if (this._eventIsPointerPenTouch(event)) { - this._deltaX = event.clientX; - } - } - _end(event) { - if (this._eventIsPointerPenTouch(event)) { - this._deltaX = event.clientX - this._deltaX; - } - this._handleSwipe(); - execute(this._config.endCallback); - } - _move(event) { - this._deltaX = event.touches && event.touches.length > 1 ? 0 : event.touches[0].clientX - this._deltaX; - } - _handleSwipe() { - const absDeltaX = Math.abs(this._deltaX); - if (absDeltaX <= SWIPE_THRESHOLD) { - return; - } - const direction = absDeltaX / this._deltaX; - this._deltaX = 0; - if (!direction) { - return; - } - execute(direction > 0 ? this._config.rightCallback : this._config.leftCallback); - } - _initEvents() { - if (this._supportPointerEvents) { - EventHandler.on(this._element, EVENT_POINTERDOWN, event => this._start(event)); - EventHandler.on(this._element, EVENT_POINTERUP, event => this._end(event)); - this._element.classList.add(CLASS_NAME_POINTER_EVENT); - } else { - EventHandler.on(this._element, EVENT_TOUCHSTART, event => this._start(event)); - EventHandler.on(this._element, EVENT_TOUCHMOVE, event => this._move(event)); - EventHandler.on(this._element, EVENT_TOUCHEND, event => this._end(event)); - } - } - _eventIsPointerPenTouch(event) { - return this._supportPointerEvents && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH); - } - static isSupported() { - return 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0; - } - } - const NAME$c = 'carousel'; - const DATA_KEY$8 = 'bs.carousel'; - const EVENT_KEY$8 = `.${DATA_KEY$8}`; - const DATA_API_KEY$5 = '.data-api'; - const ARROW_LEFT_KEY$1 = 'ArrowLeft'; - const ARROW_RIGHT_KEY$1 = 'ArrowRight'; - const TOUCHEVENT_COMPAT_WAIT = 500; - const ORDER_NEXT = 'next'; - const ORDER_PREV = 'prev'; - const DIRECTION_LEFT = 'left'; - const DIRECTION_RIGHT = 'right'; - const EVENT_SLIDE = `slide${EVENT_KEY$8}`; - const EVENT_SLID = `slid${EVENT_KEY$8}`; - const EVENT_KEYDOWN$1 = `keydown${EVENT_KEY$8}`; - const EVENT_MOUSEENTER$1 = `mouseenter${EVENT_KEY$8}`; - const EVENT_MOUSELEAVE$1 = `mouseleave${EVENT_KEY$8}`; - const EVENT_DRAG_START = `dragstart${EVENT_KEY$8}`; - const EVENT_LOAD_DATA_API$3 = `load${EVENT_KEY$8}${DATA_API_KEY$5}`; - const EVENT_CLICK_DATA_API$5 = `click${EVENT_KEY$8}${DATA_API_KEY$5}`; - const CLASS_NAME_CAROUSEL = 'carousel'; - const CLASS_NAME_ACTIVE$2 = 'active'; - const CLASS_NAME_SLIDE = 'slide'; - const CLASS_NAME_END = 'carousel-item-end'; - const CLASS_NAME_START = 'carousel-item-start'; - const CLASS_NAME_NEXT = 'carousel-item-next'; - const CLASS_NAME_PREV = 'carousel-item-prev'; - const SELECTOR_ACTIVE = '.active'; - const SELECTOR_ITEM = '.carousel-item'; - const SELECTOR_ACTIVE_ITEM = SELECTOR_ACTIVE + SELECTOR_ITEM; - const SELECTOR_ITEM_IMG = '.carousel-item img'; - const SELECTOR_INDICATORS = '.carousel-indicators'; - const SELECTOR_DATA_SLIDE = '[data-bs-slide], [data-bs-slide-to]'; - const SELECTOR_DATA_RIDE = '[data-bs-ride="carousel"]'; - const KEY_TO_DIRECTION = { - [ARROW_LEFT_KEY$1]: DIRECTION_RIGHT, - [ARROW_RIGHT_KEY$1]: DIRECTION_LEFT - }; - const Default$b = { - interval: 5000, - keyboard: true, - pause: 'hover', - ride: false, - touch: true, - wrap: true - }; - const DefaultType$b = { - interval: '(number|boolean)', - keyboard: 'boolean', - pause: '(string|boolean)', - ride: '(boolean|string)', - touch: 'boolean', - wrap: 'boolean' - }; - class Carousel extends BaseComponent { - constructor(element, config) { - super(element, config); - this._interval = null; - this._activeElement = null; - this._isSliding = false; - this.touchTimeout = null; - this._swipeHelper = null; - this._indicatorsElement = SelectorEngine.findOne(SELECTOR_INDICATORS, this._element); - this._addEventListeners(); - if (this._config.ride === CLASS_NAME_CAROUSEL) { - this.cycle(); - } - } - static get Default() { - return Default$b; - } - static get DefaultType() { - return DefaultType$b; - } - static get NAME() { - return NAME$c; - } - next() { - this._slide(ORDER_NEXT); - } - nextWhenVisible() { - if (!document.hidden && isVisible(this._element)) { - this.next(); - } - } - prev() { - this._slide(ORDER_PREV); - } - pause() { - if (this._isSliding) { - triggerTransitionEnd(this._element); - } - this._clearInterval(); - } - cycle() { - this._clearInterval(); - this._updateInterval(); - this._interval = setInterval(() => this.nextWhenVisible(), this._config.interval); - } - _maybeEnableCycle() { - if (!this._config.ride) { - return; - } - if (this._isSliding) { - EventHandler.one(this._element, EVENT_SLID, () => this.cycle()); - return; - } - this.cycle(); - } - to(index) { - const items = this._getItems(); - if (index > items.length - 1 || index < 0) { - return; - } - if (this._isSliding) { - EventHandler.one(this._element, EVENT_SLID, () => this.to(index)); - return; - } - const activeIndex = this._getItemIndex(this._getActive()); - if (activeIndex === index) { - return; - } - const order = index > activeIndex ? ORDER_NEXT : ORDER_PREV; - this._slide(order, items[index]); - } - dispose() { - if (this._swipeHelper) { - this._swipeHelper.dispose(); - } - super.dispose(); - } - _configAfterMerge(config) { - config.defaultInterval = config.interval; - return config; - } - _addEventListeners() { - if (this._config.keyboard) { - EventHandler.on(this._element, EVENT_KEYDOWN$1, event => this._keydown(event)); - } - if (this._config.pause === 'hover') { - EventHandler.on(this._element, EVENT_MOUSEENTER$1, () => this.pause()); - EventHandler.on(this._element, EVENT_MOUSELEAVE$1, () => this._maybeEnableCycle()); - } - if (this._config.touch && Swipe.isSupported()) { - this._addTouchEventListeners(); - } - } - _addTouchEventListeners() { - for (const img of SelectorEngine.find(SELECTOR_ITEM_IMG, this._element)) { - EventHandler.on(img, EVENT_DRAG_START, event => event.preventDefault()); - } - const endCallBack = () => { - if (this._config.pause !== 'hover') { - return; - } - this.pause(); - if (this.touchTimeout) { - clearTimeout(this.touchTimeout); - } - this.touchTimeout = setTimeout(() => this._maybeEnableCycle(), TOUCHEVENT_COMPAT_WAIT + this._config.interval); - }; - const swipeConfig = { - leftCallback: () => this._slide(this._directionToOrder(DIRECTION_LEFT)), - rightCallback: () => this._slide(this._directionToOrder(DIRECTION_RIGHT)), - endCallback: endCallBack - }; - this._swipeHelper = new Swipe(this._element, swipeConfig); - } - _keydown(event) { - if (/input|textarea/i.test(event.target.tagName)) { - return; - } - const direction = KEY_TO_DIRECTION[event.key]; - if (direction) { - event.preventDefault(); - this._slide(this._directionToOrder(direction)); - } - } - _getItemIndex(element) { - return this._getItems().indexOf(element); - } - _setActiveIndicatorElement(index) { - if (!this._indicatorsElement) { - return; - } - const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE, this._indicatorsElement); - activeIndicator.classList.remove(CLASS_NAME_ACTIVE$2); - activeIndicator.removeAttribute('aria-current'); - const newActiveIndicator = SelectorEngine.findOne(`[data-bs-slide-to="${index}"]`, this._indicatorsElement); - if (newActiveIndicator) { - newActiveIndicator.classList.add(CLASS_NAME_ACTIVE$2); - newActiveIndicator.setAttribute('aria-current', 'true'); - } - } - _updateInterval() { - const element = this._activeElement || this._getActive(); - if (!element) { - return; - } - const elementInterval = Number.parseInt(element.getAttribute('data-bs-interval'), 10); - this._config.interval = elementInterval || this._config.defaultInterval; - } - _slide(order, element = null) { - if (this._isSliding) { - return; - } - const activeElement = this._getActive(); - const isNext = order === ORDER_NEXT; - const nextElement = element || getNextActiveElement(this._getItems(), activeElement, isNext, this._config.wrap); - if (nextElement === activeElement) { - return; - } - const nextElementIndex = this._getItemIndex(nextElement); - const triggerEvent = eventName => { - return EventHandler.trigger(this._element, eventName, { - relatedTarget: nextElement, - direction: this._orderToDirection(order), - from: this._getItemIndex(activeElement), - to: nextElementIndex - }); - }; - const slideEvent = triggerEvent(EVENT_SLIDE); - if (slideEvent.defaultPrevented) { - return; - } - if (!activeElement || !nextElement) { - return; - } - const isCycling = Boolean(this._interval); - this.pause(); - this._isSliding = true; - this._setActiveIndicatorElement(nextElementIndex); - this._activeElement = nextElement; - const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END; - const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV; - nextElement.classList.add(orderClassName); - reflow(nextElement); - activeElement.classList.add(directionalClassName); - nextElement.classList.add(directionalClassName); - const completeCallBack = () => { - nextElement.classList.remove(directionalClassName, orderClassName); - nextElement.classList.add(CLASS_NAME_ACTIVE$2); - activeElement.classList.remove(CLASS_NAME_ACTIVE$2, orderClassName, directionalClassName); - this._isSliding = false; - triggerEvent(EVENT_SLID); - }; - this._queueCallback(completeCallBack, activeElement, this._isAnimated()); - if (isCycling) { - this.cycle(); - } - } - _isAnimated() { - return this._element.classList.contains(CLASS_NAME_SLIDE); - } - _getActive() { - return SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element); - } - _getItems() { - return SelectorEngine.find(SELECTOR_ITEM, this._element); - } - _clearInterval() { - if (this._interval) { - clearInterval(this._interval); - this._interval = null; - } - } - _directionToOrder(direction) { - if (isRTL()) { - return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT; - } - return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV; - } - _orderToDirection(order) { - if (isRTL()) { - return order === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT; - } - return order === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT; - } - static jQueryInterface(config) { - return this.each(function () { - const data = Carousel.getOrCreateInstance(this, config); - if (typeof config === 'number') { - data.to(config); - return; - } - if (typeof config === 'string') { - if (data[config] === undefined || config.startsWith('_') || config === 'constructor') { - throw new TypeError(`No method named "${config}"`); - } - data[config](); - } - }); - } - } - EventHandler.on(document, EVENT_CLICK_DATA_API$5, SELECTOR_DATA_SLIDE, function (event) { - const target = SelectorEngine.getElementFromSelector(this); - if (!target || !target.classList.contains(CLASS_NAME_CAROUSEL)) { - return; - } - event.preventDefault(); - const carousel = Carousel.getOrCreateInstance(target); - const slideIndex = this.getAttribute('data-bs-slide-to'); - if (slideIndex) { - carousel.to(slideIndex); - carousel._maybeEnableCycle(); - return; - } - if (Manipulator.getDataAttribute(this, 'slide') === 'next') { - carousel.next(); - carousel._maybeEnableCycle(); - return; - } - carousel.prev(); - carousel._maybeEnableCycle(); - }); - EventHandler.on(window, EVENT_LOAD_DATA_API$3, () => { - const carousels = SelectorEngine.find(SELECTOR_DATA_RIDE); - for (const carousel of carousels) { - Carousel.getOrCreateInstance(carousel); - } - }); - defineJQueryPlugin(Carousel); - const NAME$b = 'collapse'; - const DATA_KEY$7 = 'bs.collapse'; - const EVENT_KEY$7 = `.${DATA_KEY$7}`; - const DATA_API_KEY$4 = '.data-api'; - const EVENT_SHOW$6 = `show${EVENT_KEY$7}`; - const EVENT_SHOWN$6 = `shown${EVENT_KEY$7}`; - const EVENT_HIDE$6 = `hide${EVENT_KEY$7}`; - const EVENT_HIDDEN$6 = `hidden${EVENT_KEY$7}`; - const EVENT_CLICK_DATA_API$4 = `click${EVENT_KEY$7}${DATA_API_KEY$4}`; - const CLASS_NAME_SHOW$7 = 'show'; - const CLASS_NAME_COLLAPSE = 'collapse'; - const CLASS_NAME_COLLAPSING = 'collapsing'; - const CLASS_NAME_COLLAPSED = 'collapsed'; - const CLASS_NAME_DEEPER_CHILDREN = `:scope .${CLASS_NAME_COLLAPSE} .${CLASS_NAME_COLLAPSE}`; - const CLASS_NAME_HORIZONTAL = 'collapse-horizontal'; - const WIDTH = 'width'; - const HEIGHT = 'height'; - const SELECTOR_ACTIVES = '.collapse.show, .collapse.collapsing'; - const SELECTOR_DATA_TOGGLE$4 = '[data-bs-toggle="collapse"]'; - const Default$a = { - parent: null, - toggle: true - }; - const DefaultType$a = { - parent: '(null|element)', - toggle: 'boolean' - }; - class Collapse extends BaseComponent { - constructor(element, config) { - super(element, config); - this._isTransitioning = false; - this._triggerArray = []; - const toggleList = SelectorEngine.find(SELECTOR_DATA_TOGGLE$4); - for (const elem of toggleList) { - const selector = SelectorEngine.getSelectorFromElement(elem); - const filterElement = SelectorEngine.find(selector).filter(foundElement => foundElement === this._element); - if (selector !== null && filterElement.length) { - this._triggerArray.push(elem); - } - } - this._initializeChildren(); - if (!this._config.parent) { - this._addAriaAndCollapsedClass(this._triggerArray, this._isShown()); - } - if (this._config.toggle) { - this.toggle(); - } - } - static get Default() { - return Default$a; - } - static get DefaultType() { - return DefaultType$a; - } - static get NAME() { - return NAME$b; - } - toggle() { - if (this._isShown()) { - this.hide(); - } else { - this.show(); - } - } - show() { - if (this._isTransitioning || this._isShown()) { - return; - } - let activeChildren = []; - if (this._config.parent) { - activeChildren = this._getFirstLevelChildren(SELECTOR_ACTIVES).filter(element => element !== this._element).map(element => Collapse.getOrCreateInstance(element, { - toggle: false - })); - } - if (activeChildren.length && activeChildren[0]._isTransitioning) { - return; - } - const startEvent = EventHandler.trigger(this._element, EVENT_SHOW$6); - if (startEvent.defaultPrevented) { - return; - } - for (const activeInstance of activeChildren) { - activeInstance.hide(); - } - const dimension = this._getDimension(); - this._element.classList.remove(CLASS_NAME_COLLAPSE); - this._element.classList.add(CLASS_NAME_COLLAPSING); - this._element.style[dimension] = 0; - this._addAriaAndCollapsedClass(this._triggerArray, true); - this._isTransitioning = true; - const complete = () => { - this._isTransitioning = false; - this._element.classList.remove(CLASS_NAME_COLLAPSING); - this._element.classList.add(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7); - this._element.style[dimension] = ''; - EventHandler.trigger(this._element, EVENT_SHOWN$6); - }; - const capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1); - const scrollSize = `scroll${capitalizedDimension}`; - this._queueCallback(complete, this._element, true); - this._element.style[dimension] = `${this._element[scrollSize]}px`; - } - hide() { - if (this._isTransitioning || !this._isShown()) { - return; - } - const startEvent = EventHandler.trigger(this._element, EVENT_HIDE$6); - if (startEvent.defaultPrevented) { - return; - } - const dimension = this._getDimension(); - this._element.style[dimension] = `${this._element.getBoundingClientRect()[dimension]}px`; - reflow(this._element); - this._element.classList.add(CLASS_NAME_COLLAPSING); - this._element.classList.remove(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7); - for (const trigger of this._triggerArray) { - const element = SelectorEngine.getElementFromSelector(trigger); - if (element && !this._isShown(element)) { - this._addAriaAndCollapsedClass([trigger], false); - } - } - this._isTransitioning = true; - const complete = () => { - this._isTransitioning = false; - this._element.classList.remove(CLASS_NAME_COLLAPSING); - this._element.classList.add(CLASS_NAME_COLLAPSE); - EventHandler.trigger(this._element, EVENT_HIDDEN$6); - }; - this._element.style[dimension] = ''; - this._queueCallback(complete, this._element, true); - } - _isShown(element = this._element) { - return element.classList.contains(CLASS_NAME_SHOW$7); - } - _configAfterMerge(config) { - config.toggle = Boolean(config.toggle); - config.parent = getElement(config.parent); - return config; - } - _getDimension() { - return this._element.classList.contains(CLASS_NAME_HORIZONTAL) ? WIDTH : HEIGHT; - } - _initializeChildren() { - if (!this._config.parent) { - return; - } - const children = this._getFirstLevelChildren(SELECTOR_DATA_TOGGLE$4); - for (const element of children) { - const selected = SelectorEngine.getElementFromSelector(element); - if (selected) { - this._addAriaAndCollapsedClass([element], this._isShown(selected)); - } - } - } - _getFirstLevelChildren(selector) { - const children = SelectorEngine.find(CLASS_NAME_DEEPER_CHILDREN, this._config.parent); - return SelectorEngine.find(selector, this._config.parent).filter(element => !children.includes(element)); - } - _addAriaAndCollapsedClass(triggerArray, isOpen) { - if (!triggerArray.length) { - return; - } - for (const element of triggerArray) { - element.classList.toggle(CLASS_NAME_COLLAPSED, !isOpen); - element.setAttribute('aria-expanded', isOpen); - } - } - static jQueryInterface(config) { - const _config = {}; - if (typeof config === 'string' && /show|hide/.test(config)) { - _config.toggle = false; - } - return this.each(function () { - const data = Collapse.getOrCreateInstance(this, _config); - if (typeof config === 'string') { - if (typeof data[config] === 'undefined') { - throw new TypeError(`No method named "${config}"`); - } - data[config](); - } - }); - } - } - EventHandler.on(document, EVENT_CLICK_DATA_API$4, SELECTOR_DATA_TOGGLE$4, function (event) { - if (event.target.tagName === 'A' || event.delegateTarget && event.delegateTarget.tagName === 'A') { - event.preventDefault(); - } - for (const element of SelectorEngine.getMultipleElementsFromSelector(this)) { - Collapse.getOrCreateInstance(element, { - toggle: false - }).toggle(); - } - }); - defineJQueryPlugin(Collapse); - const NAME$a = 'dropdown'; - const DATA_KEY$6 = 'bs.dropdown'; - const EVENT_KEY$6 = `.${DATA_KEY$6}`; - const DATA_API_KEY$3 = '.data-api'; - const ESCAPE_KEY$2 = 'Escape'; - const TAB_KEY$1 = 'Tab'; - const ARROW_UP_KEY$1 = 'ArrowUp'; - const ARROW_DOWN_KEY$1 = 'ArrowDown'; - const RIGHT_MOUSE_BUTTON = 2; - const EVENT_HIDE$5 = `hide${EVENT_KEY$6}`; - const EVENT_HIDDEN$5 = `hidden${EVENT_KEY$6}`; - const EVENT_SHOW$5 = `show${EVENT_KEY$6}`; - const EVENT_SHOWN$5 = `shown${EVENT_KEY$6}`; - const EVENT_CLICK_DATA_API$3 = `click${EVENT_KEY$6}${DATA_API_KEY$3}`; - const EVENT_KEYDOWN_DATA_API = `keydown${EVENT_KEY$6}${DATA_API_KEY$3}`; - const EVENT_KEYUP_DATA_API = `keyup${EVENT_KEY$6}${DATA_API_KEY$3}`; - const CLASS_NAME_SHOW$6 = 'show'; - const CLASS_NAME_DROPUP = 'dropup'; - const CLASS_NAME_DROPEND = 'dropend'; - const CLASS_NAME_DROPSTART = 'dropstart'; - const CLASS_NAME_DROPUP_CENTER = 'dropup-center'; - const CLASS_NAME_DROPDOWN_CENTER = 'dropdown-center'; - const SELECTOR_DATA_TOGGLE$3 = '[data-bs-toggle="dropdown"]:not(.disabled):not(:disabled)'; - const SELECTOR_DATA_TOGGLE_SHOWN = `${SELECTOR_DATA_TOGGLE$3}.${CLASS_NAME_SHOW$6}`; - const SELECTOR_MENU = '.dropdown-menu'; - const SELECTOR_NAVBAR = '.navbar'; - const SELECTOR_NAVBAR_NAV = '.navbar-nav'; - const SELECTOR_VISIBLE_ITEMS = '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)'; - const PLACEMENT_TOP = isRTL() ? 'top-end' : 'top-start'; - const PLACEMENT_TOPEND = isRTL() ? 'top-start' : 'top-end'; - const PLACEMENT_BOTTOM = isRTL() ? 'bottom-end' : 'bottom-start'; - const PLACEMENT_BOTTOMEND = isRTL() ? 'bottom-start' : 'bottom-end'; - const PLACEMENT_RIGHT = isRTL() ? 'left-start' : 'right-start'; - const PLACEMENT_LEFT = isRTL() ? 'right-start' : 'left-start'; - const PLACEMENT_TOPCENTER = 'top'; - const PLACEMENT_BOTTOMCENTER = 'bottom'; - const Default$9 = { - autoClose: true, - boundary: 'clippingParents', - display: 'dynamic', - offset: [0, 2], - popperConfig: null, - reference: 'toggle' - }; - const DefaultType$9 = { - autoClose: '(boolean|string)', - boundary: '(string|element)', - display: 'string', - offset: '(array|string|function)', - popperConfig: '(null|object|function)', - reference: '(string|element|object)' - }; - class Dropdown extends BaseComponent { - constructor(element, config) { - super(element, config); - this._popper = null; - this._parent = this._element.parentNode; - this._menu = SelectorEngine.next(this._element, SELECTOR_MENU)[0] || SelectorEngine.prev(this._element, SELECTOR_MENU)[0] || SelectorEngine.findOne(SELECTOR_MENU, this._parent); - this._inNavbar = this._detectNavbar(); - } - static get Default() { - return Default$9; - } - static get DefaultType() { - return DefaultType$9; - } - static get NAME() { - return NAME$a; - } - toggle() { - return this._isShown() ? this.hide() : this.show(); - } - show() { - if (isDisabled(this._element) || this._isShown()) { - return; - } - const relatedTarget = { - relatedTarget: this._element - }; - const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$5, relatedTarget); - if (showEvent.defaultPrevented) { - return; - } - this._createPopper(); - if ('ontouchstart' in document.documentElement && !this._parent.closest(SELECTOR_NAVBAR_NAV)) { - for (const element of [].concat(...document.body.children)) { - EventHandler.on(element, 'mouseover', noop); - } - } - this._element.focus(); - this._element.setAttribute('aria-expanded', true); - this._menu.classList.add(CLASS_NAME_SHOW$6); - this._element.classList.add(CLASS_NAME_SHOW$6); - EventHandler.trigger(this._element, EVENT_SHOWN$5, relatedTarget); - } - hide() { - if (isDisabled(this._element) || !this._isShown()) { - return; - } - const relatedTarget = { - relatedTarget: this._element - }; - this._completeHide(relatedTarget); - } - dispose() { - if (this._popper) { - this._popper.destroy(); - } - super.dispose(); - } - update() { - this._inNavbar = this._detectNavbar(); - if (this._popper) { - this._popper.update(); - } - } - _completeHide(relatedTarget) { - const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$5, relatedTarget); - if (hideEvent.defaultPrevented) { - return; - } - if ('ontouchstart' in document.documentElement) { - for (const element of [].concat(...document.body.children)) { - EventHandler.off(element, 'mouseover', noop); - } - } - if (this._popper) { - this._popper.destroy(); - } - this._menu.classList.remove(CLASS_NAME_SHOW$6); - this._element.classList.remove(CLASS_NAME_SHOW$6); - this._element.setAttribute('aria-expanded', 'false'); - Manipulator.removeDataAttribute(this._menu, 'popper'); - EventHandler.trigger(this._element, EVENT_HIDDEN$5, relatedTarget); - } - _getConfig(config) { - config = super._getConfig(config); - if (typeof config.reference === 'object' && !isElement(config.reference) && typeof config.reference.getBoundingClientRect !== 'function') { - throw new TypeError(`${NAME$a.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`); - } - return config; - } - _createPopper() { - if (typeof Popper === 'undefined') { - throw new TypeError('Bootstrap\'s dropdowns require Popper (https://popper.js.org)'); - } - let referenceElement = this._element; - if (this._config.reference === 'parent') { - referenceElement = this._parent; - } else if (isElement(this._config.reference)) { - referenceElement = getElement(this._config.reference); - } else if (typeof this._config.reference === 'object') { - referenceElement = this._config.reference; - } - const popperConfig = this._getPopperConfig(); - this._popper = createPopper(referenceElement, this._menu, popperConfig); - } - _isShown() { - return this._menu.classList.contains(CLASS_NAME_SHOW$6); - } - _getPlacement() { - const parentDropdown = this._parent; - if (parentDropdown.classList.contains(CLASS_NAME_DROPEND)) { - return PLACEMENT_RIGHT; - } - if (parentDropdown.classList.contains(CLASS_NAME_DROPSTART)) { - return PLACEMENT_LEFT; - } - if (parentDropdown.classList.contains(CLASS_NAME_DROPUP_CENTER)) { - return PLACEMENT_TOPCENTER; - } - if (parentDropdown.classList.contains(CLASS_NAME_DROPDOWN_CENTER)) { - return PLACEMENT_BOTTOMCENTER; - } - const isEnd = getComputedStyle(this._menu).getPropertyValue('--bs-position').trim() === 'end'; - if (parentDropdown.classList.contains(CLASS_NAME_DROPUP)) { - return isEnd ? PLACEMENT_TOPEND : PLACEMENT_TOP; - } - return isEnd ? PLACEMENT_BOTTOMEND : PLACEMENT_BOTTOM; - } - _detectNavbar() { - return this._element.closest(SELECTOR_NAVBAR) !== null; - } - _getOffset() { - const { - offset - } = this._config; - if (typeof offset === 'string') { - return offset.split(',').map(value => Number.parseInt(value, 10)); - } - if (typeof offset === 'function') { - return popperData => offset(popperData, this._element); - } - return offset; - } - _getPopperConfig() { - const defaultBsPopperConfig = { - placement: this._getPlacement(), - modifiers: [{ - name: 'preventOverflow', - options: { - boundary: this._config.boundary - } - }, { - name: 'offset', - options: { - offset: this._getOffset() - } - }] - }; - if (this._inNavbar || this._config.display === 'static') { - Manipulator.setDataAttribute(this._menu, 'popper', 'static'); - defaultBsPopperConfig.modifiers = [{ - name: 'applyStyles', - enabled: false - }]; - } - return { - ...defaultBsPopperConfig, - ...execute(this._config.popperConfig, [defaultBsPopperConfig]) - }; - } - _selectMenuItem({ - key, - target - }) { - const items = SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(element => isVisible(element)); - if (!items.length) { - return; - } - getNextActiveElement(items, target, key === ARROW_DOWN_KEY$1, !items.includes(target)).focus(); - } - static jQueryInterface(config) { - return this.each(function () { - const data = Dropdown.getOrCreateInstance(this, config); - if (typeof config !== 'string') { - return; - } - if (typeof data[config] === 'undefined') { - throw new TypeError(`No method named "${config}"`); - } - data[config](); - }); - } - static clearMenus(event) { - if (event.button === RIGHT_MOUSE_BUTTON || event.type === 'keyup' && event.key !== TAB_KEY$1) { - return; - } - const openToggles = SelectorEngine.find(SELECTOR_DATA_TOGGLE_SHOWN); - for (const toggle of openToggles) { - const context = Dropdown.getInstance(toggle); - if (!context || context._config.autoClose === false) { - continue; - } - const composedPath = event.composedPath(); - const isMenuTarget = composedPath.includes(context._menu); - if (composedPath.includes(context._element) || context._config.autoClose === 'inside' && !isMenuTarget || context._config.autoClose === 'outside' && isMenuTarget) { - continue; - } - if (context._menu.contains(event.target) && (event.type === 'keyup' && event.key === TAB_KEY$1 || /input|select|option|textarea|form/i.test(event.target.tagName))) { - continue; - } - const relatedTarget = { - relatedTarget: context._element - }; - if (event.type === 'click') { - relatedTarget.clickEvent = event; - } - context._completeHide(relatedTarget); - } - } - static dataApiKeydownHandler(event) { - const isInput = /input|textarea/i.test(event.target.tagName); - const isEscapeEvent = event.key === ESCAPE_KEY$2; - const isUpOrDownEvent = [ARROW_UP_KEY$1, ARROW_DOWN_KEY$1].includes(event.key); - if (!isUpOrDownEvent && !isEscapeEvent) { - return; - } - if (isInput && !isEscapeEvent) { - return; - } - event.preventDefault(); - const getToggleButton = this.matches(SELECTOR_DATA_TOGGLE$3) ? this : SelectorEngine.prev(this, SELECTOR_DATA_TOGGLE$3)[0] || SelectorEngine.next(this, SELECTOR_DATA_TOGGLE$3)[0] || SelectorEngine.findOne(SELECTOR_DATA_TOGGLE$3, event.delegateTarget.parentNode); - const instance = Dropdown.getOrCreateInstance(getToggleButton); - if (isUpOrDownEvent) { - event.stopPropagation(); - instance.show(); - instance._selectMenuItem(event); - return; - } - if (instance._isShown()) { - event.stopPropagation(); - instance.hide(); - getToggleButton.focus(); - } - } - } - EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_DATA_TOGGLE$3, Dropdown.dataApiKeydownHandler); - EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_MENU, Dropdown.dataApiKeydownHandler); - EventHandler.on(document, EVENT_CLICK_DATA_API$3, Dropdown.clearMenus); - EventHandler.on(document, EVENT_KEYUP_DATA_API, Dropdown.clearMenus); - EventHandler.on(document, EVENT_CLICK_DATA_API$3, SELECTOR_DATA_TOGGLE$3, function (event) { - event.preventDefault(); - Dropdown.getOrCreateInstance(this).toggle(); - }); - defineJQueryPlugin(Dropdown); - const NAME$9 = 'backdrop'; - const CLASS_NAME_FADE$4 = 'fade'; - const CLASS_NAME_SHOW$5 = 'show'; - const EVENT_MOUSEDOWN = `mousedown.bs.${NAME$9}`; - const Default$8 = { - className: 'modal-backdrop', - clickCallback: null, - isAnimated: false, - isVisible: true, - rootElement: 'body' - }; - const DefaultType$8 = { - className: 'string', - clickCallback: '(function|null)', - isAnimated: 'boolean', - isVisible: 'boolean', - rootElement: '(element|string)' - }; - class Backdrop extends Config { - constructor(config) { - super(); - this._config = this._getConfig(config); - this._isAppended = false; - this._element = null; - } - static get Default() { - return Default$8; - } - static get DefaultType() { - return DefaultType$8; - } - static get NAME() { - return NAME$9; - } - show(callback) { - if (!this._config.isVisible) { - execute(callback); - return; - } - this._append(); - const element = this._getElement(); - if (this._config.isAnimated) { - reflow(element); - } - element.classList.add(CLASS_NAME_SHOW$5); - this._emulateAnimation(() => { - execute(callback); - }); - } - hide(callback) { - if (!this._config.isVisible) { - execute(callback); - return; - } - this._getElement().classList.remove(CLASS_NAME_SHOW$5); - this._emulateAnimation(() => { - this.dispose(); - execute(callback); - }); - } - dispose() { - if (!this._isAppended) { - return; - } - EventHandler.off(this._element, EVENT_MOUSEDOWN); - this._element.remove(); - this._isAppended = false; - } - _getElement() { - if (!this._element) { - const backdrop = document.createElement('div'); - backdrop.className = this._config.className; - if (this._config.isAnimated) { - backdrop.classList.add(CLASS_NAME_FADE$4); - } - this._element = backdrop; - } - return this._element; - } - _configAfterMerge(config) { - config.rootElement = getElement(config.rootElement); - return config; - } - _append() { - if (this._isAppended) { - return; - } - const element = this._getElement(); - this._config.rootElement.append(element); - EventHandler.on(element, EVENT_MOUSEDOWN, () => { - execute(this._config.clickCallback); - }); - this._isAppended = true; - } - _emulateAnimation(callback) { - executeAfterTransition(callback, this._getElement(), this._config.isAnimated); - } - } - const NAME$8 = 'focustrap'; - const DATA_KEY$5 = 'bs.focustrap'; - const EVENT_KEY$5 = `.${DATA_KEY$5}`; - const EVENT_FOCUSIN$2 = `focusin${EVENT_KEY$5}`; - const EVENT_KEYDOWN_TAB = `keydown.tab${EVENT_KEY$5}`; - const TAB_KEY = 'Tab'; - const TAB_NAV_FORWARD = 'forward'; - const TAB_NAV_BACKWARD = 'backward'; - const Default$7 = { - autofocus: true, - trapElement: null - }; - const DefaultType$7 = { - autofocus: 'boolean', - trapElement: 'element' - }; - class FocusTrap extends Config { - constructor(config) { - super(); - this._config = this._getConfig(config); - this._isActive = false; - this._lastTabNavDirection = null; - } - static get Default() { - return Default$7; - } - static get DefaultType() { - return DefaultType$7; - } - static get NAME() { - return NAME$8; - } - activate() { - if (this._isActive) { - return; - } - if (this._config.autofocus) { - this._config.trapElement.focus(); - } - EventHandler.off(document, EVENT_KEY$5); - EventHandler.on(document, EVENT_FOCUSIN$2, event => this._handleFocusin(event)); - EventHandler.on(document, EVENT_KEYDOWN_TAB, event => this._handleKeydown(event)); - this._isActive = true; - } - deactivate() { - if (!this._isActive) { - return; - } - this._isActive = false; - EventHandler.off(document, EVENT_KEY$5); - } - _handleFocusin(event) { - const { - trapElement - } = this._config; - if (event.target === document || event.target === trapElement || trapElement.contains(event.target)) { - return; - } - const elements = SelectorEngine.focusableChildren(trapElement); - if (elements.length === 0) { - trapElement.focus(); - } else if (this._lastTabNavDirection === TAB_NAV_BACKWARD) { - elements[elements.length - 1].focus(); - } else { - elements[0].focus(); - } - } - _handleKeydown(event) { - if (event.key !== TAB_KEY) { - return; - } - this._lastTabNavDirection = event.shiftKey ? TAB_NAV_BACKWARD : TAB_NAV_FORWARD; - } - } - const SELECTOR_FIXED_CONTENT = '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top'; - const SELECTOR_STICKY_CONTENT = '.sticky-top'; - const PROPERTY_PADDING = 'padding-right'; - const PROPERTY_MARGIN = 'margin-right'; - class ScrollBarHelper { - constructor() { - this._element = document.body; - } - getWidth() { - const documentWidth = document.documentElement.clientWidth; - return Math.abs(window.innerWidth - documentWidth); - } - hide() { - const width = this.getWidth(); - this._disableOverFlow(); - this._setElementAttributes(this._element, PROPERTY_PADDING, calculatedValue => calculatedValue + width); - this._setElementAttributes(SELECTOR_FIXED_CONTENT, PROPERTY_PADDING, calculatedValue => calculatedValue + width); - this._setElementAttributes(SELECTOR_STICKY_CONTENT, PROPERTY_MARGIN, calculatedValue => calculatedValue - width); - } - reset() { - this._resetElementAttributes(this._element, 'overflow'); - this._resetElementAttributes(this._element, PROPERTY_PADDING); - this._resetElementAttributes(SELECTOR_FIXED_CONTENT, PROPERTY_PADDING); - this._resetElementAttributes(SELECTOR_STICKY_CONTENT, PROPERTY_MARGIN); - } - isOverflowing() { - return this.getWidth() > 0; - } - _disableOverFlow() { - this._saveInitialAttribute(this._element, 'overflow'); - this._element.style.overflow = 'hidden'; - } - _setElementAttributes(selector, styleProperty, callback) { - const scrollbarWidth = this.getWidth(); - const manipulationCallBack = element => { - if (element !== this._element && window.innerWidth > element.clientWidth + scrollbarWidth) { - return; - } - this._saveInitialAttribute(element, styleProperty); - const calculatedValue = window.getComputedStyle(element).getPropertyValue(styleProperty); - element.style.setProperty(styleProperty, `${callback(Number.parseFloat(calculatedValue))}px`); - }; - this._applyManipulationCallback(selector, manipulationCallBack); - } - _saveInitialAttribute(element, styleProperty) { - const actualValue = element.style.getPropertyValue(styleProperty); - if (actualValue) { - Manipulator.setDataAttribute(element, styleProperty, actualValue); - } - } - _resetElementAttributes(selector, styleProperty) { - const manipulationCallBack = element => { - const value = Manipulator.getDataAttribute(element, styleProperty); - if (value === null) { - element.style.removeProperty(styleProperty); - return; - } - Manipulator.removeDataAttribute(element, styleProperty); - element.style.setProperty(styleProperty, value); - }; - this._applyManipulationCallback(selector, manipulationCallBack); - } - _applyManipulationCallback(selector, callBack) { - if (isElement(selector)) { - callBack(selector); - return; - } - for (const sel of SelectorEngine.find(selector, this._element)) { - callBack(sel); - } - } - } - const NAME$7 = 'modal'; - const DATA_KEY$4 = 'bs.modal'; - const EVENT_KEY$4 = `.${DATA_KEY$4}`; - const DATA_API_KEY$2 = '.data-api'; - const ESCAPE_KEY$1 = 'Escape'; - const EVENT_HIDE$4 = `hide${EVENT_KEY$4}`; - const EVENT_HIDE_PREVENTED$1 = `hidePrevented${EVENT_KEY$4}`; - const EVENT_HIDDEN$4 = `hidden${EVENT_KEY$4}`; - const EVENT_SHOW$4 = `show${EVENT_KEY$4}`; - const EVENT_SHOWN$4 = `shown${EVENT_KEY$4}`; - const EVENT_RESIZE$1 = `resize${EVENT_KEY$4}`; - const EVENT_CLICK_DISMISS = `click.dismiss${EVENT_KEY$4}`; - const EVENT_MOUSEDOWN_DISMISS = `mousedown.dismiss${EVENT_KEY$4}`; - const EVENT_KEYDOWN_DISMISS$1 = `keydown.dismiss${EVENT_KEY$4}`; - const EVENT_CLICK_DATA_API$2 = `click${EVENT_KEY$4}${DATA_API_KEY$2}`; - const CLASS_NAME_OPEN = 'modal-open'; - const CLASS_NAME_FADE$3 = 'fade'; - const CLASS_NAME_SHOW$4 = 'show'; - const CLASS_NAME_STATIC = 'modal-static'; - const OPEN_SELECTOR$1 = '.modal.show'; - const SELECTOR_DIALOG = '.modal-dialog'; - const SELECTOR_MODAL_BODY = '.modal-body'; - const SELECTOR_DATA_TOGGLE$2 = '[data-bs-toggle="modal"]'; - const Default$6 = { - backdrop: true, - focus: true, - keyboard: true - }; - const DefaultType$6 = { - backdrop: '(boolean|string)', - focus: 'boolean', - keyboard: 'boolean' - }; - class Modal extends BaseComponent { - constructor(element, config) { - super(element, config); - this._dialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element); - this._backdrop = this._initializeBackDrop(); - this._focustrap = this._initializeFocusTrap(); - this._isShown = false; - this._isTransitioning = false; - this._scrollBar = new ScrollBarHelper(); - this._addEventListeners(); - } - static get Default() { - return Default$6; - } - static get DefaultType() { - return DefaultType$6; - } - static get NAME() { - return NAME$7; - } - toggle(relatedTarget) { - return this._isShown ? this.hide() : this.show(relatedTarget); - } - show(relatedTarget) { - if (this._isShown || this._isTransitioning) { - return; - } - const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$4, { - relatedTarget - }); - if (showEvent.defaultPrevented) { - return; - } - this._isShown = true; - this._isTransitioning = true; - this._scrollBar.hide(); - document.body.classList.add(CLASS_NAME_OPEN); - this._adjustDialog(); - this._backdrop.show(() => this._showElement(relatedTarget)); - } - hide() { - if (!this._isShown || this._isTransitioning) { - return; - } - const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$4); - if (hideEvent.defaultPrevented) { - return; - } - this._isShown = false; - this._isTransitioning = true; - this._focustrap.deactivate(); - this._element.classList.remove(CLASS_NAME_SHOW$4); - this._queueCallback(() => this._hideModal(), this._element, this._isAnimated()); - } - dispose() { - EventHandler.off(window, EVENT_KEY$4); - EventHandler.off(this._dialog, EVENT_KEY$4); - this._backdrop.dispose(); - this._focustrap.deactivate(); - super.dispose(); - } - handleUpdate() { - this._adjustDialog(); - } - _initializeBackDrop() { - return new Backdrop({ - isVisible: Boolean(this._config.backdrop), - isAnimated: this._isAnimated() - }); - } - _initializeFocusTrap() { - return new FocusTrap({ - trapElement: this._element - }); - } - _showElement(relatedTarget) { - if (!document.body.contains(this._element)) { - document.body.append(this._element); - } - this._element.style.display = 'block'; - this._element.removeAttribute('aria-hidden'); - this._element.setAttribute('aria-modal', true); - this._element.setAttribute('role', 'dialog'); - this._element.scrollTop = 0; - const modalBody = SelectorEngine.findOne(SELECTOR_MODAL_BODY, this._dialog); - if (modalBody) { - modalBody.scrollTop = 0; - } - reflow(this._element); - this._element.classList.add(CLASS_NAME_SHOW$4); - const transitionComplete = () => { - if (this._config.focus) { - this._focustrap.activate(); - } - this._isTransitioning = false; - EventHandler.trigger(this._element, EVENT_SHOWN$4, { - relatedTarget - }); - }; - this._queueCallback(transitionComplete, this._dialog, this._isAnimated()); - } - _addEventListeners() { - EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS$1, event => { - if (event.key !== ESCAPE_KEY$1) { - return; - } - if (this._config.keyboard) { - this.hide(); - return; - } - this._triggerBackdropTransition(); - }); - EventHandler.on(window, EVENT_RESIZE$1, () => { - if (this._isShown && !this._isTransitioning) { - this._adjustDialog(); - } - }); - EventHandler.on(this._element, EVENT_MOUSEDOWN_DISMISS, event => { - EventHandler.one(this._element, EVENT_CLICK_DISMISS, event2 => { - if (this._element !== event.target || this._element !== event2.target) { - return; - } - if (this._config.backdrop === 'static') { - this._triggerBackdropTransition(); - return; - } - if (this._config.backdrop) { - this.hide(); - } - }); - }); - } - _hideModal() { - this._element.style.display = 'none'; - this._element.setAttribute('aria-hidden', true); - this._element.removeAttribute('aria-modal'); - this._element.removeAttribute('role'); - this._isTransitioning = false; - this._backdrop.hide(() => { - document.body.classList.remove(CLASS_NAME_OPEN); - this._resetAdjustments(); - this._scrollBar.reset(); - EventHandler.trigger(this._element, EVENT_HIDDEN$4); - }); - } - _isAnimated() { - return this._element.classList.contains(CLASS_NAME_FADE$3); - } - _triggerBackdropTransition() { - const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED$1); - if (hideEvent.defaultPrevented) { - return; - } - const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight; - const initialOverflowY = this._element.style.overflowY; - if (initialOverflowY === 'hidden' || this._element.classList.contains(CLASS_NAME_STATIC)) { - return; - } - if (!isModalOverflowing) { - this._element.style.overflowY = 'hidden'; - } - this._element.classList.add(CLASS_NAME_STATIC); - this._queueCallback(() => { - this._element.classList.remove(CLASS_NAME_STATIC); - this._queueCallback(() => { - this._element.style.overflowY = initialOverflowY; - }, this._dialog); - }, this._dialog); - this._element.focus(); - } - _adjustDialog() { - const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight; - const scrollbarWidth = this._scrollBar.getWidth(); - const isBodyOverflowing = scrollbarWidth > 0; - if (isBodyOverflowing && !isModalOverflowing) { - const property = isRTL() ? 'paddingLeft' : 'paddingRight'; - this._element.style[property] = `${scrollbarWidth}px`; - } - if (!isBodyOverflowing && isModalOverflowing) { - const property = isRTL() ? 'paddingRight' : 'paddingLeft'; - this._element.style[property] = `${scrollbarWidth}px`; - } - } - _resetAdjustments() { - this._element.style.paddingLeft = ''; - this._element.style.paddingRight = ''; - } - static jQueryInterface(config, relatedTarget) { - return this.each(function () { - const data = Modal.getOrCreateInstance(this, config); - if (typeof config !== 'string') { - return; - } - if (typeof data[config] === 'undefined') { - throw new TypeError(`No method named "${config}"`); - } - data[config](relatedTarget); - }); - } - } - EventHandler.on(document, EVENT_CLICK_DATA_API$2, SELECTOR_DATA_TOGGLE$2, function (event) { - const target = SelectorEngine.getElementFromSelector(this); - if (['A', 'AREA'].includes(this.tagName)) { - event.preventDefault(); - } - EventHandler.one(target, EVENT_SHOW$4, showEvent => { - if (showEvent.defaultPrevented) { - return; - } - EventHandler.one(target, EVENT_HIDDEN$4, () => { - if (isVisible(this)) { - this.focus(); - } - }); - }); - const alreadyOpen = SelectorEngine.findOne(OPEN_SELECTOR$1); - if (alreadyOpen) { - Modal.getInstance(alreadyOpen).hide(); - } - const data = Modal.getOrCreateInstance(target); - data.toggle(this); - }); - enableDismissTrigger(Modal); - defineJQueryPlugin(Modal); - const NAME$6 = 'offcanvas'; - const DATA_KEY$3 = 'bs.offcanvas'; - const EVENT_KEY$3 = `.${DATA_KEY$3}`; - const DATA_API_KEY$1 = '.data-api'; - const EVENT_LOAD_DATA_API$2 = `load${EVENT_KEY$3}${DATA_API_KEY$1}`; - const ESCAPE_KEY = 'Escape'; - const CLASS_NAME_SHOW$3 = 'show'; - const CLASS_NAME_SHOWING$1 = 'showing'; - const CLASS_NAME_HIDING = 'hiding'; - const CLASS_NAME_BACKDROP = 'offcanvas-backdrop'; - const OPEN_SELECTOR = '.offcanvas.show'; - const EVENT_SHOW$3 = `show${EVENT_KEY$3}`; - const EVENT_SHOWN$3 = `shown${EVENT_KEY$3}`; - const EVENT_HIDE$3 = `hide${EVENT_KEY$3}`; - const EVENT_HIDE_PREVENTED = `hidePrevented${EVENT_KEY$3}`; - const EVENT_HIDDEN$3 = `hidden${EVENT_KEY$3}`; - const EVENT_RESIZE = `resize${EVENT_KEY$3}`; - const EVENT_CLICK_DATA_API$1 = `click${EVENT_KEY$3}${DATA_API_KEY$1}`; - const EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY$3}`; - const SELECTOR_DATA_TOGGLE$1 = '[data-bs-toggle="offcanvas"]'; - const Default$5 = { - backdrop: true, - keyboard: true, - scroll: false - }; - const DefaultType$5 = { - backdrop: '(boolean|string)', - keyboard: 'boolean', - scroll: 'boolean' - }; - class Offcanvas extends BaseComponent { - constructor(element, config) { - super(element, config); - this._isShown = false; - this._backdrop = this._initializeBackDrop(); - this._focustrap = this._initializeFocusTrap(); - this._addEventListeners(); - } - static get Default() { - return Default$5; - } - static get DefaultType() { - return DefaultType$5; - } - static get NAME() { - return NAME$6; - } - toggle(relatedTarget) { - return this._isShown ? this.hide() : this.show(relatedTarget); - } - show(relatedTarget) { - if (this._isShown) { - return; - } - const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$3, { - relatedTarget - }); - if (showEvent.defaultPrevented) { - return; - } - this._isShown = true; - this._backdrop.show(); - if (!this._config.scroll) { - new ScrollBarHelper().hide(); - } - this._element.setAttribute('aria-modal', true); - this._element.setAttribute('role', 'dialog'); - this._element.classList.add(CLASS_NAME_SHOWING$1); - const completeCallBack = () => { - if (!this._config.scroll || this._config.backdrop) { - this._focustrap.activate(); - } - this._element.classList.add(CLASS_NAME_SHOW$3); - this._element.classList.remove(CLASS_NAME_SHOWING$1); - EventHandler.trigger(this._element, EVENT_SHOWN$3, { - relatedTarget - }); - }; - this._queueCallback(completeCallBack, this._element, true); - } - hide() { - if (!this._isShown) { - return; - } - const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$3); - if (hideEvent.defaultPrevented) { - return; - } - this._focustrap.deactivate(); - this._element.blur(); - this._isShown = false; - this._element.classList.add(CLASS_NAME_HIDING); - this._backdrop.hide(); - const completeCallback = () => { - this._element.classList.remove(CLASS_NAME_SHOW$3, CLASS_NAME_HIDING); - this._element.removeAttribute('aria-modal'); - this._element.removeAttribute('role'); - if (!this._config.scroll) { - new ScrollBarHelper().reset(); - } - EventHandler.trigger(this._element, EVENT_HIDDEN$3); - }; - this._queueCallback(completeCallback, this._element, true); - } - dispose() { - this._backdrop.dispose(); - this._focustrap.deactivate(); - super.dispose(); - } - _initializeBackDrop() { - const clickCallback = () => { - if (this._config.backdrop === 'static') { - EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED); - return; - } - this.hide(); - }; - const isVisible = Boolean(this._config.backdrop); - return new Backdrop({ - className: CLASS_NAME_BACKDROP, - isVisible, - isAnimated: true, - rootElement: this._element.parentNode, - clickCallback: isVisible ? clickCallback : null - }); - } - _initializeFocusTrap() { - return new FocusTrap({ - trapElement: this._element - }); - } - _addEventListeners() { - EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS, event => { - if (event.key !== ESCAPE_KEY) { - return; - } - if (this._config.keyboard) { - this.hide(); - return; - } - EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED); - }); - } - static jQueryInterface(config) { - return this.each(function () { - const data = Offcanvas.getOrCreateInstance(this, config); - if (typeof config !== 'string') { - return; - } - if (data[config] === undefined || config.startsWith('_') || config === 'constructor') { - throw new TypeError(`No method named "${config}"`); - } - data[config](this); - }); - } - } - EventHandler.on(document, EVENT_CLICK_DATA_API$1, SELECTOR_DATA_TOGGLE$1, function (event) { - const target = SelectorEngine.getElementFromSelector(this); - if (['A', 'AREA'].includes(this.tagName)) { - event.preventDefault(); - } - if (isDisabled(this)) { - return; - } - EventHandler.one(target, EVENT_HIDDEN$3, () => { - if (isVisible(this)) { - this.focus(); - } - }); - const alreadyOpen = SelectorEngine.findOne(OPEN_SELECTOR); - if (alreadyOpen && alreadyOpen !== target) { - Offcanvas.getInstance(alreadyOpen).hide(); - } - const data = Offcanvas.getOrCreateInstance(target); - data.toggle(this); - }); - EventHandler.on(window, EVENT_LOAD_DATA_API$2, () => { - for (const selector of SelectorEngine.find(OPEN_SELECTOR)) { - Offcanvas.getOrCreateInstance(selector).show(); - } - }); - EventHandler.on(window, EVENT_RESIZE, () => { - for (const element of SelectorEngine.find('[aria-modal][class*=show][class*=offcanvas-]')) { - if (getComputedStyle(element).position !== 'fixed') { - Offcanvas.getOrCreateInstance(element).hide(); - } - } - }); - enableDismissTrigger(Offcanvas); - defineJQueryPlugin(Offcanvas); - const ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i; - const DefaultAllowlist = { - '*': ['class', 'dir', 'id', 'lang', 'role', ARIA_ATTRIBUTE_PATTERN], - a: ['target', 'href', 'title', 'rel'], - area: [], - b: [], - br: [], - col: [], - code: [], - div: [], - em: [], - hr: [], - h1: [], - h2: [], - h3: [], - h4: [], - h5: [], - h6: [], - i: [], - img: ['src', 'srcset', 'alt', 'title', 'width', 'height'], - li: [], - ol: [], - p: [], - pre: [], - s: [], - small: [], - span: [], - sub: [], - sup: [], - strong: [], - u: [], - ul: [] - }; - const uriAttributes = new Set(['background', 'cite', 'href', 'itemtype', 'longdesc', 'poster', 'src', 'xlink:href']); - const SAFE_URL_PATTERN = /^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:/?#]*(?:[/?#]|$))/i; - const allowedAttribute = (attribute, allowedAttributeList) => { - const attributeName = attribute.nodeName.toLowerCase(); - if (allowedAttributeList.includes(attributeName)) { - if (uriAttributes.has(attributeName)) { - return Boolean(SAFE_URL_PATTERN.test(attribute.nodeValue)); - } - return true; - } - return allowedAttributeList.filter(attributeRegex => attributeRegex instanceof RegExp).some(regex => regex.test(attributeName)); - }; - function sanitizeHtml(unsafeHtml, allowList, sanitizeFunction) { - if (!unsafeHtml.length) { - return unsafeHtml; - } - if (sanitizeFunction && typeof sanitizeFunction === 'function') { - return sanitizeFunction(unsafeHtml); - } - const domParser = new window.DOMParser(); - const createdDocument = domParser.parseFromString(unsafeHtml, 'text/html'); - const elements = [].concat(...createdDocument.body.querySelectorAll('*')); - for (const element of elements) { - const elementName = element.nodeName.toLowerCase(); - if (!Object.keys(allowList).includes(elementName)) { - element.remove(); - continue; - } - const attributeList = [].concat(...element.attributes); - const allowedAttributes = [].concat(allowList['*'] || [], allowList[elementName] || []); - for (const attribute of attributeList) { - if (!allowedAttribute(attribute, allowedAttributes)) { - element.removeAttribute(attribute.nodeName); - } - } - } - return createdDocument.body.innerHTML; - } - const NAME$5 = 'TemplateFactory'; - const Default$4 = { - allowList: DefaultAllowlist, - content: {}, - extraClass: '', - html: false, - sanitize: true, - sanitizeFn: null, - template: '
    ' - }; - const DefaultType$4 = { - allowList: 'object', - content: 'object', - extraClass: '(string|function)', - html: 'boolean', - sanitize: 'boolean', - sanitizeFn: '(null|function)', - template: 'string' - }; - const DefaultContentType = { - entry: '(string|element|function|null)', - selector: '(string|element)' - }; - class TemplateFactory extends Config { - constructor(config) { - super(); - this._config = this._getConfig(config); - } - static get Default() { - return Default$4; - } - static get DefaultType() { - return DefaultType$4; - } - static get NAME() { - return NAME$5; - } - getContent() { - return Object.values(this._config.content).map(config => this._resolvePossibleFunction(config)).filter(Boolean); - } - hasContent() { - return this.getContent().length > 0; - } - changeContent(content) { - this._checkContent(content); - this._config.content = { - ...this._config.content, - ...content - }; - return this; - } - toHtml() { - const templateWrapper = document.createElement('div'); - templateWrapper.innerHTML = this._maybeSanitize(this._config.template); - for (const [selector, text] of Object.entries(this._config.content)) { - this._setContent(templateWrapper, text, selector); - } - const template = templateWrapper.children[0]; - const extraClass = this._resolvePossibleFunction(this._config.extraClass); - if (extraClass) { - template.classList.add(...extraClass.split(' ')); - } - return template; - } - _typeCheckConfig(config) { - super._typeCheckConfig(config); - this._checkContent(config.content); - } - _checkContent(arg) { - for (const [selector, content] of Object.entries(arg)) { - super._typeCheckConfig({ - selector, - entry: content - }, DefaultContentType); - } - } - _setContent(template, content, selector) { - const templateElement = SelectorEngine.findOne(selector, template); - if (!templateElement) { - return; - } - content = this._resolvePossibleFunction(content); - if (!content) { - templateElement.remove(); - return; - } - if (isElement(content)) { - this._putElementInTemplate(getElement(content), templateElement); - return; - } - if (this._config.html) { - templateElement.innerHTML = this._maybeSanitize(content); - return; - } - templateElement.textContent = content; - } - _maybeSanitize(arg) { - return this._config.sanitize ? sanitizeHtml(arg, this._config.allowList, this._config.sanitizeFn) : arg; - } - _resolvePossibleFunction(arg) { - return execute(arg, [this]); - } - _putElementInTemplate(element, templateElement) { - if (this._config.html) { - templateElement.innerHTML = ''; - templateElement.append(element); - return; - } - templateElement.textContent = element.textContent; - } - } - const NAME$4 = 'tooltip'; - const DISALLOWED_ATTRIBUTES = new Set(['sanitize', 'allowList', 'sanitizeFn']); - const CLASS_NAME_FADE$2 = 'fade'; - const CLASS_NAME_MODAL = 'modal'; - const CLASS_NAME_SHOW$2 = 'show'; - const SELECTOR_TOOLTIP_INNER = '.tooltip-inner'; - const SELECTOR_MODAL = `.${CLASS_NAME_MODAL}`; - const EVENT_MODAL_HIDE = 'hide.bs.modal'; - const TRIGGER_HOVER = 'hover'; - const TRIGGER_FOCUS = 'focus'; - const TRIGGER_CLICK = 'click'; - const TRIGGER_MANUAL = 'manual'; - const EVENT_HIDE$2 = 'hide'; - const EVENT_HIDDEN$2 = 'hidden'; - const EVENT_SHOW$2 = 'show'; - const EVENT_SHOWN$2 = 'shown'; - const EVENT_INSERTED = 'inserted'; - const EVENT_CLICK$1 = 'click'; - const EVENT_FOCUSIN$1 = 'focusin'; - const EVENT_FOCUSOUT$1 = 'focusout'; - const EVENT_MOUSEENTER = 'mouseenter'; - const EVENT_MOUSELEAVE = 'mouseleave'; - const AttachmentMap = { - AUTO: 'auto', - TOP: 'top', - RIGHT: isRTL() ? 'left' : 'right', - BOTTOM: 'bottom', - LEFT: isRTL() ? 'right' : 'left' - }; - const Default$3 = { - allowList: DefaultAllowlist, - animation: true, - boundary: 'clippingParents', - container: false, - customClass: '', - delay: 0, - fallbackPlacements: ['top', 'right', 'bottom', 'left'], - html: false, - offset: [0, 6], - placement: 'top', - popperConfig: null, - sanitize: true, - sanitizeFn: null, - selector: false, - template: '', - title: '', - trigger: 'hover focus' - }; - const DefaultType$3 = { - allowList: 'object', - animation: 'boolean', - boundary: '(string|element)', - container: '(string|element|boolean)', - customClass: '(string|function)', - delay: '(number|object)', - fallbackPlacements: 'array', - html: 'boolean', - offset: '(array|string|function)', - placement: '(string|function)', - popperConfig: '(null|object|function)', - sanitize: 'boolean', - sanitizeFn: '(null|function)', - selector: '(string|boolean)', - template: 'string', - title: '(string|element|function)', - trigger: 'string' - }; - class Tooltip extends BaseComponent { - constructor(element, config) { - if (typeof Popper === 'undefined') { - throw new TypeError('Bootstrap\'s tooltips require Popper (https://popper.js.org)'); - } - super(element, config); - this._isEnabled = true; - this._timeout = 0; - this._isHovered = null; - this._activeTrigger = {}; - this._popper = null; - this._templateFactory = null; - this._newContent = null; - this.tip = null; - this._setListeners(); - if (!this._config.selector) { - this._fixTitle(); - } - } - static get Default() { - return Default$3; - } - static get DefaultType() { - return DefaultType$3; - } - static get NAME() { - return NAME$4; - } - enable() { - this._isEnabled = true; - } - disable() { - this._isEnabled = false; - } - toggleEnabled() { - this._isEnabled = !this._isEnabled; - } - toggle() { - if (!this._isEnabled) { - return; - } - this._activeTrigger.click = !this._activeTrigger.click; - if (this._isShown()) { - this._leave(); - return; - } - this._enter(); - } - dispose() { - clearTimeout(this._timeout); - EventHandler.off(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler); - if (this._element.getAttribute('data-bs-original-title')) { - this._element.setAttribute('title', this._element.getAttribute('data-bs-original-title')); - } - this._disposePopper(); - super.dispose(); - } - show() { - if (this._element.style.display === 'none') { - throw new Error('Please use show on visible elements'); - } - if (!(this._isWithContent() && this._isEnabled)) { - return; - } - const showEvent = EventHandler.trigger(this._element, this.constructor.eventName(EVENT_SHOW$2)); - const shadowRoot = findShadowRoot(this._element); - const isInTheDom = (shadowRoot || this._element.ownerDocument.documentElement).contains(this._element); - if (showEvent.defaultPrevented || !isInTheDom) { - return; - } - this._disposePopper(); - const tip = this._getTipElement(); - this._element.setAttribute('aria-describedby', tip.getAttribute('id')); - const { - container - } = this._config; - if (!this._element.ownerDocument.documentElement.contains(this.tip)) { - container.append(tip); - EventHandler.trigger(this._element, this.constructor.eventName(EVENT_INSERTED)); - } - this._popper = this._createPopper(tip); - tip.classList.add(CLASS_NAME_SHOW$2); - if ('ontouchstart' in document.documentElement) { - for (const element of [].concat(...document.body.children)) { - EventHandler.on(element, 'mouseover', noop); - } - } - const complete = () => { - EventHandler.trigger(this._element, this.constructor.eventName(EVENT_SHOWN$2)); - if (this._isHovered === false) { - this._leave(); - } - this._isHovered = false; - }; - this._queueCallback(complete, this.tip, this._isAnimated()); - } - hide() { - if (!this._isShown()) { - return; - } - const hideEvent = EventHandler.trigger(this._element, this.constructor.eventName(EVENT_HIDE$2)); - if (hideEvent.defaultPrevented) { - return; - } - const tip = this._getTipElement(); - tip.classList.remove(CLASS_NAME_SHOW$2); - if ('ontouchstart' in document.documentElement) { - for (const element of [].concat(...document.body.children)) { - EventHandler.off(element, 'mouseover', noop); - } - } - this._activeTrigger[TRIGGER_CLICK] = false; - this._activeTrigger[TRIGGER_FOCUS] = false; - this._activeTrigger[TRIGGER_HOVER] = false; - this._isHovered = null; - const complete = () => { - if (this._isWithActiveTrigger()) { - return; - } - if (!this._isHovered) { - this._disposePopper(); - } - this._element.removeAttribute('aria-describedby'); - EventHandler.trigger(this._element, this.constructor.eventName(EVENT_HIDDEN$2)); - }; - this._queueCallback(complete, this.tip, this._isAnimated()); - } - update() { - if (this._popper) { - this._popper.update(); - } - } - _isWithContent() { - return Boolean(this._getTitle()); - } - _getTipElement() { - if (!this.tip) { - this.tip = this._createTipElement(this._newContent || this._getContentForTemplate()); - } - return this.tip; - } - _createTipElement(content) { - const tip = this._getTemplateFactory(content).toHtml(); - if (!tip) { - return null; - } - tip.classList.remove(CLASS_NAME_FADE$2, CLASS_NAME_SHOW$2); - tip.classList.add(`bs-${this.constructor.NAME}-auto`); - const tipId = getUID(this.constructor.NAME).toString(); - tip.setAttribute('id', tipId); - if (this._isAnimated()) { - tip.classList.add(CLASS_NAME_FADE$2); - } - return tip; - } - setContent(content) { - this._newContent = content; - if (this._isShown()) { - this._disposePopper(); - this.show(); - } - } - _getTemplateFactory(content) { - if (this._templateFactory) { - this._templateFactory.changeContent(content); - } else { - this._templateFactory = new TemplateFactory({ - ...this._config, - content, - extraClass: this._resolvePossibleFunction(this._config.customClass) - }); - } - return this._templateFactory; - } - _getContentForTemplate() { - return { - [SELECTOR_TOOLTIP_INNER]: this._getTitle() - }; - } - _getTitle() { - return this._resolvePossibleFunction(this._config.title) || this._element.getAttribute('data-bs-original-title'); - } - _initializeOnDelegatedTarget(event) { - return this.constructor.getOrCreateInstance(event.delegateTarget, this._getDelegateConfig()); - } - _isAnimated() { - return this._config.animation || this.tip && this.tip.classList.contains(CLASS_NAME_FADE$2); - } - _isShown() { - return this.tip && this.tip.classList.contains(CLASS_NAME_SHOW$2); - } - _createPopper(tip) { - const placement = execute(this._config.placement, [this, tip, this._element]); - const attachment = AttachmentMap[placement.toUpperCase()]; - return createPopper(this._element, tip, this._getPopperConfig(attachment)); - } - _getOffset() { - const { - offset - } = this._config; - if (typeof offset === 'string') { - return offset.split(',').map(value => Number.parseInt(value, 10)); - } - if (typeof offset === 'function') { - return popperData => offset(popperData, this._element); - } - return offset; - } - _resolvePossibleFunction(arg) { - return execute(arg, [this._element]); - } - _getPopperConfig(attachment) { - const defaultBsPopperConfig = { - placement: attachment, - modifiers: [{ - name: 'flip', - options: { - fallbackPlacements: this._config.fallbackPlacements - } - }, { - name: 'offset', - options: { - offset: this._getOffset() - } - }, { - name: 'preventOverflow', - options: { - boundary: this._config.boundary - } - }, { - name: 'arrow', - options: { - element: `.${this.constructor.NAME}-arrow` - } - }, { - name: 'preSetPlacement', - enabled: true, - phase: 'beforeMain', - fn: data => { - this._getTipElement().setAttribute('data-popper-placement', data.state.placement); - } - }] - }; - return { - ...defaultBsPopperConfig, - ...execute(this._config.popperConfig, [defaultBsPopperConfig]) - }; - } - _setListeners() { - const triggers = this._config.trigger.split(' '); - for (const trigger of triggers) { - if (trigger === 'click') { - EventHandler.on(this._element, this.constructor.eventName(EVENT_CLICK$1), this._config.selector, event => { - const context = this._initializeOnDelegatedTarget(event); - context.toggle(); - }); - } else if (trigger !== TRIGGER_MANUAL) { - const eventIn = trigger === TRIGGER_HOVER ? this.constructor.eventName(EVENT_MOUSEENTER) : this.constructor.eventName(EVENT_FOCUSIN$1); - const eventOut = trigger === TRIGGER_HOVER ? this.constructor.eventName(EVENT_MOUSELEAVE) : this.constructor.eventName(EVENT_FOCUSOUT$1); - EventHandler.on(this._element, eventIn, this._config.selector, event => { - const context = this._initializeOnDelegatedTarget(event); - context._activeTrigger[event.type === 'focusin' ? TRIGGER_FOCUS : TRIGGER_HOVER] = true; - context._enter(); - }); - EventHandler.on(this._element, eventOut, this._config.selector, event => { - const context = this._initializeOnDelegatedTarget(event); - context._activeTrigger[event.type === 'focusout' ? TRIGGER_FOCUS : TRIGGER_HOVER] = context._element.contains(event.relatedTarget); - context._leave(); - }); - } - } - this._hideModalHandler = () => { - if (this._element) { - this.hide(); - } - }; - EventHandler.on(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler); - } - _fixTitle() { - const title = this._element.getAttribute('title'); - if (!title) { - return; - } - if (!this._element.getAttribute('aria-label') && !this._element.textContent.trim()) { - this._element.setAttribute('aria-label', title); - } - this._element.setAttribute('data-bs-original-title', title); - this._element.removeAttribute('title'); - } - _enter() { - if (this._isShown() || this._isHovered) { - this._isHovered = true; - return; - } - this._isHovered = true; - this._setTimeout(() => { - if (this._isHovered) { - this.show(); - } - }, this._config.delay.show); - } - _leave() { - if (this._isWithActiveTrigger()) { - return; - } - this._isHovered = false; - this._setTimeout(() => { - if (!this._isHovered) { - this.hide(); - } - }, this._config.delay.hide); - } - _setTimeout(handler, timeout) { - clearTimeout(this._timeout); - this._timeout = setTimeout(handler, timeout); - } - _isWithActiveTrigger() { - return Object.values(this._activeTrigger).includes(true); - } - _getConfig(config) { - const dataAttributes = Manipulator.getDataAttributes(this._element); - for (const dataAttribute of Object.keys(dataAttributes)) { - if (DISALLOWED_ATTRIBUTES.has(dataAttribute)) { - delete dataAttributes[dataAttribute]; - } - } - config = { - ...dataAttributes, - ...(typeof config === 'object' && config ? config : {}) - }; - config = this._mergeConfigObj(config); - config = this._configAfterMerge(config); - this._typeCheckConfig(config); - return config; - } - _configAfterMerge(config) { - config.container = config.container === false ? document.body : getElement(config.container); - if (typeof config.delay === 'number') { - config.delay = { - show: config.delay, - hide: config.delay - }; - } - if (typeof config.title === 'number') { - config.title = config.title.toString(); - } - if (typeof config.content === 'number') { - config.content = config.content.toString(); - } - return config; - } - _getDelegateConfig() { - const config = {}; - for (const [key, value] of Object.entries(this._config)) { - if (this.constructor.Default[key] !== value) { - config[key] = value; - } - } - config.selector = false; - config.trigger = 'manual'; - return config; - } - _disposePopper() { - if (this._popper) { - this._popper.destroy(); - this._popper = null; - } - if (this.tip) { - this.tip.remove(); - this.tip = null; - } - } - static jQueryInterface(config) { - return this.each(function () { - const data = Tooltip.getOrCreateInstance(this, config); - if (typeof config !== 'string') { - return; - } - if (typeof data[config] === 'undefined') { - throw new TypeError(`No method named "${config}"`); - } - data[config](); - }); - } - } - defineJQueryPlugin(Tooltip); - const NAME$3 = 'popover'; - const SELECTOR_TITLE = '.popover-header'; - const SELECTOR_CONTENT = '.popover-body'; - const Default$2 = { - ...Tooltip.Default, - content: '', - offset: [0, 8], - placement: 'right', - template: '', - trigger: 'click' - }; - const DefaultType$2 = { - ...Tooltip.DefaultType, - content: '(null|string|element|function)' - }; - class Popover extends Tooltip { - static get Default() { - return Default$2; - } - static get DefaultType() { - return DefaultType$2; - } - static get NAME() { - return NAME$3; - } - _isWithContent() { - return this._getTitle() || this._getContent(); - } - _getContentForTemplate() { - return { - [SELECTOR_TITLE]: this._getTitle(), - [SELECTOR_CONTENT]: this._getContent() - }; - } - _getContent() { - return this._resolvePossibleFunction(this._config.content); - } - static jQueryInterface(config) { - return this.each(function () { - const data = Popover.getOrCreateInstance(this, config); - if (typeof config !== 'string') { - return; - } - if (typeof data[config] === 'undefined') { - throw new TypeError(`No method named "${config}"`); - } - data[config](); - }); - } - } - defineJQueryPlugin(Popover); - const NAME$2 = 'scrollspy'; - const DATA_KEY$2 = 'bs.scrollspy'; - const EVENT_KEY$2 = `.${DATA_KEY$2}`; - const DATA_API_KEY = '.data-api'; - const EVENT_ACTIVATE = `activate${EVENT_KEY$2}`; - const EVENT_CLICK = `click${EVENT_KEY$2}`; - const EVENT_LOAD_DATA_API$1 = `load${EVENT_KEY$2}${DATA_API_KEY}`; - const CLASS_NAME_DROPDOWN_ITEM = 'dropdown-item'; - const CLASS_NAME_ACTIVE$1 = 'active'; - const SELECTOR_DATA_SPY = '[data-bs-spy="scroll"]'; - const SELECTOR_TARGET_LINKS = '[href]'; - const SELECTOR_NAV_LIST_GROUP = '.nav, .list-group'; - const SELECTOR_NAV_LINKS = '.nav-link'; - const SELECTOR_NAV_ITEMS = '.nav-item'; - const SELECTOR_LIST_ITEMS = '.list-group-item'; - const SELECTOR_LINK_ITEMS = `${SELECTOR_NAV_LINKS}, ${SELECTOR_NAV_ITEMS} > ${SELECTOR_NAV_LINKS}, ${SELECTOR_LIST_ITEMS}`; - const SELECTOR_DROPDOWN = '.dropdown'; - const SELECTOR_DROPDOWN_TOGGLE$1 = '.dropdown-toggle'; - const Default$1 = { - offset: null, - rootMargin: '0px 0px -25%', - smoothScroll: false, - target: null, - threshold: [0.1, 0.5, 1] - }; - const DefaultType$1 = { - offset: '(number|null)', - rootMargin: 'string', - smoothScroll: 'boolean', - target: 'element', - threshold: 'array' - }; - class ScrollSpy extends BaseComponent { - constructor(element, config) { - super(element, config); - this._targetLinks = new Map(); - this._observableSections = new Map(); - this._rootElement = getComputedStyle(this._element).overflowY === 'visible' ? null : this._element; - this._activeTarget = null; - this._observer = null; - this._previousScrollData = { - visibleEntryTop: 0, - parentScrollTop: 0 - }; - this.refresh(); - } - static get Default() { - return Default$1; - } - static get DefaultType() { - return DefaultType$1; - } - static get NAME() { - return NAME$2; - } - refresh() { - this._initializeTargetsAndObservables(); - this._maybeEnableSmoothScroll(); - if (this._observer) { - this._observer.disconnect(); - } else { - this._observer = this._getNewObserver(); - } - for (const section of this._observableSections.values()) { - this._observer.observe(section); - } - } - dispose() { - this._observer.disconnect(); - super.dispose(); - } - _configAfterMerge(config) { - config.target = getElement(config.target) || document.body; - config.rootMargin = config.offset ? `${config.offset}px 0px -30%` : config.rootMargin; - if (typeof config.threshold === 'string') { - config.threshold = config.threshold.split(',').map(value => Number.parseFloat(value)); - } - return config; - } - _maybeEnableSmoothScroll() { - if (!this._config.smoothScroll) { - return; - } - EventHandler.off(this._config.target, EVENT_CLICK); - EventHandler.on(this._config.target, EVENT_CLICK, SELECTOR_TARGET_LINKS, event => { - const observableSection = this._observableSections.get(event.target.hash); - if (observableSection) { - event.preventDefault(); - const root = this._rootElement || window; - const height = observableSection.offsetTop - this._element.offsetTop; - if (root.scrollTo) { - root.scrollTo({ - top: height, - behavior: 'smooth' - }); - return; - } - root.scrollTop = height; - } - }); - } - _getNewObserver() { - const options = { - root: this._rootElement, - threshold: this._config.threshold, - rootMargin: this._config.rootMargin - }; - return new IntersectionObserver(entries => this._observerCallback(entries), options); - } - _observerCallback(entries) { - const targetElement = entry => this._targetLinks.get(`#${entry.target.id}`); - const activate = entry => { - this._previousScrollData.visibleEntryTop = entry.target.offsetTop; - this._process(targetElement(entry)); - }; - const parentScrollTop = (this._rootElement || document.documentElement).scrollTop; - const userScrollsDown = parentScrollTop >= this._previousScrollData.parentScrollTop; - this._previousScrollData.parentScrollTop = parentScrollTop; - for (const entry of entries) { - if (!entry.isIntersecting) { - this._activeTarget = null; - this._clearActiveClass(targetElement(entry)); - continue; - } - const entryIsLowerThanPrevious = entry.target.offsetTop >= this._previousScrollData.visibleEntryTop; - if (userScrollsDown && entryIsLowerThanPrevious) { - activate(entry); - if (!parentScrollTop) { - return; - } - continue; - } - if (!userScrollsDown && !entryIsLowerThanPrevious) { - activate(entry); - } - } - } - _initializeTargetsAndObservables() { - this._targetLinks = new Map(); - this._observableSections = new Map(); - const targetLinks = SelectorEngine.find(SELECTOR_TARGET_LINKS, this._config.target); - for (const anchor of targetLinks) { - if (!anchor.hash || isDisabled(anchor)) { - continue; - } - const observableSection = SelectorEngine.findOne(decodeURI(anchor.hash), this._element); - if (isVisible(observableSection)) { - this._targetLinks.set(decodeURI(anchor.hash), anchor); - this._observableSections.set(anchor.hash, observableSection); - } - } - } - _process(target) { - if (this._activeTarget === target) { - return; - } - this._clearActiveClass(this._config.target); - this._activeTarget = target; - target.classList.add(CLASS_NAME_ACTIVE$1); - this._activateParents(target); - EventHandler.trigger(this._element, EVENT_ACTIVATE, { - relatedTarget: target - }); - } - _activateParents(target) { - if (target.classList.contains(CLASS_NAME_DROPDOWN_ITEM)) { - SelectorEngine.findOne(SELECTOR_DROPDOWN_TOGGLE$1, target.closest(SELECTOR_DROPDOWN)).classList.add(CLASS_NAME_ACTIVE$1); - return; - } - for (const listGroup of SelectorEngine.parents(target, SELECTOR_NAV_LIST_GROUP)) { - for (const item of SelectorEngine.prev(listGroup, SELECTOR_LINK_ITEMS)) { - item.classList.add(CLASS_NAME_ACTIVE$1); - } - } - } - _clearActiveClass(parent) { - parent.classList.remove(CLASS_NAME_ACTIVE$1); - const activeNodes = SelectorEngine.find(`${SELECTOR_TARGET_LINKS}.${CLASS_NAME_ACTIVE$1}`, parent); - for (const node of activeNodes) { - node.classList.remove(CLASS_NAME_ACTIVE$1); - } - } - static jQueryInterface(config) { - return this.each(function () { - const data = ScrollSpy.getOrCreateInstance(this, config); - if (typeof config !== 'string') { - return; - } - if (data[config] === undefined || config.startsWith('_') || config === 'constructor') { - throw new TypeError(`No method named "${config}"`); - } - data[config](); - }); - } - } - EventHandler.on(window, EVENT_LOAD_DATA_API$1, () => { - for (const spy of SelectorEngine.find(SELECTOR_DATA_SPY)) { - ScrollSpy.getOrCreateInstance(spy); - } - }); - defineJQueryPlugin(ScrollSpy); - const NAME$1 = 'tab'; - const DATA_KEY$1 = 'bs.tab'; - const EVENT_KEY$1 = `.${DATA_KEY$1}`; - const EVENT_HIDE$1 = `hide${EVENT_KEY$1}`; - const EVENT_HIDDEN$1 = `hidden${EVENT_KEY$1}`; - const EVENT_SHOW$1 = `show${EVENT_KEY$1}`; - const EVENT_SHOWN$1 = `shown${EVENT_KEY$1}`; - const EVENT_CLICK_DATA_API = `click${EVENT_KEY$1}`; - const EVENT_KEYDOWN = `keydown${EVENT_KEY$1}`; - const EVENT_LOAD_DATA_API = `load${EVENT_KEY$1}`; - const ARROW_LEFT_KEY = 'ArrowLeft'; - const ARROW_RIGHT_KEY = 'ArrowRight'; - const ARROW_UP_KEY = 'ArrowUp'; - const ARROW_DOWN_KEY = 'ArrowDown'; - const HOME_KEY = 'Home'; - const END_KEY = 'End'; - const CLASS_NAME_ACTIVE = 'active'; - const CLASS_NAME_FADE$1 = 'fade'; - const CLASS_NAME_SHOW$1 = 'show'; - const CLASS_DROPDOWN = 'dropdown'; - const SELECTOR_DROPDOWN_TOGGLE = '.dropdown-toggle'; - const SELECTOR_DROPDOWN_MENU = '.dropdown-menu'; - const NOT_SELECTOR_DROPDOWN_TOGGLE = ':not(.dropdown-toggle)'; - const SELECTOR_TAB_PANEL = '.list-group, .nav, [role="tablist"]'; - const SELECTOR_OUTER = '.nav-item, .list-group-item'; - const SELECTOR_INNER = `.nav-link${NOT_SELECTOR_DROPDOWN_TOGGLE}, .list-group-item${NOT_SELECTOR_DROPDOWN_TOGGLE}, [role="tab"]${NOT_SELECTOR_DROPDOWN_TOGGLE}`; - const SELECTOR_DATA_TOGGLE = '[data-bs-toggle="tab"], [data-bs-toggle="pill"], [data-bs-toggle="list"]'; - const SELECTOR_INNER_ELEM = `${SELECTOR_INNER}, ${SELECTOR_DATA_TOGGLE}`; - const SELECTOR_DATA_TOGGLE_ACTIVE = `.${CLASS_NAME_ACTIVE}[data-bs-toggle="tab"], .${CLASS_NAME_ACTIVE}[data-bs-toggle="pill"], .${CLASS_NAME_ACTIVE}[data-bs-toggle="list"]`; - class Tab extends BaseComponent { - constructor(element) { - super(element); - this._parent = this._element.closest(SELECTOR_TAB_PANEL); - if (!this._parent) { - return; - } - this._setInitialAttributes(this._parent, this._getChildren()); - EventHandler.on(this._element, EVENT_KEYDOWN, event => this._keydown(event)); - } - static get NAME() { - return NAME$1; - } - show() { - const innerElem = this._element; - if (this._elemIsActive(innerElem)) { - return; - } - const active = this._getActiveElem(); - const hideEvent = active ? EventHandler.trigger(active, EVENT_HIDE$1, { - relatedTarget: innerElem - }) : null; - const showEvent = EventHandler.trigger(innerElem, EVENT_SHOW$1, { - relatedTarget: active - }); - if (showEvent.defaultPrevented || hideEvent && hideEvent.defaultPrevented) { - return; - } - this._deactivate(active, innerElem); - this._activate(innerElem, active); - } - _activate(element, relatedElem) { - if (!element) { - return; - } - element.classList.add(CLASS_NAME_ACTIVE); - this._activate(SelectorEngine.getElementFromSelector(element)); - const complete = () => { - if (element.getAttribute('role') !== 'tab') { - element.classList.add(CLASS_NAME_SHOW$1); - return; - } - element.removeAttribute('tabindex'); - element.setAttribute('aria-selected', true); - this._toggleDropDown(element, true); - EventHandler.trigger(element, EVENT_SHOWN$1, { - relatedTarget: relatedElem - }); - }; - this._queueCallback(complete, element, element.classList.contains(CLASS_NAME_FADE$1)); - } - _deactivate(element, relatedElem) { - if (!element) { - return; - } - element.classList.remove(CLASS_NAME_ACTIVE); - element.blur(); - this._deactivate(SelectorEngine.getElementFromSelector(element)); - const complete = () => { - if (element.getAttribute('role') !== 'tab') { - element.classList.remove(CLASS_NAME_SHOW$1); - return; - } - element.setAttribute('aria-selected', false); - element.setAttribute('tabindex', '-1'); - this._toggleDropDown(element, false); - EventHandler.trigger(element, EVENT_HIDDEN$1, { - relatedTarget: relatedElem - }); - }; - this._queueCallback(complete, element, element.classList.contains(CLASS_NAME_FADE$1)); - } - _keydown(event) { - if (![ARROW_LEFT_KEY, ARROW_RIGHT_KEY, ARROW_UP_KEY, ARROW_DOWN_KEY, HOME_KEY, END_KEY].includes(event.key)) { - return; - } - event.stopPropagation(); - event.preventDefault(); - const children = this._getChildren().filter(element => !isDisabled(element)); - let nextActiveElement; - if ([HOME_KEY, END_KEY].includes(event.key)) { - nextActiveElement = children[event.key === HOME_KEY ? 0 : children.length - 1]; - } else { - const isNext = [ARROW_RIGHT_KEY, ARROW_DOWN_KEY].includes(event.key); - nextActiveElement = getNextActiveElement(children, event.target, isNext, true); - } - if (nextActiveElement) { - nextActiveElement.focus({ - preventScroll: true - }); - Tab.getOrCreateInstance(nextActiveElement).show(); - } - } - _getChildren() { - return SelectorEngine.find(SELECTOR_INNER_ELEM, this._parent); - } - _getActiveElem() { - return this._getChildren().find(child => this._elemIsActive(child)) || null; - } - _setInitialAttributes(parent, children) { - this._setAttributeIfNotExists(parent, 'role', 'tablist'); - for (const child of children) { - this._setInitialAttributesOnChild(child); - } - } - _setInitialAttributesOnChild(child) { - child = this._getInnerElement(child); - const isActive = this._elemIsActive(child); - const outerElem = this._getOuterElement(child); - child.setAttribute('aria-selected', isActive); - if (outerElem !== child) { - this._setAttributeIfNotExists(outerElem, 'role', 'presentation'); - } - if (!isActive) { - child.setAttribute('tabindex', '-1'); - } - this._setAttributeIfNotExists(child, 'role', 'tab'); - this._setInitialAttributesOnTargetPanel(child); - } - _setInitialAttributesOnTargetPanel(child) { - const target = SelectorEngine.getElementFromSelector(child); - if (!target) { - return; - } - this._setAttributeIfNotExists(target, 'role', 'tabpanel'); - if (child.id) { - this._setAttributeIfNotExists(target, 'aria-labelledby', `${child.id}`); - } - } - _toggleDropDown(element, open) { - const outerElem = this._getOuterElement(element); - if (!outerElem.classList.contains(CLASS_DROPDOWN)) { - return; - } - const toggle = (selector, className) => { - const element = SelectorEngine.findOne(selector, outerElem); - if (element) { - element.classList.toggle(className, open); - } - }; - toggle(SELECTOR_DROPDOWN_TOGGLE, CLASS_NAME_ACTIVE); - toggle(SELECTOR_DROPDOWN_MENU, CLASS_NAME_SHOW$1); - outerElem.setAttribute('aria-expanded', open); - } - _setAttributeIfNotExists(element, attribute, value) { - if (!element.hasAttribute(attribute)) { - element.setAttribute(attribute, value); - } - } - _elemIsActive(elem) { - return elem.classList.contains(CLASS_NAME_ACTIVE); - } - _getInnerElement(elem) { - return elem.matches(SELECTOR_INNER_ELEM) ? elem : SelectorEngine.findOne(SELECTOR_INNER_ELEM, elem); - } - _getOuterElement(elem) { - return elem.closest(SELECTOR_OUTER) || elem; - } - static jQueryInterface(config) { - return this.each(function () { - const data = Tab.getOrCreateInstance(this); - if (typeof config !== 'string') { - return; - } - if (data[config] === undefined || config.startsWith('_') || config === 'constructor') { - throw new TypeError(`No method named "${config}"`); - } - data[config](); - }); - } - } - EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function (event) { - if (['A', 'AREA'].includes(this.tagName)) { - event.preventDefault(); - } - if (isDisabled(this)) { - return; - } - Tab.getOrCreateInstance(this).show(); - }); - EventHandler.on(window, EVENT_LOAD_DATA_API, () => { - for (const element of SelectorEngine.find(SELECTOR_DATA_TOGGLE_ACTIVE)) { - Tab.getOrCreateInstance(element); - } - }); - defineJQueryPlugin(Tab); - const NAME = 'toast'; - const DATA_KEY = 'bs.toast'; - const EVENT_KEY = `.${DATA_KEY}`; - const EVENT_MOUSEOVER = `mouseover${EVENT_KEY}`; - const EVENT_MOUSEOUT = `mouseout${EVENT_KEY}`; - const EVENT_FOCUSIN = `focusin${EVENT_KEY}`; - const EVENT_FOCUSOUT = `focusout${EVENT_KEY}`; - const EVENT_HIDE = `hide${EVENT_KEY}`; - const EVENT_HIDDEN = `hidden${EVENT_KEY}`; - const EVENT_SHOW = `show${EVENT_KEY}`; - const EVENT_SHOWN = `shown${EVENT_KEY}`; - const CLASS_NAME_FADE = 'fade'; - const CLASS_NAME_HIDE = 'hide'; - const CLASS_NAME_SHOW = 'show'; - const CLASS_NAME_SHOWING = 'showing'; - const DefaultType = { - animation: 'boolean', - autohide: 'boolean', - delay: 'number' - }; - const Default = { - animation: true, - autohide: true, - delay: 5000 - }; - class Toast extends BaseComponent { - constructor(element, config) { - super(element, config); - this._timeout = null; - this._hasMouseInteraction = false; - this._hasKeyboardInteraction = false; - this._setListeners(); - } - static get Default() { - return Default; - } - static get DefaultType() { - return DefaultType; - } - static get NAME() { - return NAME; - } - show() { - const showEvent = EventHandler.trigger(this._element, EVENT_SHOW); - if (showEvent.defaultPrevented) { - return; - } - this._clearTimeout(); - if (this._config.animation) { - this._element.classList.add(CLASS_NAME_FADE); - } - const complete = () => { - this._element.classList.remove(CLASS_NAME_SHOWING); - EventHandler.trigger(this._element, EVENT_SHOWN); - this._maybeScheduleHide(); - }; - this._element.classList.remove(CLASS_NAME_HIDE); - reflow(this._element); - this._element.classList.add(CLASS_NAME_SHOW, CLASS_NAME_SHOWING); - this._queueCallback(complete, this._element, this._config.animation); - } - hide() { - if (!this.isShown()) { - return; - } - const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE); - if (hideEvent.defaultPrevented) { - return; - } - const complete = () => { - this._element.classList.add(CLASS_NAME_HIDE); - this._element.classList.remove(CLASS_NAME_SHOWING, CLASS_NAME_SHOW); - EventHandler.trigger(this._element, EVENT_HIDDEN); - }; - this._element.classList.add(CLASS_NAME_SHOWING); - this._queueCallback(complete, this._element, this._config.animation); - } - dispose() { - this._clearTimeout(); - if (this.isShown()) { - this._element.classList.remove(CLASS_NAME_SHOW); - } - super.dispose(); - } - isShown() { - return this._element.classList.contains(CLASS_NAME_SHOW); - } - _maybeScheduleHide() { - if (!this._config.autohide) { - return; - } - if (this._hasMouseInteraction || this._hasKeyboardInteraction) { - return; - } - this._timeout = setTimeout(() => { - this.hide(); - }, this._config.delay); - } - _onInteraction(event, isInteracting) { - switch (event.type) { - case 'mouseover': - case 'mouseout': - { - this._hasMouseInteraction = isInteracting; - break; - } - case 'focusin': - case 'focusout': - { - this._hasKeyboardInteraction = isInteracting; - break; - } - } - if (isInteracting) { - this._clearTimeout(); - return; - } - const nextElement = event.relatedTarget; - if (this._element === nextElement || this._element.contains(nextElement)) { - return; - } - this._maybeScheduleHide(); - } - _setListeners() { - EventHandler.on(this._element, EVENT_MOUSEOVER, event => this._onInteraction(event, true)); - EventHandler.on(this._element, EVENT_MOUSEOUT, event => this._onInteraction(event, false)); - EventHandler.on(this._element, EVENT_FOCUSIN, event => this._onInteraction(event, true)); - EventHandler.on(this._element, EVENT_FOCUSOUT, event => this._onInteraction(event, false)); - } - _clearTimeout() { - clearTimeout(this._timeout); - this._timeout = null; - } - static jQueryInterface(config) { - return this.each(function () { - const data = Toast.getOrCreateInstance(this, config); - if (typeof config === 'string') { - if (typeof data[config] === 'undefined') { - throw new TypeError(`No method named "${config}"`); - } - data[config](this); - } - }); - } - } - enableDismissTrigger(Toast); - defineJQueryPlugin(Toast); - - var bootstrap = /*#__PURE__*/Object.freeze({ - __proto__: null, - Alert: Alert, - Button: Button, - Carousel: Carousel, - Collapse: Collapse, - Dropdown: Dropdown, - Modal: Modal, - Offcanvas: Offcanvas, - Popover: Popover, - ScrollSpy: ScrollSpy, - Tab: Tab, - Toast: Toast, - Tooltip: Tooltip - }); - - var dropdownTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="dropdown"]')); - dropdownTriggerList.map(function (dropdownTriggerEl) { - var options = { - boundary: dropdownTriggerEl.getAttribute('data-bs-boundary') === 'viewport' ? document.querySelector('.btn') : 'clippingParents' - }; - return new Dropdown(dropdownTriggerEl, options); - }); - - var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]')); - tooltipTriggerList.map(function (tooltipTriggerEl) { - var _ref, _tooltipTriggerEl$get; - var options = { - delay: { - show: 50, - hide: 50 - }, - html: (_ref = tooltipTriggerEl.getAttribute("data-bs-html") === "true") !== null && _ref !== void 0 ? _ref : false, - placement: (_tooltipTriggerEl$get = tooltipTriggerEl.getAttribute('data-bs-placement')) !== null && _tooltipTriggerEl$get !== void 0 ? _tooltipTriggerEl$get : 'auto' - }; - return new Tooltip(tooltipTriggerEl, options); - }); - - var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]')); - popoverTriggerList.map(function (popoverTriggerEl) { - var _ref, _popoverTriggerEl$get; - var options = { - delay: { - show: 50, - hide: 50 - }, - html: (_ref = popoverTriggerEl.getAttribute('data-bs-html') === "true") !== null && _ref !== void 0 ? _ref : false, - placement: (_popoverTriggerEl$get = popoverTriggerEl.getAttribute('data-bs-placement')) !== null && _popoverTriggerEl$get !== void 0 ? _popoverTriggerEl$get : 'auto' - }; - return new Popover(popoverTriggerEl, options); - }); - - var switchesTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="switch-icon"]')); - switchesTriggerList.map(function (switchTriggerEl) { - switchTriggerEl.addEventListener('click', function (e) { - e.stopPropagation(); - switchTriggerEl.classList.toggle('active'); - }); - }); - - var EnableActivationTabsFromLocationHash = function EnableActivationTabsFromLocationHash() { - var locationHash = window.location.hash; - if (locationHash) { - var tabsList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tab"]')); - var matchedTabs = tabsList.filter(function (tab) { - return tab.hash === locationHash; - }); - matchedTabs.map(function (tab) { - new Tab(tab).show(); - }); - } - }; - EnableActivationTabsFromLocationHash(); - - var toastsTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="toast"]')); - toastsTriggerList.map(function (toastTriggerEl) { - return new Toast(toastTriggerEl); - }); - - var prefix = 'tblr-'; - var hexToRgba = function hexToRgba(hex, opacity) { - var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); - return result ? "rgba(".concat(parseInt(result[1], 16), ", ").concat(parseInt(result[2], 16), ", ").concat(parseInt(result[3], 16), ", ").concat(opacity, ")") : null; - }; - var getColor = function getColor(color) { - var opacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; - var c = getComputedStyle(document.body).getPropertyValue("--".concat(prefix).concat(color)).trim(); - if (opacity !== 1) { - return hexToRgba(c, opacity); - } - return c; - }; - - var tabler = /*#__PURE__*/Object.freeze({ - __proto__: null, - prefix: prefix, - hexToRgba: hexToRgba, - getColor: getColor - }); - - globalThis.bootstrap = bootstrap; - globalThis.tabler = tabler; - -})); diff --git a/mc_web_console_front/assets/jsOld/common/tabler/tablerHelper.js b/mc_web_console_front/assets/jsOld/common/tabler/tablerHelper.js deleted file mode 100644 index ee53ed10..00000000 --- a/mc_web_console_front/assets/jsOld/common/tabler/tablerHelper.js +++ /dev/null @@ -1,133 +0,0 @@ -/*! -* Tabler v1.0.0-beta20 (https://tabler.io) -* @version 1.0.0-beta20 -* @link https://tabler.io -* Copyright 2018-2023 The Tabler Authors -* Copyright 2018-2023 codecalm.net Paweł Kuna -* Licensed under MIT (https://github.com/tabler/tabler/blob/master/LICENSE) -*/ -(function (factory) { - typeof define === 'function' && define.amd ? define(factory) : - factory(); -})((function () { - 'use strict'; - - function _iterableToArrayLimit(arr, i) { - var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; - if (null != _i) { - var _s, - _e, - _x, - _r, - _arr = [], - _n = !0, - _d = !1; - try { - if (_x = (_i = _i.call(arr)).next, 0 === i) { - if (Object(_i) !== _i) return; - _n = !1; - } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); - } catch (err) { - _d = !0, _e = err; - } finally { - try { - if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; - } finally { - if (_d) throw _e; - } - } - return _arr; - } - } - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; - } - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - return arr2; - } - function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - var items = { - "menu-position": { - localStorage: "tablerMenuPosition", - default: "top" - }, - "menu-behavior": { - localStorage: "tablerMenuBehavior", - default: "sticky" - }, - "container-layout": { - localStorage: "tablerContainerLayout", - default: "boxed" - } - }; - var config = {}; - for (var _i = 0, _Object$entries = Object.entries(items); _i < _Object$entries.length; _i++) { - var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), - key = _Object$entries$_i[0], - params = _Object$entries$_i[1]; - var lsParams = localStorage.getItem(params.localStorage); - config[key] = lsParams ? lsParams : params.default; - } - var parseUrl = function parseUrl() { - var search = window.location.search.substring(1); - var params = search.split("&"); - for (var i = 0; i < params.length; i++) { - var arr = params[i].split("="); - var _key = arr[0]; - var value = arr[1]; - if (!!items[_key]) { - localStorage.setItem(items[_key].localStorage, value); - config[_key] = value; - } - } - }; - var toggleFormControls = function toggleFormControls(form) { - for (var _i2 = 0, _Object$entries2 = Object.entries(items); _i2 < _Object$entries2.length; _i2++) { - var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2), - _key2 = _Object$entries2$_i[0]; - _Object$entries2$_i[1]; - var elem = form.querySelector("[name=\"settings-".concat(_key2, "\"][value=\"").concat(config[_key2], "\"]")); - if (elem) { - elem.checked = true; - } - } - }; - var submitForm = function submitForm(form) { - for (var _i3 = 0, _Object$entries3 = Object.entries(items); _i3 < _Object$entries3.length; _i3++) { - var _Object$entries3$_i = _slicedToArray(_Object$entries3[_i3], 2), - _key3 = _Object$entries3$_i[0], - _params2 = _Object$entries3$_i[1]; - var value = form.querySelector("[name=\"settings-".concat(_key3, "\"]:checked")).value; - localStorage.setItem(_params2.localStorage, value); - config[_key3] = value; - } - window.dispatchEvent(new Event("resize")); - new bootstrap.Offcanvas(form).hide(); - }; - parseUrl(); - var form = document.querySelector("#offcanvasSettings"); - if (form) { - form.addEventListener("submit", function (e) { - e.preventDefault(); - submitForm(form); - }); - toggleFormControls(form); - } - -})); diff --git a/mc_web_console_front/assets/jsOld/common/tabler/themeMode.js b/mc_web_console_front/assets/jsOld/common/tabler/themeMode.js deleted file mode 100644 index 9cea2e3d..00000000 --- a/mc_web_console_front/assets/jsOld/common/tabler/themeMode.js +++ /dev/null @@ -1,36 +0,0 @@ -/*! -* Tabler v1.0.0-beta20 (https://tabler.io) -* @version 1.0.0-beta20 -* @link https://tabler.io -* Copyright 2018-2023 The Tabler Authors -* Copyright 2018-2023 codecalm.net Paweł Kuna -* Licensed under MIT (https://github.com/tabler/tabler/blob/master/LICENSE) -*/ -(function (factory) { - typeof define === 'function' && define.amd ? define(factory) : - factory(); -})((function () { - 'use strict'; - - var themeStorageKey = "themeMode"; - var defaultTheme = "light"; - var selectedTheme; - var params = new Proxy(new URLSearchParams(window.location.search), { - get: function get(searchParams, prop) { - return searchParams.get(prop); - } - }); - if (!!params.theme) { - localStorage.setItem(themeStorageKey, params.theme); - selectedTheme = params.theme; - } else { - var storedTheme = localStorage.getItem(themeStorageKey); - selectedTheme = storedTheme ? storedTheme : defaultTheme; - } - if (selectedTheme === 'dark') { - document.body.setAttribute("data-bs-theme", selectedTheme); - } else { - document.body.removeAttribute("data-bs-theme"); - } - -})); diff --git a/mc_web_console_front/assets/jsOld/common/view/main.js b/mc_web_console_front/assets/jsOld/common/view/main.js deleted file mode 100644 index 8f1e1461..00000000 --- a/mc_web_console_front/assets/jsOld/common/view/main.js +++ /dev/null @@ -1,2 +0,0 @@ -// starting 지점. - diff --git a/mc_web_console_front/assets/jsOld/common/view/navbar.js b/mc_web_console_front/assets/jsOld/common/view/navbar.js deleted file mode 100644 index 09115ecf..00000000 --- a/mc_web_console_front/assets/jsOld/common/view/navbar.js +++ /dev/null @@ -1,63 +0,0 @@ -document.addEventListener('DOMContentLoaded',async function () { - let workspaceList = await webconsolejs["common/storage/sessionstorage"].getSessionWorkspaceList() - - console.log(workspaceList) - let projectListselectBox = document.getElementById("select-current-project"); - let workspaceListselectBox = document.getElementById("select-current-workspace"); - for (let workspace of workspaceList){ - let option = document.createElement("option"); - option.text = workspace.Name; - option.value = workspace.Id; - workspaceListselectBox.add(option); - } - let currentWorksppacProject = webconsolejs["common/storage/sessionstorage"].getSessionCurrentWorkspaceProjcet() - if (currentWorksppacProject) { - console.log("123123123123123") - await webconsolejs["common/storage/sessionstorage"].updateSessionProjectListByWorkspaceId(currentWorksppacProject.currentWorkspace) - let projectList = webconsolejs["common/storage/sessionstorage"].getSessionProjectList() - for (let projcet of projectList){ - let option = document.createElement("option"); - option.text = projcet.Name; - option.value = projcet.Id; - projectListselectBox.add(option); - } - workspaceListselectBox.value = currentWorksppacProject.currentWorkspace - projectListselectBox.value = currentWorksppacProject.currentProject - }else{ - workspaceListselectBox.value = "" - projectListselectBox.value = "" - } -}); - -document.getElementById("select-current-workspace").addEventListener('change',async function () { - let projectListselectBox = document.getElementById("select-current-project"); - while (projectListselectBox.options.length > 0) { - projectListselectBox.remove(0); - } - await webconsolejs["common/storage/sessionstorage"].updateSessionProjectListByWorkspaceId(this.value) - let projectList = webconsolejs["common/storage/sessionstorage"].getSessionProjectList() - for (let projcet of projectList){ - let option = document.createElement("option"); - option.text = projcet.Name; - option.value = projcet.Id; - projectListselectBox.add(option); - } -}); - - -document.getElementById("select-refresh").addEventListener("click",async function () { - await webconsolejs["common/storage/sessionstorage"].updateSessionWorkspaceList() - alert("Workspace List is updated") -}); - -document.getElementById("select-confirm").addEventListener("click",function () { - let workspacId = document.getElementById("select-current-workspace").value - let projectId = document.getElementById("select-current-project").value; - - if (workspacId && projectId){ - webconsolejs["common/storage/sessionstorage"].setSessionCurrentWorkspaceProjcet(workspacId, projectId) - alert("SUCCESS : "+workspacId+" and "+projectId+" is selected !") - }else { - alert("ERROR : workspace and project is not selected !") - } -}); \ No newline at end of file diff --git a/mc_web_console_front/assets/jsOld/common/view/sideMenu.js b/mc_web_console_front/assets/jsOld/common/view/sideMenu.js deleted file mode 100644 index 5df845b0..00000000 --- a/mc_web_console_front/assets/jsOld/common/view/sideMenu.js +++ /dev/null @@ -1,7 +0,0 @@ -document.addEventListener("DOMContentLoaded", function () { - const path = window.location.pathname.split('/') - const depth2 = 'sidebar_'+ path[3] - const depth3 = 'sidebar_'+path[3]+'_'+path[4] - document.getElementsByName(depth2).forEach(i => i.classList.add('show', 'active')); - document.getElementById(depth3).classList.add('active'); -}); \ No newline at end of file diff --git a/mc_web_console_front/assets/jsOld/debug/apicall/apicall.js b/mc_web_console_front/assets/jsOld/debug/apicall/apicall.js deleted file mode 100644 index d1b15279..00000000 --- a/mc_web_console_front/assets/jsOld/debug/apicall/apicall.js +++ /dev/null @@ -1,106 +0,0 @@ -import axios from 'axios'; -import { TabulatorFull as Tabulator } from 'tabulator-tables'; - - -document.getElementById("sendBtn").addEventListener('click', function () { - let method = document.getElementById("methodSelect").value - let target = document.getElementById("targetSelect").value - let path = document.getElementById("path").value - - let targetPath = "" - if (target == "direct") { - alert("not implement") - return - } else if (target == "self") { - targetPath = "/api/debug/" + path - } else { - targetPath = "/api/debug/" + target + path - } - - if (document.getElementById("CSRFSelect").value == "True") { - let csrfToken = document.getElementById("csrf-token").getAttribute('content'); - axios.defaults.headers.common['X-CSRF-TOKEN'] = csrfToken; - } else { - axios.defaults.headers.common['X-CSRF-TOKEN'] = ""; - } - - if (document.getElementById("authorizationSelect").value == "BearerToken") { - axios.defaults.headers.common['Authorization'] = "Bearer " + document.getElementById("bearerToken").value; - } - - let jsonData - if (document.getElementById("bodyArea").value){ - jsonData = JSON.parse(document.getElementById("bodyArea").value) - } - - - if (method == "POST") { - axios.defaults.headers.common['Content-Type'] = 'application/json'; - } - - axios({ - method: method, - url: paramsTable.getData().length > 0 ? targetPath + '?' + buildQueryString(paramsTable.getData()) : targetPath, - data: jsonData - }).then(function (response) { - document.getElementById("RequestTarget").innerText = paramsTable.getData().length > 0 ? targetPath + '?' + buildQueryString(paramsTable.getData()) : targetPath; - document.getElementById("ResponseData").innerText = JSON.stringify(response.data, null, 2); - document.getElementById("ResponseHeaders").innerText = response.headers; - console.log(response.data); - }).catch(function (error) { - document.getElementById("RequestTarget").innerText = ""; - document.getElementById("ResponseData").innerText = error; - document.getElementById("ResponseHeaders").innerText = ""; - console.error(error); - }); - - }); - -function buildQueryString(data) { - return data.map(item => `${encodeURIComponent(item.key)}=${encodeURIComponent(item.value)}`).join('&'); -} - -let paramsTable = new Tabulator() -document.addEventListener("DOMContentLoaded", function () { - paramsTable = new Tabulator("#paramsTable", { - layout: "fitColumns", - resizableColumnFit: true, - columns: [ - { title: "KEY", field: "key", editor: "input" }, - { title: "VALUE", field: "value", editor: "input" }, - { - formatter: "buttonCross", resizable: false, frozen: true, align: "center", title: "del", headerSort: false, cellClick: function (e, cell) { - if (confirm('Are you sure you want to delete?')) - cell.getRow().delete(); - } - } - ], - - }); -}); -document.getElementById("paramAdd").addEventListener('click', function () { - paramsTable.addRow(); -}); - -let headerTable = new Tabulator() -document.addEventListener("DOMContentLoaded", function () { - headerTable = new Tabulator("#headerTable", { - layout: "fitColumns", - resizableColumnFit: true, - columns: [ - { title: "KEY", field: "key", editor: "input" }, - { title: "VALUE", field: "value", editor: "input" }, - { - formatter: "buttonCross", resizable: false, frozen: true, align: "center", title: "del", headerSort: false, cellClick: function (e, cell) { - if (confirm('Are you sure you want to delete?')) - cell.getRow().delete(); - } - } - ], - - }); -}); -document.getElementById("headerAdd").addEventListener('click', function () { - headerTable.addRow(); -}); - diff --git a/mc_web_console_front/assets/jsOld/debug/auth/login.js b/mc_web_console_front/assets/jsOld/debug/auth/login.js deleted file mode 100644 index 859a767d..00000000 --- a/mc_web_console_front/assets/jsOld/debug/auth/login.js +++ /dev/null @@ -1,11 +0,0 @@ -import axios from 'axios' - -document.addEventListener("DOMContentLoaded", function () { - axios.get('http://ifconfig.me/all.json') - .then(function (response) { - console.log(response.data); - }) - .catch(function (error) { - console.error(error); - }); -}); \ No newline at end of file diff --git a/mc_web_console_front/assets/jsOld/debug/default-test.js b/mc_web_console_front/assets/jsOld/debug/default-test.js deleted file mode 100644 index 50ee9096..00000000 --- a/mc_web_console_front/assets/jsOld/debug/default-test.js +++ /dev/null @@ -1,13 +0,0 @@ -// this is start and test copy js - -import axios from 'axios' - -document.addEventListener("DOMContentLoaded", function () { - axios.get('http://ifconfig.me/all.json') - .then(function (response) { - console.log(response.data); - }) - .catch(function (error) { - console.error(error); - }); -}); \ No newline at end of file diff --git a/mc_web_console_front/assets/jsOld/debug/home/dash.js b/mc_web_console_front/assets/jsOld/debug/home/dash.js deleted file mode 100644 index d1667975..00000000 --- a/mc_web_console_front/assets/jsOld/debug/home/dash.js +++ /dev/null @@ -1,583 +0,0 @@ -import ApexCharts from 'apexcharts'; - -import { Tabulator } from 'tabulator-tables'; - -import jsVectorMap from 'jsvectormap'; -import 'jsvectormap/dist/maps/world.js'; - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-revenue-bg'), { - chart: { - type: "area", - fontFamily: 'inherit', - height: 40.0, - sparkline: { - enabled: true - }, - animations: { - enabled: false - }, - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: .16, - type: 'solid' - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Profits", - data: [37, 35, 44, 28, 36, 24, 65, 31, 37, 39, 62, 51, 35, 41, 35, 27, 93, 53, 61, 27, 54, 43, 19, 46, 39, 62, 51, 35, 41, 67] - }], - tooltip: { - theme: 'dark' - }, - grid: { - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - })).render(); -}); - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-new-clients'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 40.0, - sparkline: { - enabled: true - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - stroke: { - width: [2, 1], - dashArray: [0, 3], - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "May", - data: [37, 35, 44, 28, 36, 24, 65, 31, 37, 39, 62, 51, 35, 41, 35, 27, 93, 53, 61, 27, 54, 43, 4, 46, 39, 62, 51, 35, 41, 67] - }, { - name: "April", - data: [93, 54, 51, 24, 35, 35, 31, 67, 19, 43, 28, 36, 62, 61, 27, 39, 35, 41, 27, 35, 51, 46, 62, 37, 44, 53, 41, 65, 39, 37] - }], - tooltip: { - theme: 'dark' - }, - grid: { - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19' - ], - colors: [tabler.getColor("primary"), tabler.getColor("gray-600")], - legend: { - show: false, - }, - })).render(); -}); - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-active-users'), { - chart: { - type: "bar", - fontFamily: 'inherit', - height: 40.0, - sparkline: { - enabled: true - }, - animations: { - enabled: false - }, - }, - plotOptions: { - bar: { - columnWidth: '50%', - } - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: 1, - }, - series: [{ - name: "Profits", - data: [37, 35, 44, 28, 36, 24, 65, 31, 37, 39, 62, 51, 35, 41, 35, 27, 93, 53, 61, 27, 54, 43, 19, 46, 39, 62, 51, 35, 41, 67] - }], - tooltip: { - theme: 'dark' - }, - grid: { - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - })).render(); -}); - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-mentions'), { - chart: { - type: "bar", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - stacked: true, - }, - plotOptions: { - bar: { - columnWidth: '50%', - } - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: 1, - }, - series: [{ - name: "Web", - data: [1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 2, 12, 5, 8, 22, 6, 8, 6, 4, 1, 8, 24, 29, 51, 40, 47, 23, 26, 50, 26, 41, 22, 46, 47, 81, 46, 6] - }, { - name: "Social", - data: [2, 5, 4, 3, 3, 1, 4, 7, 5, 1, 2, 5, 3, 2, 6, 7, 7, 1, 5, 5, 2, 12, 4, 6, 18, 3, 5, 2, 13, 15, 20, 47, 18, 15, 11, 10, 0] - }, { - name: "Other", - data: [2, 9, 1, 7, 8, 3, 6, 5, 5, 4, 6, 4, 1, 9, 3, 6, 7, 5, 2, 8, 4, 9, 1, 2, 6, 7, 5, 1, 8, 3, 2, 3, 4, 9, 7, 1, 6] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - xaxis: { - lines: { - show: true - } - }, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19', '2020-07-20', '2020-07-21', '2020-07-22', '2020-07-23', '2020-07-24', '2020-07-25', '2020-07-26' - ], - colors: [tabler.getColor("primary"), tabler.getColor("primary", 0.8), tabler.getColor("green", 0.8)], - legend: { - show: false, - }, - })).render(); -}); - -document.addEventListener("DOMContentLoaded", function () { - const map = new jsVectorMap({ - selector: '#map-world', - map: 'world', - backgroundColor: 'transparent', - regionStyle: { - initial: { - fill: tabler.getColor('body-bg'), - stroke: tabler.getColor('border-color'), - strokeWidth: 2, - } - }, - zoomOnScroll: false, - zoomButtons: false, - // -------- Series -------- - visualizeData: { - scale: [tabler.getColor('bg-surface'), tabler.getColor('primary')], - values: { "AF": 16, "AL": 11, "DZ": 158, "AO": 85, "AG": 1, "AR": 351, "AM": 8, "AU": 1219, "AT": 366, "AZ": 52, "BS": 7, "BH": 21, "BD": 105, "BB": 3, "BY": 52, "BE": 461, "BZ": 1, "BJ": 6, "BT": 1, "BO": 19, "BA": 16, "BW": 12, "BR": 2023, "BN": 11, "BG": 44, "BF": 8, "BI": 1, "KH": 11, "CM": 21, "CA": 1563, "CV": 1, "CF": 2, "TD": 7, "CL": 199, "CN": 5745, "CO": 283, "KM": 0, "CD": 12, "CG": 11, "CR": 35, "CI": 22, "HR": 59, "CY": 22, "CZ": 195, "DK": 304, "DJ": 1, "DM": 0, "DO": 50, "EC": 61, "EG": 216, "SV": 21, "GQ": 14, "ER": 2, "EE": 19, "ET": 30, "FJ": 3, "FI": 231, "FR": 2555, "GA": 12, "GM": 1, "GE": 11, "DE": 3305, "GH": 18, "GR": 305, "GD": 0, "GT": 40, "GN": 4, "GW": 0, "GY": 2, "HT": 6, "HN": 15, "HK": 226, "HU": 132, "IS": 12, "IN": 1430, "ID": 695, "IR": 337, "IQ": 84, "IE": 204, "IL": 201, "IT": 2036, "JM": 13, "JP": 5390, "JO": 27, "KZ": 129, "KE": 32, "KI": 0, "KR": 986, "KW": 117, "KG": 4, "LA": 6, "LV": 23, "LB": 39, "LS": 1, "LR": 0, "LY": 77, "LT": 35, "LU": 52, "MK": 9, "MG": 8, "MW": 5, "MY": 218, "MV": 1, "ML": 9, "MT": 7, "MR": 3, "MU": 9, "MX": 1004, "MD": 5, "MN": 5, "ME": 3, "MA": 91, "MZ": 10, "MM": 35, "NA": 11, "NP": 15, "NL": 770, "NZ": 138, "NI": 6, "NE": 5, "NG": 206, "NO": 413, "OM": 53, "PK": 174, "PA": 27, "PG": 8, "PY": 17, "PE": 153, "PH": 189, "PL": 438, "PT": 223, "QA": 126, "RO": 158, "RU": 1476, "RW": 5, "WS": 0, "ST": 0, "SA": 434, "SN": 12, "RS": 38, "SC": 0, "SL": 1, "SG": 217, "SK": 86, "SI": 46, "SB": 0, "ZA": 354, "ES": 1374, "LK": 48, "KN": 0, "LC": 1, "VC": 0, "SD": 65, "SR": 3, "SZ": 3, "SE": 444, "CH": 522, "SY": 59, "TW": 426, "TJ": 5, "TZ": 22, "TH": 312, "TL": 0, "TG": 3, "TO": 0, "TT": 21, "TN": 43, "TR": 729, "TM": 0, "UG": 17, "UA": 136, "AE": 239, "GB": 2258, "US": 4624, "UY": 40, "UZ": 37, "VU": 0, "VE": 285, "VN": 101, "YE": 30, "ZM": 15, "ZW": 5 }, - }, - }); - window.addEventListener("resize", () => { - map.updateSize(); - }); -}); - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('sparkline-activity'), { - chart: { - type: "radialBar", - fontFamily: 'inherit', - height: 40, - width: 40, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - plotOptions: { - radialBar: { - hollow: { - margin: 0, - size: '75%' - }, - track: { - margin: 0 - }, - dataLabels: { - show: false - } - } - }, - colors: [tabler.getColor("blue")], - series: [35], - })).render(); -}); - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-development-activity'), { - chart: { - type: "area", - fontFamily: 'inherit', - height: 192, - sparkline: { - enabled: true - }, - animations: { - enabled: false - }, - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: .16, - type: 'solid' - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Purchases", - data: [3, 5, 4, 6, 7, 5, 6, 8, 24, 7, 12, 5, 6, 3, 8, 4, 14, 30, 17, 19, 15, 14, 25, 32, 40, 55, 60, 48, 52, 70] - }], - tooltip: { - theme: 'dark' - }, - grid: { - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - point: { - show: false - }, - })).render(); -}); - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-1'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [17, 24, 20, 10, 5, 1, 4, 18, 13] - }], - })).render(); -}); - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-2'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [13, 11, 19, 22, 12, 7, 14, 3, 21] - }], - })).render(); -}); - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-3'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [10, 13, 10, 4, 17, 3, 23, 22, 19] - }], - })).render(); -}); - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-4'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [6, 15, 13, 13, 5, 7, 17, 20, 19] - }], - })).render(); -}); - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-5'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [2, 11, 15, 14, 21, 20, 8, 23, 18, 14] - }], - })).render(); -}); - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-6'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [22, 12, 7, 14, 3, 21, 8, 23, 18, 14] - }], - })).render(); -}); - -var tabledata = [ - {id:1, name:"Oli Bob", age:"12", col:"red", dob:""}, - {id:2, name:"Mary May", age:"1", col:"blue", dob:"14/05/1982"}, - {id:3, name:"Christine Lobowski", age:"42", col:"green", dob:"22/05/1982"}, - {id:4, name:"Brendon Philips", age:"125", col:"orange", dob:"01/08/1980"}, - {id:5, name:"Margret Marmajuke", age:"16", col:"yellow", dob:"31/01/1999"}, -]; - -//create Tabulator on DOM element with id "example-table" -var table = new Tabulator("#example-table", { - height:205, // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value) - data:tabledata, //assign data to table - layout:"fitColumns", //fit columns to width of table (optional) - columns:[ //Define Table Columns - {title:"Name", field:"name", width:150}, - {title:"Age", field:"age", hozAlign:"left", formatter:"progress"}, - {title:"Favourite Color", field:"col"}, - {title:"Date Of Birth", field:"dob", sorter:"date", hozAlign:"center"}, - ], -}); - -//trigger an alert message when the row is clicked -table.on("rowClick", function(e, row){ - alert("Row " + row.getData().id + " Clicked!!!!"); -}); diff --git a/mc_web_console_front/assets/jsOld/debug/tabler/chart.js b/mc_web_console_front/assets/jsOld/debug/tabler/chart.js deleted file mode 100644 index ecce9067..00000000 --- a/mc_web_console_front/assets/jsOld/debug/tabler/chart.js +++ /dev/null @@ -1,1734 +0,0 @@ -import ApexCharts from 'apexcharts'; - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-active-users-2'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 288, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Mobile", - data: [4164, 4652, 4817, 4841, 4920, 5439, 5486, 5498, 5512, 5538, 5841, 5877, 6086, 6146, 6199, 6431, 6704, 7939, 8127, 8296, 8322, 8389, 8411, 8502, 8868, 8977, 9273, 9325, 9345, 9430] - },{ - name: "Desktop", - data: [2164, 2292, 2386, 2430, 2528, 3045, 3255, 3295, 3481, 3604, 3688, 3840, 3932, 3949, 4003, 4298, 4424, 4869, 4922, 4973, 5155, 5267, 5566, 5689, 5692, 5758, 5773, 5799, 5960, 6000] - },{ - name: "Tablet", - data: [1069, 1089, 1125, 1141, 1162, 1179, 1185, 1216, 1274, 1322, 1346, 1395, 1439, 1564, 1581, 1590, 1656, 1815, 1868, 2010, 2133, 2179, 2264, 2265, 2278, 2343, 2354, 2456, 2472, 2480] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19' - ], - colors: [tabler.getColor("primary"), tabler.getColor("azure"), tabler.getColor("green")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-social-referrals'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 288, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Facebook", - data: [13281, 8521, 15038, 9983, 15417, 8888, 7052, 14270, 5214, 9587, 5950, 16852, 17836, 12217, 17406, 12262, 9147, 14961, 18292, 15230, 13435, 10649, 5140, 13680, 4508, 13271, 13413, 5543, 18727, 18238, 18175, 6246, 5864, 17847, 9170, 6445, 12945, 8142, 8980, 10422, 15535, 11569, 10114, 17621, 16138, 13046, 6652, 9906, 14100, 16495, 6749] - },{ - name: "Twitter", - data: [3680, 1862, 3070, 2252, 5348, 3091, 3000, 3984, 5176, 5325, 2420, 5474, 3098, 1893, 3748, 2879, 4197, 5186, 4213, 4334, 2807, 1594, 4863, 2030, 3752, 4856, 5341, 3954, 3461, 3097, 3404, 4949, 2283, 3227, 3630, 2360, 3477, 4675, 1901, 2252, 3347, 2954, 5029, 2079, 2830, 3292, 4578, 3401, 4104, 3749, 4457, 3734] - },{ - name: "Dribbble", - data: [722, 1866, 961, 1108, 1110, 561, 1753, 1815, 1985, 776, 859, 547, 1488, 766, 702, 621, 1599, 1372, 1620, 963, 759, 764, 739, 789, 1696, 1454, 1842, 734, 551, 1689, 1924, 1875, 908, 1675, 1541, 1953, 534, 502, 1524, 1867, 719, 1472, 1608, 1025, 889, 1150, 654, 1695, 1662, 1285, 1787] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - xaxis: { - lines: { - show: true - } - }, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19', '2020-07-20', '2020-07-21', '2020-07-22', '2020-07-23', '2020-07-24', '2020-07-25', '2020-07-26', '2020-07-27', '2020-07-28', '2020-07-29', '2020-07-30', '2020-07-31', '2020-08-01', '2020-08-02', '2020-08-03', '2020-08-04', '2020-08-05', '2020-08-06', '2020-08-07', '2020-08-08', '2020-08-09' - ], - colors: [tabler.getColor("facebook"), tabler.getColor("twitter"), tabler.getColor("dribbble")], - legend: { - show: true, - position: 'bottom', - offsetY: 12, - markers: { - width: 10, - height: 10, - radius: 100, - }, - itemMargin: { - horizontal: 8, - vertical: 8 - }, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-tasks-overview'), { - chart: { - type: "bar", - fontFamily: 'inherit', - height: 320, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - plotOptions: { - bar: { - columnWidth: '50%', - } - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: 1, - }, - series: [{ - name: "A", - data: [44, 32, 48, 72, 60, 16, 44, 32, 78, 50, 68, 34, 26, 48, 72, 60, 84, 64, 74, 52, 62, 50, 32, 22] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - categories: ['Sprint 1', 'Sprint 2', 'Sprint 3', 'Sprint 4', 'Sprint 5', 'Sprint 6', 'Sprint 7', 'Sprint 8', 'Sprint 9', 'Sprint 10', 'Sprint 11', 'Sprint 12', 'Sprint 13', 'Sprint 14', 'Sprint 15', 'Sprint 16', 'Sprint 17', 'Sprint 18', 'Sprint 19', 'Sprint 20', 'Sprint 21', 'Sprint 22', 'Sprint 23', 'Sprint 24'], - }, - yaxis: { - labels: { - padding: 4 - }, - }, - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-demo-pie'), { - chart: { - type: "donut", - fontFamily: 'inherit', - height: 240, - sparkline: { - enabled: true - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - series: [44, 55, 12, 2], - labels: ["Direct", "Affilliate", "E-mail", "Other"], - tooltip: { - theme: 'dark' - }, - grid: { - strokeDashArray: 4, - }, - colors: [tabler.getColor("primary"), tabler.getColor("primary", 0.8), tabler.getColor("primary", 0.6), tabler.getColor("gray-300")], - legend: { - show: true, - position: 'bottom', - offsetY: 12, - markers: { - width: 10, - height: 10, - radius: 100, - }, - itemMargin: { - horizontal: 8, - vertical: 8 - }, - }, - tooltip: { - fillSeriesColor: false - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-completion-tasks'), { - chart: { - type: "bar", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - plotOptions: { - bar: { - columnWidth: '50%', - } - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: 1, - }, - series: [{ - name: "Tasks completion", - data: [155, 65, 465, 265, 225, 325, 80] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-completion-tasks-2'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Tasks completion", - data: [155, 65, 465, 265, 225, 325, 80] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-completion-tasks-3'), { - chart: { - type: "area", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: .16, - type: 'solid' - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Tasks completion", - data: [155, 65, 465, 265, 225, 325, 80] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-completion-tasks-4'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - stroke: { - width: 2, - lineCap: "round", - curve: "straight", - }, - series: [{ - name: "Tasks completion", - data: [155, 65, 465, 265, 225, 325, 80] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-completion-tasks-5'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - stroke: { - width: 2, - lineCap: "round", - curve: "stepline", - }, - series: [{ - name: "Tasks completion", - data: [155, 65, 465, 265, 225, 325, 80] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-completion-tasks-6'), { - chart: { - type: "bar", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - plotOptions: { - bar: { - barHeight: '50%', - horizontal: true, - } - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: 1, - }, - series: [{ - name: "Tasks completion", - data: [155, 65, 465, 265, 225, 325, 80] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-completion-tasks-7'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Tasks completion", - data: [155, 65, 465, 265, 225, 325, 80] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-completion-tasks-8'), { - chart: { - type: "bar", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - plotOptions: { - bar: { - columnWidth: '50%', - } - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: 1, - }, - series: [{ - name: "", - data: [155, 65, 465, 265, 225, 325, 80] - },{ - name: "", - data: [113, 42, 65, 54, 76, 65, 35] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26' - ], - colors: [tabler.getColor("primary"), tabler.getColor("red")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-completion-tasks-9'), { - chart: { - type: "bar", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - stacked: true, - }, - plotOptions: { - bar: { - columnWidth: '50%', - } - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: 1, - }, - series: [{ - name: "", - data: [155, 65, 465, 265, 225, 325, 80] - },{ - name: "", - data: [113, 42, 65, 54, 76, 65, 35] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26' - ], - colors: [tabler.getColor("primary"), tabler.getColor("red")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-completion-tasks-10'), { - chart: { - type: "area", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: .16, - type: 'solid' - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "", - data: [155, 65, 465, 265, 225, 325, 80] - },{ - name: "", - data: [113, 42, 65, 54, 76, 65, 35] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26' - ], - colors: [tabler.getColor("primary"), tabler.getColor("red")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-completion-tasks-11'), { - chart: { - type: "area", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - stacked: true, - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: .16, - type: 'solid' - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "", - data: [155, 65, 465, 265, 225, 325, 80] - },{ - name: "", - data: [113, 42, 65, 54, 76, 65, 35] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26' - ], - colors: [tabler.getColor("primary"), tabler.getColor("red")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-tasks'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "New", - data: [0, 0, 1, 2, 21, 9, 12, 10, 31, 13, 65, 10, 12, 6, 4, 3, 0] - },{ - name: "Completed", - data: [0, 0, 1, 2, 7, 5, 6, 8, 24, 7, 12, 5, 6, 3, 2, 2, 0] - },{ - name: "Closed", - data: [0, 0, 1, 0, 2, 0, 1, 0, 2, 3, 0, 2, 3, 2, 1, 0, 0] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - categories: ['M', 'T', 'W', 'T', 'F', 'S', 'S', 'M', 'T', 'W', 'T', 'F', 'S', 'S', 'M', 'T', 'W'], - }, - yaxis: { - labels: { - padding: 4 - }, - }, - colors: [tabler.getColor("primary"), tabler.getColor("lime"), tabler.getColor("orange")], - legend: { - show: false, - }, - tooltip: { - enabled: false, - }, - point: { - show: false - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-line-stroke'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - stroke: { - width: 2, - lineCap: "round", - curve: "straight", - }, - series: [{ - name: "Development", - data: [8, 10, 11, 12, 20, 27, 30] - },{ - name: "Marketing", - data: [3, 16, 17, 19, 20, 30, 30] - },{ - name: "Sales", - data: [7, 10, 11, 18, 18, 18, 24] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - categories: ['2013', '2014', '2015', '2016', '2017', '2018', '2019'], - }, - yaxis: { - labels: { - padding: 4 - }, - }, - colors: [tabler.getColor("orange"), tabler.getColor("primary"), tabler.getColor("green")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-stepline'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - stroke: { - width: 2, - lineCap: "round", - curve: "stepline", - }, - series: [{ - name: "Development", - data: [34, 44, 54, 21, 12, 43, 33, 23, 66, 66, 58] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - yaxis: { - labels: { - padding: 4 - }, - }, - colors: [tabler.getColor("orange")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-temperature'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Tokyo", - data: [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] - },{ - name: "London", - data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - dataLabels: { - enabled: true, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], - }, - yaxis: { - labels: { - padding: 4 - }, - }, - colors: [tabler.getColor("primary"), tabler.getColor("green")], - legend: { - show: false, - }, - markers: { - size: 2 - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-area'), { - chart: { - type: "area", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: .16, - type: 'solid' - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Maximum", - data: [11, 8, 15, 18, 19, 17] - },{ - name: "Minimum", - data: [7, 7, 5, 7, 9, 12] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'], - }, - yaxis: { - labels: { - padding: 4 - }, - }, - colors: [tabler.getColor("primary"), tabler.getColor("pink")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-area-spline'), { - chart: { - type: "area", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: .16, - type: 'solid' - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Maximum", - data: [11, 8, 15, 18, 19, 17] - },{ - name: "Minimum", - data: [7, 7, 5, 7, 9, 12] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'], - }, - yaxis: { - labels: { - padding: 4 - }, - }, - colors: [tabler.getColor("primary"), tabler.getColor("pink")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-area-spline-stacked'), { - chart: { - type: "area", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - stacked: true, - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: .16, - type: 'solid' - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Maximum", - data: [11, 8, 15, 18, 19, 17] - },{ - name: "Minimum", - data: [7, 7, 5, 7, 9, 12] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'], - }, - yaxis: { - labels: { - padding: 4 - }, - }, - colors: [tabler.getColor("primary"), tabler.getColor("pink")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-spline'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Hestavollane", - data: [0.2, 0.8, 0.8, 0.8, 1, 1.3, 1.5, 2.9, 1.9, 2.6, 1.6, 3, 4, 3.6, 4.5, 4.2, 4.5, 4.5, 4, 3.1, 2.7, 4, 2.7, 2.3, 2.3, 4.1, 7.7, 7.1, 5.6, 6.1, 5.8, 8.6, 7.2, 9, 10.9, 11.5, 11.6, 11.1, 12, 12.3, 10.7, 9.4, 9.8, 9.6, 9.8, 9.5, 8.5, 7.4, 7.6] - },{ - name: "Vik", - data: [0, 0, 0.6, 0.9, 0.8, 0.2, 0, 0, 0, 0.1, 0.6, 0.7, 0.8, 0.6, 0.2, 0, 0.1, 0.3, 0.3, 0, 0.1, 0, 0, 0, 0.2, 0.1, 0, 0.3, 0, 0.1, 0.2, 0.1, 0.3, 0.3, 0, 3.1, 3.1, 2.5, 1.5, 1.9, 2.1, 1, 2.3, 1.9, 1.2, 0.7, 1.3, 0.4, 0.3] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'], - }, - yaxis: { - labels: { - padding: 4 - }, - }, - colors: [tabler.getColor("primary"), tabler.getColor("green")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-scatter'), { - chart: { - type: "scatter", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - series: [{ - name: "Maximum", - data: [11, 8, 15, 18, 19, 17] - },{ - name: "Minimum", - data: [7, 7, 5, 7, 9, 12] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'], - }, - yaxis: { - labels: { - padding: 4 - }, - }, - colors: [tabler.getColor("primary"), tabler.getColor("pink")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-combination'), { - chart: { - type: "bar", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - }, - plotOptions: { - bar: { - columnWidth: '50%', - } - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: 1, - }, - series: [{ - name: "Development", - data: [30, 20, 50, 40, 60, 50] - },{ - name: "Marketing", - data: [200, 130, 90, 240, 130, 220] - },{ - name: "Sales", - data: [300, 200, 160, 400, 250, 250] - },{ - name: "Sales", - data: [200, 130, 90, 240, 130, 220] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - categories: ['2013', '2014', '2015', '2016', '2017', '2018'], - }, - yaxis: { - labels: { - padding: 4 - }, - }, - colors: [tabler.getColor("green"), tabler.getColor("pink"), tabler.getColor("green"), tabler.getColor("primary")], - legend: { - show: false, - }, - })).render(); -}); - diff --git a/mc_web_console_front/assets/jsOld/debug/tabler/form-elements.js b/mc_web_console_front/assets/jsOld/debug/tabler/form-elements.js deleted file mode 100644 index 2bd11cbc..00000000 --- a/mc_web_console_front/assets/jsOld/debug/tabler/form-elements.js +++ /dev/null @@ -1,358 +0,0 @@ - -import Litepicker from 'litepicker'; -import * as noUiSlider from 'nouislider/dist/nouislider.min'; -import TomSelect from 'tom-select'; - - -document.addEventListener("DOMContentLoaded", function () { - var el; - window && (new TomSelect(el = document.getElementById('select-states'), { - copyClassesToDropdown: false, - dropdownParent: 'body', - controlInput: '', - render: { - item: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - option: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - }, - })); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (noUiSlider.create(document.getElementById('range-simple'), { - start: 20, - connect: [true, false], - step: 10, - range: { - min: 0, - max: 100 - } - })); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (noUiSlider.create(document.getElementById('range-connect'), { - start: [60, 90], - connect: [false, true, false], - step: 10, - range: { - min: 0, - max: 100 - } - })); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (noUiSlider.create(document.getElementById('range-color'), { - start: 40, - connect: [true, false], - step: 10, - range: { - min: 0, - max: 100 - } - })); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new Litepicker({ - element: document.getElementById('datepicker-default'), - buttonText: { - previousMonth: ` - `, - nextMonth: ` - `, - }, - })); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new Litepicker({ - element: document.getElementById('datepicker-icon'), - buttonText: { - previousMonth: ` - `, - nextMonth: ` - `, - }, - })); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new Litepicker({ - element: document.getElementById('datepicker-icon-prepend'), - buttonText: { - previousMonth: ` - `, - nextMonth: ` - `, - }, - })); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new Litepicker({ - element: document.getElementById('datepicker-inline'), - buttonText: { - previousMonth: ` - `, - nextMonth: ` - `, - }, - inlineMode: true, - })); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - var el; - window && (new TomSelect(el = document.getElementById('select-tags'), { - copyClassesToDropdown: false, - dropdownParent: 'body', - controlInput: '', - render: { - item: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - option: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - }, - })); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - var el; - window && (new TomSelect(el = document.getElementById('select-users'), { - copyClassesToDropdown: false, - dropdownParent: 'body', - controlInput: '', - render: { - item: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - option: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - }, - })); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - var el; - window && (new TomSelect(el = document.getElementById('select-optgroups'), { - copyClassesToDropdown: false, - dropdownParent: 'body', - controlInput: '', - render: { - item: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - option: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - }, - })); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - var el; - window && (new TomSelect(el = document.getElementById('select-people'), { - copyClassesToDropdown: false, - dropdownParent: 'body', - controlInput: '', - render: { - item: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - option: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - }, - })); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - var el; - window && (new TomSelect(el = document.getElementById('select-countries'), { - copyClassesToDropdown: false, - dropdownParent: 'body', - controlInput: '', - render: { - item: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - option: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - }, - })); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - var el; - window && (new TomSelect(el = document.getElementById('select-labels'), { - copyClassesToDropdown: false, - dropdownParent: 'body', - controlInput: '', - render: { - item: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - option: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - }, - })); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - var el; - window && (new TomSelect(el = document.getElementById('select-countries-valid'), { - copyClassesToDropdown: false, - dropdownParent: 'body', - controlInput: '', - render: { - item: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - option: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - }, - })); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - var el; - window && (new TomSelect(el = document.getElementById('select-countries-invalid'), { - copyClassesToDropdown: false, - dropdownParent: 'body', - controlInput: '', - render: { - item: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - option: function (data, escape) { - if (data.customProperties) { - return '
    ' + data.customProperties + '' + escape(data.text) + '
    '; - } - return '
    ' + escape(data.text) + '
    '; - }, - }, - })); -}); - - - -document.addEventListener("DOMContentLoaded", function () { - let sliderTriggerList = [].slice.call(document.querySelectorAll("[data-slider]")); - sliderTriggerList.map(function (sliderTriggerEl) { - let options = {}; - if (sliderTriggerEl.getAttribute("data-slider")) { - options = JSON.parse(sliderTriggerEl.getAttribute("data-slider")); - } - let slider = noUiSlider.create(sliderTriggerEl, options); - if (options['js-name']) { - window[options['js-name']] = slider; - } - }); -}); diff --git a/mc_web_console_front/assets/jsOld/debug/tabler/index.js b/mc_web_console_front/assets/jsOld/debug/tabler/index.js deleted file mode 100644 index a68c4dd3..00000000 --- a/mc_web_console_front/assets/jsOld/debug/tabler/index.js +++ /dev/null @@ -1,593 +0,0 @@ -import ApexCharts from 'apexcharts'; - -import jsVectorMap from 'jsvectormap'; -import 'jsvectormap/dist/maps/world.js'; - - -document.addEventListener("DOMContentLoaded", function () { - console.log(window.ApexCharts) - window && (new ApexCharts(document.getElementById('chart-revenue-bg'), { - chart: { - type: "area", - fontFamily: 'inherit', - height: 40.0, - sparkline: { - enabled: true - }, - animations: { - enabled: false - }, - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: .16, - type: 'solid' - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Profits", - data: [37, 35, 44, 28, 36, 24, 65, 31, 37, 39, 62, 51, 35, 41, 35, 27, 93, 53, 61, 27, 54, 43, 19, 46, 39, 62, 51, 35, 41, 67] - }], - tooltip: { - theme: 'dark' - }, - grid: { - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - })).render(); - - - - - - - window && (new ApexCharts(document.getElementById('chart-new-clients'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 40.0, - sparkline: { - enabled: true - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - stroke: { - width: [2, 1], - dashArray: [0, 3], - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "May", - data: [37, 35, 44, 28, 36, 24, 65, 31, 37, 39, 62, 51, 35, 41, 35, 27, 93, 53, 61, 27, 54, 43, 4, 46, 39, 62, 51, 35, 41, 67] - }, { - name: "April", - data: [93, 54, 51, 24, 35, 35, 31, 67, 19, 43, 28, 36, 62, 61, 27, 39, 35, 41, 27, 35, 51, 46, 62, 37, 44, 53, 41, 65, 39, 37] - }], - tooltip: { - theme: 'dark' - }, - grid: { - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19' - ], - colors: [tabler.getColor("primary"), tabler.getColor("gray-600")], - legend: { - show: false, - }, - })).render(); - - - - - - - window && (new ApexCharts(document.getElementById('chart-active-users'), { - chart: { - type: "bar", - fontFamily: 'inherit', - height: 40.0, - sparkline: { - enabled: true - }, - animations: { - enabled: false - }, - }, - plotOptions: { - bar: { - columnWidth: '50%', - } - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: 1, - }, - series: [{ - name: "Profits", - data: [37, 35, 44, 28, 36, 24, 65, 31, 37, 39, 62, 51, 35, 41, 35, 27, 93, 53, 61, 27, 54, 43, 19, 46, 39, 62, 51, 35, 41, 67] - }], - tooltip: { - theme: 'dark' - }, - grid: { - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - })).render(); - - - - - - - window && (new ApexCharts(document.getElementById('chart-mentions'), { - chart: { - type: "bar", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - stacked: true, - }, - plotOptions: { - bar: { - columnWidth: '50%', - } - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: 1, - }, - series: [{ - name: "Web", - data: [1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 2, 12, 5, 8, 22, 6, 8, 6, 4, 1, 8, 24, 29, 51, 40, 47, 23, 26, 50, 26, 41, 22, 46, 47, 81, 46, 6] - }, { - name: "Social", - data: [2, 5, 4, 3, 3, 1, 4, 7, 5, 1, 2, 5, 3, 2, 6, 7, 7, 1, 5, 5, 2, 12, 4, 6, 18, 3, 5, 2, 13, 15, 20, 47, 18, 15, 11, 10, 0] - }, { - name: "Other", - data: [2, 9, 1, 7, 8, 3, 6, 5, 5, 4, 6, 4, 1, 9, 3, 6, 7, 5, 2, 8, 4, 9, 1, 2, 6, 7, 5, 1, 8, 3, 2, 3, 4, 9, 7, 1, 6] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - xaxis: { - lines: { - show: true - } - }, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19', '2020-07-20', '2020-07-21', '2020-07-22', '2020-07-23', '2020-07-24', '2020-07-25', '2020-07-26' - ], - colors: [tabler.getColor("primary"), tabler.getColor("primary", 0.8), tabler.getColor("green", 0.8)], - legend: { - show: false, - }, - })).render(); - - - - - - - const map = new jsVectorMap({ - selector: '#map-world', - map: 'world', - backgroundColor: 'transparent', - regionStyle: { - initial: { - fill: tabler.getColor('body-bg'), - stroke: tabler.getColor('border-color'), - strokeWidth: 2, - } - }, - zoomOnScroll: false, - zoomButtons: false, - // -------- Series -------- - visualizeData: { - scale: [tabler.getColor('bg-surface'), tabler.getColor('primary')], - values: { "AF": 16, "AL": 11, "DZ": 158, "AO": 85, "AG": 1, "AR": 351, "AM": 8, "AU": 1219, "AT": 366, "AZ": 52, "BS": 7, "BH": 21, "BD": 105, "BB": 3, "BY": 52, "BE": 461, "BZ": 1, "BJ": 6, "BT": 1, "BO": 19, "BA": 16, "BW": 12, "BR": 2023, "BN": 11, "BG": 44, "BF": 8, "BI": 1, "KH": 11, "CM": 21, "CA": 1563, "CV": 1, "CF": 2, "TD": 7, "CL": 199, "CN": 5745, "CO": 283, "KM": 0, "CD": 12, "CG": 11, "CR": 35, "CI": 22, "HR": 59, "CY": 22, "CZ": 195, "DK": 304, "DJ": 1, "DM": 0, "DO": 50, "EC": 61, "EG": 216, "SV": 21, "GQ": 14, "ER": 2, "EE": 19, "ET": 30, "FJ": 3, "FI": 231, "FR": 2555, "GA": 12, "GM": 1, "GE": 11, "DE": 3305, "GH": 18, "GR": 305, "GD": 0, "GT": 40, "GN": 4, "GW": 0, "GY": 2, "HT": 6, "HN": 15, "HK": 226, "HU": 132, "IS": 12, "IN": 1430, "ID": 695, "IR": 337, "IQ": 84, "IE": 204, "IL": 201, "IT": 2036, "JM": 13, "JP": 5390, "JO": 27, "KZ": 129, "KE": 32, "KI": 0, "KR": 986, "KW": 117, "KG": 4, "LA": 6, "LV": 23, "LB": 39, "LS": 1, "LR": 0, "LY": 77, "LT": 35, "LU": 52, "MK": 9, "MG": 8, "MW": 5, "MY": 218, "MV": 1, "ML": 9, "MT": 7, "MR": 3, "MU": 9, "MX": 1004, "MD": 5, "MN": 5, "ME": 3, "MA": 91, "MZ": 10, "MM": 35, "NA": 11, "NP": 15, "NL": 770, "NZ": 138, "NI": 6, "NE": 5, "NG": 206, "NO": 413, "OM": 53, "PK": 174, "PA": 27, "PG": 8, "PY": 17, "PE": 153, "PH": 189, "PL": 438, "PT": 223, "QA": 126, "RO": 158, "RU": 1476, "RW": 5, "WS": 0, "ST": 0, "SA": 434, "SN": 12, "RS": 38, "SC": 0, "SL": 1, "SG": 217, "SK": 86, "SI": 46, "SB": 0, "ZA": 354, "ES": 1374, "LK": 48, "KN": 0, "LC": 1, "VC": 0, "SD": 65, "SR": 3, "SZ": 3, "SE": 444, "CH": 522, "SY": 59, "TW": 426, "TJ": 5, "TZ": 22, "TH": 312, "TL": 0, "TG": 3, "TO": 0, "TT": 21, "TN": 43, "TR": 729, "TM": 0, "UG": 17, "UA": 136, "AE": 239, "GB": 2258, "US": 4624, "UY": 40, "UZ": 37, "VU": 0, "VE": 285, "VN": 101, "YE": 30, "ZM": 15, "ZW": 5 }, - }, - }); - window.addEventListener("resize", () => { - map.updateSize(); - }); - - - - - - - window && (new ApexCharts(document.getElementById('sparkline-activity'), { - chart: { - type: "radialBar", - fontFamily: 'inherit', - height: 40, - width: 40, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - plotOptions: { - radialBar: { - hollow: { - margin: 0, - size: '75%' - }, - track: { - margin: 0 - }, - dataLabels: { - show: false - } - } - }, - colors: [tabler.getColor("blue")], - series: [35], - })).render(); - - - - - - - window && (new ApexCharts(document.getElementById('chart-development-activity'), { - chart: { - type: "area", - fontFamily: 'inherit', - height: 192, - sparkline: { - enabled: true - }, - animations: { - enabled: false - }, - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: .16, - type: 'solid' - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Purchases", - data: [3, 5, 4, 6, 7, 5, 6, 8, 24, 7, 12, 5, 6, 3, 8, 4, 14, 30, 17, 19, 15, 14, 25, 32, 40, 55, 60, 48, 52, 70] - }], - tooltip: { - theme: 'dark' - }, - grid: { - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - point: { - show: false - }, - })).render(); - - - - - - - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-1'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [17, 24, 20, 10, 5, 1, 4, 18, 13] - }], - })).render(); - - - - - - - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-2'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [13, 11, 19, 22, 12, 7, 14, 3, 21] - }], - })).render(); - - - - - - - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-3'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [10, 13, 10, 4, 17, 3, 23, 22, 19] - }], - })).render(); - - - - - - - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-4'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [6, 15, 13, 13, 5, 7, 17, 20, 19] - }], - })).render(); - - - - - - - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-5'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [2, 11, 15, 14, 21, 20, 8, 23, 18, 14] - }], - })).render(); - - - - - - - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-6'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [22, 12, 7, 14, 3, 21, 8, 23, 18, 14] - }], - })).render(); -}); - diff --git a/mc_web_console_front/assets/jsOld/debug/tabler/layout-combo.js b/mc_web_console_front/assets/jsOld/debug/tabler/layout-combo.js deleted file mode 100644 index 2f03cf50..00000000 --- a/mc_web_console_front/assets/jsOld/debug/tabler/layout-combo.js +++ /dev/null @@ -1,592 +0,0 @@ -import ApexCharts from 'apexcharts'; - -import jsVectorMap from 'jsvectormap'; -import 'jsvectormap/dist/maps/world.js'; - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-revenue-bg'), { - chart: { - type: "area", - fontFamily: 'inherit', - height: 40.0, - sparkline: { - enabled: true - }, - animations: { - enabled: false - }, - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: .16, - type: 'solid' - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Profits", - data: [37, 35, 44, 28, 36, 24, 65, 31, 37, 39, 62, 51, 35, 41, 35, 27, 93, 53, 61, 27, 54, 43, 19, 46, 39, 62, 51, 35, 41, 67] - }], - tooltip: { - theme: 'dark' - }, - grid: { - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-new-clients'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 40.0, - sparkline: { - enabled: true - }, - animations: { - enabled: false - }, - }, - fill: { - opacity: 1, - }, - stroke: { - width: [2, 1], - dashArray: [0, 3], - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "May", - data: [37, 35, 44, 28, 36, 24, 65, 31, 37, 39, 62, 51, 35, 41, 35, 27, 93, 53, 61, 27, 54, 43, 4, 46, 39, 62, 51, 35, 41, 67] - }, { - name: "April", - data: [93, 54, 51, 24, 35, 35, 31, 67, 19, 43, 28, 36, 62, 61, 27, 39, 35, 41, 27, 35, 51, 46, 62, 37, 44, 53, 41, 65, 39, 37] - }], - tooltip: { - theme: 'dark' - }, - grid: { - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19' - ], - colors: [tabler.getColor("primary"), tabler.getColor("gray-600")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-active-users'), { - chart: { - type: "bar", - fontFamily: 'inherit', - height: 40.0, - sparkline: { - enabled: true - }, - animations: { - enabled: false - }, - }, - plotOptions: { - bar: { - columnWidth: '50%', - } - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: 1, - }, - series: [{ - name: "Profits", - data: [37, 35, 44, 28, 36, 24, 65, 31, 37, 39, 62, 51, 35, 41, 35, 27, 93, 53, 61, 27, 54, 43, 19, 46, 39, 62, 51, 35, 41, 67] - }], - tooltip: { - theme: 'dark' - }, - grid: { - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-mentions'), { - chart: { - type: "bar", - fontFamily: 'inherit', - height: 240, - parentHeightOffset: 0, - toolbar: { - show: false, - }, - animations: { - enabled: false - }, - stacked: true, - }, - plotOptions: { - bar: { - columnWidth: '50%', - } - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: 1, - }, - series: [{ - name: "Web", - data: [1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 2, 12, 5, 8, 22, 6, 8, 6, 4, 1, 8, 24, 29, 51, 40, 47, 23, 26, 50, 26, 41, 22, 46, 47, 81, 46, 6] - }, { - name: "Social", - data: [2, 5, 4, 3, 3, 1, 4, 7, 5, 1, 2, 5, 3, 2, 6, 7, 7, 1, 5, 5, 2, 12, 4, 6, 18, 3, 5, 2, 13, 15, 20, 47, 18, 15, 11, 10, 0] - }, { - name: "Other", - data: [2, 9, 1, 7, 8, 3, 6, 5, 5, 4, 6, 4, 1, 9, 3, 6, 7, 5, 2, 8, 4, 9, 1, 2, 6, 7, 5, 1, 8, 3, 2, 3, 4, 9, 7, 1, 6] - }], - tooltip: { - theme: 'dark' - }, - grid: { - padding: { - top: -20, - right: 0, - left: -4, - bottom: -4 - }, - strokeDashArray: 4, - xaxis: { - lines: { - show: true - } - }, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19', '2020-07-20', '2020-07-21', '2020-07-22', '2020-07-23', '2020-07-24', '2020-07-25', '2020-07-26' - ], - colors: [tabler.getColor("primary"), tabler.getColor("primary", 0.8), tabler.getColor("green", 0.8)], - legend: { - show: false, - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - const map = new jsVectorMap({ - selector: '#map-world', - map: 'world', - backgroundColor: 'transparent', - regionStyle: { - initial: { - fill: tabler.getColor('body-bg'), - stroke: tabler.getColor('border-color'), - strokeWidth: 2, - } - }, - zoomOnScroll: false, - zoomButtons: false, - // -------- Series -------- - visualizeData: { - scale: [tabler.getColor('bg-surface'), tabler.getColor('primary')], - values: { "AF": 16, "AL": 11, "DZ": 158, "AO": 85, "AG": 1, "AR": 351, "AM": 8, "AU": 1219, "AT": 366, "AZ": 52, "BS": 7, "BH": 21, "BD": 105, "BB": 3, "BY": 52, "BE": 461, "BZ": 1, "BJ": 6, "BT": 1, "BO": 19, "BA": 16, "BW": 12, "BR": 2023, "BN": 11, "BG": 44, "BF": 8, "BI": 1, "KH": 11, "CM": 21, "CA": 1563, "CV": 1, "CF": 2, "TD": 7, "CL": 199, "CN": 5745, "CO": 283, "KM": 0, "CD": 12, "CG": 11, "CR": 35, "CI": 22, "HR": 59, "CY": 22, "CZ": 195, "DK": 304, "DJ": 1, "DM": 0, "DO": 50, "EC": 61, "EG": 216, "SV": 21, "GQ": 14, "ER": 2, "EE": 19, "ET": 30, "FJ": 3, "FI": 231, "FR": 2555, "GA": 12, "GM": 1, "GE": 11, "DE": 3305, "GH": 18, "GR": 305, "GD": 0, "GT": 40, "GN": 4, "GW": 0, "GY": 2, "HT": 6, "HN": 15, "HK": 226, "HU": 132, "IS": 12, "IN": 1430, "ID": 695, "IR": 337, "IQ": 84, "IE": 204, "IL": 201, "IT": 2036, "JM": 13, "JP": 5390, "JO": 27, "KZ": 129, "KE": 32, "KI": 0, "KR": 986, "KW": 117, "KG": 4, "LA": 6, "LV": 23, "LB": 39, "LS": 1, "LR": 0, "LY": 77, "LT": 35, "LU": 52, "MK": 9, "MG": 8, "MW": 5, "MY": 218, "MV": 1, "ML": 9, "MT": 7, "MR": 3, "MU": 9, "MX": 1004, "MD": 5, "MN": 5, "ME": 3, "MA": 91, "MZ": 10, "MM": 35, "NA": 11, "NP": 15, "NL": 770, "NZ": 138, "NI": 6, "NE": 5, "NG": 206, "NO": 413, "OM": 53, "PK": 174, "PA": 27, "PG": 8, "PY": 17, "PE": 153, "PH": 189, "PL": 438, "PT": 223, "QA": 126, "RO": 158, "RU": 1476, "RW": 5, "WS": 0, "ST": 0, "SA": 434, "SN": 12, "RS": 38, "SC": 0, "SL": 1, "SG": 217, "SK": 86, "SI": 46, "SB": 0, "ZA": 354, "ES": 1374, "LK": 48, "KN": 0, "LC": 1, "VC": 0, "SD": 65, "SR": 3, "SZ": 3, "SE": 444, "CH": 522, "SY": 59, "TW": 426, "TJ": 5, "TZ": 22, "TH": 312, "TL": 0, "TG": 3, "TO": 0, "TT": 21, "TN": 43, "TR": 729, "TM": 0, "UG": 17, "UA": 136, "AE": 239, "GB": 2258, "US": 4624, "UY": 40, "UZ": 37, "VU": 0, "VE": 285, "VN": 101, "YE": 30, "ZM": 15, "ZW": 5 }, - }, - }); - window.addEventListener("resize", () => { - map.updateSize(); - }); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('sparkline-activity'), { - chart: { - type: "radialBar", - fontFamily: 'inherit', - height: 40, - width: 40, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - plotOptions: { - radialBar: { - hollow: { - margin: 0, - size: '75%' - }, - track: { - margin: 0 - }, - dataLabels: { - show: false - } - } - }, - colors: [tabler.getColor("blue")], - series: [35], - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('chart-development-activity'), { - chart: { - type: "area", - fontFamily: 'inherit', - height: 192, - sparkline: { - enabled: true - }, - animations: { - enabled: false - }, - }, - dataLabels: { - enabled: false, - }, - fill: { - opacity: .16, - type: 'solid' - }, - stroke: { - width: 2, - lineCap: "round", - curve: "smooth", - }, - series: [{ - name: "Purchases", - data: [3, 5, 4, 6, 7, 5, 6, 8, 24, 7, 12, 5, 6, 3, 8, 4, 14, 30, 17, 19, 15, 14, 25, 32, 40, 55, 60, 48, 52, 70] - }], - tooltip: { - theme: 'dark' - }, - grid: { - strokeDashArray: 4, - }, - xaxis: { - labels: { - padding: 0, - }, - tooltip: { - enabled: false - }, - axisBorder: { - show: false, - }, - type: 'datetime', - }, - yaxis: { - labels: { - padding: 4 - }, - }, - labels: [ - '2020-06-20', '2020-06-21', '2020-06-22', '2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26', '2020-06-27', '2020-06-28', '2020-06-29', '2020-06-30', '2020-07-01', '2020-07-02', '2020-07-03', '2020-07-04', '2020-07-05', '2020-07-06', '2020-07-07', '2020-07-08', '2020-07-09', '2020-07-10', '2020-07-11', '2020-07-12', '2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16', '2020-07-17', '2020-07-18', '2020-07-19' - ], - colors: [tabler.getColor("primary")], - legend: { - show: false, - }, - point: { - show: false - }, - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-1'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [17, 24, 20, 10, 5, 1, 4, 18, 13] - }], - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-2'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [13, 11, 19, 22, 12, 7, 14, 3, 21] - }], - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-3'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [10, 13, 10, 4, 17, 3, 23, 22, 19] - }], - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-4'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [6, 15, 13, 13, 5, 7, 17, 20, 19] - }], - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-5'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [2, 11, 15, 14, 21, 20, 8, 23, 18, 14] - }], - })).render(); -}); - - - - -document.addEventListener("DOMContentLoaded", function () { - window && (new ApexCharts(document.getElementById('sparkline-bounce-rate-6'), { - chart: { - type: "line", - fontFamily: 'inherit', - height: 24, - animations: { - enabled: false - }, - sparkline: { - enabled: true - }, - }, - tooltip: { - enabled: false, - }, - stroke: { - width: 2, - lineCap: "round", - }, - series: [{ - color: tabler.getColor("primary"), - data: [22, 12, 7, 14, 3, 21, 8, 23, 18, 14] - }], - })).render(); -}); - diff --git a/mc_web_console_front/assets/jsOld/debug/tabulator/tabulator.js b/mc_web_console_front/assets/jsOld/debug/tabulator/tabulator.js deleted file mode 100644 index 06a0dfae..00000000 --- a/mc_web_console_front/assets/jsOld/debug/tabulator/tabulator.js +++ /dev/null @@ -1,33 +0,0 @@ -import { TabulatorFull as Tabulator } from 'tabulator-tables'; - -var tabledata = [ - {id:1, name:"Oli Bob", age:"12", col:"red", dob:""}, - {id:2, name:"Mary May", age:"1", col:"blue", dob:"14/05/1982"}, - {id:3, name:"Christine Lobowski", age:"42", col:"green", dob:"22/05/1982"}, - {id:4, name:"Brendon Philips", age:"125", col:"orange", dob:"01/08/1980"}, - {id:5, name:"Margret Marmajuke", age:"16", col:"yellow", dob:"31/01/1999"}, - {id:5, name:"Margret 1", age:"16", col:"yellow", dob:"31/01/1999"}, -]; - -//create Tabulator on DOM element with id "example-table" -var table = new Tabulator("#example-table", { - data: tabledata, //assign data to table - layout:"fitColumns", - resizableColumnFit:true, - - pagination:"local", - paginationSize:6, - paginationSizeSelector:[3, 6, 8, 10], - movableColumns:true, - paginationCounter:"rows", - - columns:[ //Define Table Columns - {title:"Name", field:"name"}, - {title:"Measurement", field:"col"}, - {title:"Target Type", field:"col"}, - {title:"Targer ID", field:"col"}, - {title:"Alert Event Type", field:"col"}, - {title:"Alert Event Name", field:"col"}, - ], - -}); \ No newline at end of file diff --git a/mc_web_console_front/assets/jsOld/debug/workflow/workflow.js b/mc_web_console_front/assets/jsOld/debug/workflow/workflow.js deleted file mode 100644 index b0b5c1c1..00000000 --- a/mc_web_console_front/assets/jsOld/debug/workflow/workflow.js +++ /dev/null @@ -1,206 +0,0 @@ -/* global document, sequentialWorkflowDesigner, console, localStorage */ -import { Designer } from 'sequential-workflow-designer'; - -function createTaskStep(id, type, name, properties) { - return { - id, - componentType: 'task', - type, - name, - properties: properties || {} - }; -} - -function createIfStep(id, _true, _false) { - return { - id, - componentType: 'switch', - type: 'if', - name: 'If', - branches: { - 'true': _true, - 'false': _false - }, - properties: {} - }; -} - -function createContainerStep(id, steps) { - return { - id, - componentType: 'container', - type: 'loop', - name: 'Loop', - properties: {}, - sequence: steps - }; -} - -function toolboxGroup(name) { - return { - name, - steps: [ - createTaskStep(null, 'save', 'Save file'), - createTaskStep(null, 'text', 'Send email'), - createTaskStep(null, 'task', 'Create task'), - createIfStep(null, [], []), - createContainerStep(null, []) - ] - }; -} - -function reloadChangeReadonlyButtonText() { - changeReadonlyButton.innerText = 'Readonly: ' + (designer.isReadonly() ? 'ON' : 'OFF'); -} - -export function appendCheckbox(root, label, isReadonly, isChecked, onClick) { - const item = document.createElement('div'); - item.innerHTML = '

    '; - const h3 = item.getElementsByTagName('h3')[0]; - h3.innerText = label; - const input = item.getElementsByTagName('input')[0]; - input.checked = isChecked; - if (isReadonly) { - input.setAttribute('disabled', 'disabled'); - } - input.addEventListener('click', () => { - onClick(input.checked); - }); - root.appendChild(item); -} - -function appendPath(root, step) { - const parents = designer.getStepParents(step); - const path = document.createElement('div'); - path.className = 'step-path'; - path.innerText = 'Step path: ' + parents.map((parent) => { - return typeof parent === 'string' ? parent : parent.name; - }).join('/'); - root.appendChild(path); -} - -let designer; -let changeReadonlyButton; -let validationStatusText; -const localStorageKey = 'sqdFullscreen'; - -function refreshValidationStatus() { - validationStatusText.innerText = designer.isValid() ? 'Definition is valid' : 'Definition is invalid'; -} - -function loadState() { - const state = localStorage[localStorageKey]; - if (state) { - return JSON.parse(state); - } - return { - definition: getStartDefinition() - } -} - -function saveState() { - localStorage[localStorageKey] = JSON.stringify({ - definition: designer.getDefinition(), - undoStack: designer.dumpUndoStack() - }); -} - -const initialState = loadState(); - -const configuration = { - undoStackSize: 20, - undoStack: initialState.undoStack, - - toolbox: { - groups: [ - toolboxGroup('Main'), - toolboxGroup('File system'), - toolboxGroup('E-mail') - ] - }, - - controlBar: true, - - steps: { - isDuplicable: () => true, - iconUrlProvider: (_, type) => { - return `/assets/images/workflow/icon-${type}.svg` - }, - }, - - validator: { - step: (step) => { - return !step.properties['isInvalid']; - } - }, - - editors: { - rootEditorProvider: (definition, _context, isReadonly) => { - const root = document.createElement('div'); - root.className = 'definition-json'; - root.innerHTML = ''; - const textarea = root.getElementsByTagName('textarea')[0]; - if (isReadonly) { - textarea.setAttribute('readonly', 'readonly'); - } - textarea.value = JSON.stringify(definition, null, 2); - return root; - }, - - stepEditorProvider: (step, editorContext, _definition, isReadonly) => { - const root = document.createElement('div'); - - appendCheckbox(root, 'Is invalid', isReadonly, !!step.properties['isInvalid'], (checked) => { - step.properties['isInvalid'] = checked; - editorContext.notifyPropertiesChanged(); - }); - - if (step.type === 'if') { - appendCheckbox(root, 'Catch branch', isReadonly, !!step.branches['catch'], (checked) => { - if (checked) { - step.branches['catch'] = []; - } else { - delete step.branches['catch']; - } - editorContext.notifyChildrenChanged(); - }); - } - - appendPath(root, step); - return root; - } - } -}; - -function getStartDefinition() { - return { - properties: {}, - sequence: [ - createIfStep('00000000000000000000000000000001', - [ createTaskStep('00000000000000000000000000000002', 'save', 'Save file', { isInvalid: true }) ], - [ createTaskStep('00000000000000000000000000000003', 'text', 'Send email') ] - ), - createContainerStep('00000000000000000000000000000004', [ - createTaskStep('00000000000000000000000000000005', 'task', 'Create task') - ]) - ] - }; -} - -const placeholder = document.getElementById('designer'); -designer = Designer.create(placeholder, initialState.definition, configuration); -designer.onDefinitionChanged.subscribe((newDefinition) => { - refreshValidationStatus(); - saveState(); - console.log('the definition has changed', newDefinition); -}); - -changeReadonlyButton = document.getElementById('changeReadonlyButton'); -changeReadonlyButton.addEventListener('click', () => { - designer.setIsReadonly(!designer.isReadonly()); - reloadChangeReadonlyButtonText(); -}); -reloadChangeReadonlyButtonText(); - -validationStatusText = document.getElementById('validationStatus'); -refreshValidationStatus(); diff --git a/mc_web_console_front/assets/jsOld/operation/about/about.js b/mc_web_console_front/assets/jsOld/operation/about/about.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/operation/dashboard/global.js b/mc_web_console_front/assets/jsOld/operation/dashboard/global.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/operation/dashboard/ns.js b/mc_web_console_front/assets/jsOld/operation/dashboard/ns.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/operation/manage/mcis.js b/mc_web_console_front/assets/jsOld/operation/manage/mcis.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/operation/manage/mcks.js b/mc_web_console_front/assets/jsOld/operation/manage/mcks.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/operation/manage/pmks.js b/mc_web_console_front/assets/jsOld/operation/manage/pmks.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/operation/monitoring/mcis.js b/mc_web_console_front/assets/jsOld/operation/monitoring/mcis.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/operation/policy/monitoring.js b/mc_web_console_front/assets/jsOld/operation/policy/monitoring.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/operation/policy/threshold.js b/mc_web_console_front/assets/jsOld/operation/policy/threshold.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/operation/service/nlb.js b/mc_web_console_front/assets/jsOld/operation/service/nlb.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/operation/about/about.js b/mc_web_console_front/assets/jsOld/partials/operation/about/about.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/operation/dashboard/global.js b/mc_web_console_front/assets/jsOld/partials/operation/dashboard/global.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/operation/dashboard/ns.js b/mc_web_console_front/assets/jsOld/partials/operation/dashboard/ns.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/operation/manage/mcis.js b/mc_web_console_front/assets/jsOld/partials/operation/manage/mcis.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/operation/manage/mcks.js b/mc_web_console_front/assets/jsOld/partials/operation/manage/mcks.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/operation/manage/pmks.js b/mc_web_console_front/assets/jsOld/partials/operation/manage/pmks.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/operation/monitoring/mcis.js b/mc_web_console_front/assets/jsOld/partials/operation/monitoring/mcis.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/operation/policy/monitoring.js b/mc_web_console_front/assets/jsOld/partials/operation/policy/monitoring.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/operation/policy/threshold.js b/mc_web_console_front/assets/jsOld/partials/operation/policy/threshold.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/operation/service/nlb.js b/mc_web_console_front/assets/jsOld/partials/operation/service/nlb.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/operation/worldmap.js b/mc_web_console_front/assets/jsOld/partials/operation/worldmap.js deleted file mode 100644 index 63a19d1b..00000000 --- a/mc_web_console_front/assets/jsOld/partials/operation/worldmap.js +++ /dev/null @@ -1,31 +0,0 @@ -// import jsVectorMap from 'jsvectormap' -// import 'jsvectormap/dist/maps/world.js' - -// import tabler from '../../common/tabler/tabler' - -// document.addEventListener("DOMContentLoaded", function () { -// const map = new jsVectorMap({ -// selector: '#map-world', -// map: 'world', -// backgroundColor: 'transparent', -// regionStyle: { -// initial: { -// // fill: tabler.getColor('body-bg'), -// // stroke: tabler.getColor('border-color'), -// fill: rgba(255,255,255,1), -// stroke: rgba(255,255,255,1), -// strokeWidth: 2, -// } -// }, -// zoomOnScroll: false, -// zoomButtons: false, -// // -------- Series -------- -// visualizeData: { -// scale: [tabler.getColor('bg-surface'), tabler.getColor('primary')], -// values: { "AF": 16, "AL": 11, "DZ": 158, "AO": 85, "AG": 1, "AR": 351, "AM": 8, "AU": 1219, "AT": 366, "AZ": 52, "BS": 7, "BH": 21, "BD": 105, "BB": 3, "BY": 52, "BE": 461, "BZ": 1, "BJ": 6, "BT": 1, "BO": 19, "BA": 16, "BW": 12, "BR": 2023, "BN": 11, "BG": 44, "BF": 8, "BI": 1, "KH": 11, "CM": 21, "CA": 1563, "CV": 1, "CF": 2, "TD": 7, "CL": 199, "CN": 5745, "CO": 283, "KM": 0, "CD": 12, "CG": 11, "CR": 35, "CI": 22, "HR": 59, "CY": 22, "CZ": 195, "DK": 304, "DJ": 1, "DM": 0, "DO": 50, "EC": 61, "EG": 216, "SV": 21, "GQ": 14, "ER": 2, "EE": 19, "ET": 30, "FJ": 3, "FI": 231, "FR": 2555, "GA": 12, "GM": 1, "GE": 11, "DE": 3305, "GH": 18, "GR": 305, "GD": 0, "GT": 40, "GN": 4, "GW": 0, "GY": 2, "HT": 6, "HN": 15, "HK": 226, "HU": 132, "IS": 12, "IN": 1430, "ID": 695, "IR": 337, "IQ": 84, "IE": 204, "IL": 201, "IT": 2036, "JM": 13, "JP": 5390, "JO": 27, "KZ": 129, "KE": 32, "KI": 0, "KR": 986, "KW": 117, "KG": 4, "LA": 6, "LV": 23, "LB": 39, "LS": 1, "LR": 0, "LY": 77, "LT": 35, "LU": 52, "MK": 9, "MG": 8, "MW": 5, "MY": 218, "MV": 1, "ML": 9, "MT": 7, "MR": 3, "MU": 9, "MX": 1004, "MD": 5, "MN": 5, "ME": 3, "MA": 91, "MZ": 10, "MM": 35, "NA": 11, "NP": 15, "NL": 770, "NZ": 138, "NI": 6, "NE": 5, "NG": 206, "NO": 413, "OM": 53, "PK": 174, "PA": 27, "PG": 8, "PY": 17, "PE": 153, "PH": 189, "PL": 438, "PT": 223, "QA": 126, "RO": 158, "RU": 1476, "RW": 5, "WS": 0, "ST": 0, "SA": 434, "SN": 12, "RS": 38, "SC": 0, "SL": 1, "SG": 217, "SK": 86, "SI": 46, "SB": 0, "ZA": 354, "ES": 1374, "LK": 48, "KN": 0, "LC": 1, "VC": 0, "SD": 65, "SR": 3, "SZ": 3, "SE": 444, "CH": 522, "SY": 59, "TW": 426, "TJ": 5, "TZ": 22, "TH": 312, "TL": 0, "TG": 3, "TO": 0, "TT": 21, "TN": 43, "TR": 729, "TM": 0, "UG": 17, "UA": 136, "AE": 239, "GB": 2258, "US": 4624, "UY": 40, "UZ": 37, "VU": 0, "VE": 285, "VN": 101, "YE": 30, "ZM": 15, "ZW": 5 }, -// }, -// }); -// window.addEventListener("resize", () => { -// map.updateSize(); -// }); -// }); \ No newline at end of file diff --git a/mc_web_console_front/assets/jsOld/partials/setting/cloudconnections/cloudconnections.js b/mc_web_console_front/assets/jsOld/partials/setting/cloudconnections/cloudconnections.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/setting/namespace/namespace.js b/mc_web_console_front/assets/jsOld/partials/setting/namespace/namespace.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/setting/resources/disk.js b/mc_web_console_front/assets/jsOld/partials/setting/resources/disk.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/setting/resources/myimage.js b/mc_web_console_front/assets/jsOld/partials/setting/resources/myimage.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/setting/resources/network.js b/mc_web_console_front/assets/jsOld/partials/setting/resources/network.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/setting/resources/security.js b/mc_web_console_front/assets/jsOld/partials/setting/resources/security.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/setting/resources/serverimage.js b/mc_web_console_front/assets/jsOld/partials/setting/resources/serverimage.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/setting/resources/serverspec.js b/mc_web_console_front/assets/jsOld/partials/setting/resources/serverspec.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/partials/setting/resources/sshkey.js b/mc_web_console_front/assets/jsOld/partials/setting/resources/sshkey.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/setting/cloudconnections/cloudconnections.js b/mc_web_console_front/assets/jsOld/setting/cloudconnections/cloudconnections.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/setting/namespace/namespace.js b/mc_web_console_front/assets/jsOld/setting/namespace/namespace.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/setting/resources/disk.js b/mc_web_console_front/assets/jsOld/setting/resources/disk.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/setting/resources/myimage.js b/mc_web_console_front/assets/jsOld/setting/resources/myimage.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/setting/resources/network.js b/mc_web_console_front/assets/jsOld/setting/resources/network.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/setting/resources/security.js b/mc_web_console_front/assets/jsOld/setting/resources/security.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/setting/resources/serverimage.js b/mc_web_console_front/assets/jsOld/setting/resources/serverimage.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/setting/resources/serverspec.js b/mc_web_console_front/assets/jsOld/setting/resources/serverspec.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/jsOld/setting/resources/sshkey.js b/mc_web_console_front/assets/jsOld/setting/resources/sshkey.js deleted file mode 100644 index e69de29b..00000000 diff --git a/mc_web_console_front/assets/static/logo/logo-small.svg b/mc_web_console_front/assets/static/logo/logo-small.svg new file mode 100644 index 00000000..8e29c719 Binary files /dev/null and b/mc_web_console_front/assets/static/logo/logo-small.svg differ diff --git a/mc_web_console_front/go.mod b/mc_web_console_front/go.mod index 742ccd7f..5912a314 100644 --- a/mc_web_console_front/go.mod +++ b/mc_web_console_front/go.mod @@ -3,46 +3,39 @@ module mc_web_console_front go 1.21.0 require ( - github.com/davecgh/go-spew v1.1.1 github.com/gobuffalo/buffalo v1.1.0 github.com/gobuffalo/envy v1.10.2 github.com/gobuffalo/mw-csrf v1.0.2 github.com/gobuffalo/mw-forcessl v1.0.2 github.com/gobuffalo/mw-i18n/v2 v2.0.3 github.com/gobuffalo/mw-paramlogger v1.0.2 - github.com/gobuffalo/suite/v4 v4.0.4 - github.com/gobuffalo/validate v2.0.4+incompatible - github.com/golang-jwt/jwt/v4 v4.5.0 - github.com/mitchellh/mapstructure v1.5.0 + github.com/golang-jwt/jwt v3.2.2+incompatible + github.com/lestrrat-go/jwx v1.2.29 github.com/unrolled/secure v1.14.0 ) require ( github.com/BurntSushi/toml v1.3.2 // indirect - github.com/Masterminds/semver/v3 v3.2.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/fatih/color v1.15.0 // indirect github.com/fatih/structs v1.1.0 // indirect github.com/felixge/httpsnoop v1.0.3 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/go-sql-driver/mysql v1.7.1 // indirect github.com/gobuffalo/events v1.4.3 // indirect - github.com/gobuffalo/fizz v1.14.4 // indirect github.com/gobuffalo/flect v1.0.2 // indirect github.com/gobuffalo/github_flavored_markdown v1.1.4 // indirect github.com/gobuffalo/grift v1.5.2 // indirect github.com/gobuffalo/helpers v0.6.7 // indirect - github.com/gobuffalo/httptest v1.5.2 // indirect github.com/gobuffalo/logger v1.0.7 // indirect github.com/gobuffalo/meta v0.3.3 // indirect - github.com/gobuffalo/middleware v1.0.0 // indirect github.com/gobuffalo/nulls v0.4.2 // indirect github.com/gobuffalo/plush/v4 v4.1.18 // indirect - github.com/gobuffalo/pop/v6 v6.1.1 // indirect github.com/gobuffalo/refresh v1.13.3 // indirect github.com/gobuffalo/tags/v3 v3.1.4 // indirect github.com/gobuffalo/validate/v3 v3.3.3 // indirect + github.com/goccy/go-json v0.10.2 // indirect github.com/gofrs/uuid v4.4.0+incompatible // indirect github.com/gorilla/css v1.0.0 // indirect github.com/gorilla/handlers v1.5.1 // indirect @@ -50,19 +43,13 @@ require ( github.com/gorilla/securecookie v1.1.1 // indirect github.com/gorilla/sessions v1.2.1 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/jackc/chunkreader/v2 v2.0.1 // indirect - github.com/jackc/pgconn v1.14.0 // indirect - github.com/jackc/pgio v1.0.0 // indirect - github.com/jackc/pgpassfile v1.0.0 // indirect - github.com/jackc/pgproto3/v2 v2.3.2 // indirect - github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect - github.com/jackc/pgtype v1.14.0 // indirect - github.com/jackc/pgx/v4 v4.18.1 // indirect - github.com/jmoiron/sqlx v1.3.5 // indirect github.com/joho/godotenv v1.5.1 // indirect - github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect github.com/kr/pretty v0.3.0 // indirect - github.com/luna-duclos/instrumentedsql v1.1.3 // indirect + github.com/lestrrat-go/backoff/v2 v2.0.8 // indirect + github.com/lestrrat-go/blackmagic v1.0.2 // indirect + github.com/lestrrat-go/httpcc v1.0.1 // indirect + github.com/lestrrat-go/iter v1.0.2 // indirect + github.com/lestrrat-go/option v1.0.1 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.19 // indirect github.com/mattn/go-sqlite3 v2.0.3+incompatible // indirect @@ -70,26 +57,21 @@ require ( github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/monoculum/formam v3.5.5+incompatible // indirect github.com/nicksnyder/go-i18n v1.10.1 // indirect - github.com/onsi/ginkgo v1.16.5 // indirect - github.com/onsi/gomega v1.32.0 // indirect github.com/pelletier/go-toml v1.9.5 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rogpeppe/go-internal v1.11.0 // indirect - github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e // indirect github.com/sergi/go-diff v1.3.1 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d // indirect github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e // indirect github.com/spf13/cobra v1.7.0 // indirect github.com/spf13/pflag v1.0.5 // indirect - github.com/stretchr/testify v1.8.2 // indirect - golang.org/x/crypto v0.18.0 // indirect + golang.org/x/crypto v0.21.0 // indirect golang.org/x/mod v0.12.0 // indirect - golang.org/x/net v0.20.0 // indirect + golang.org/x/net v0.21.0 // indirect golang.org/x/sync v0.3.0 // indirect - golang.org/x/sys v0.16.0 // indirect - golang.org/x/term v0.16.0 // indirect + golang.org/x/sys v0.18.0 // indirect + golang.org/x/term v0.18.0 // indirect golang.org/x/text v0.14.0 // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/yaml.v2 v2.4.0 // indirect diff --git a/mc_web_console_front/go.sum b/mc_web_console_front/go.sum index d5583e30..2080a0b3 100644 --- a/mc_web_console_front/go.sum +++ b/mc_web_console_front/go.sum @@ -1,23 +1,17 @@ -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v1.2.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8= github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= -github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= -github.com/Masterminds/semver/v3 v3.2.1 h1:RN9w6+7QoMeJVGyfmbcgs28Br8cvmnucEXnY0rYXWg0= -github.com/Masterminds/semver/v3 v3.2.1/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= -github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I= -github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ= -github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/decred/dcrd/crypto/blake256 v1.0.1/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= @@ -28,32 +22,19 @@ github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk= github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= -github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= -github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= -github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= -github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= -github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= -github.com/gobuffalo/attrs v1.0.3/go.mod h1:KvDJCE0avbufqS0Bw3UV7RQynESY0jjod+572ctX4t8= github.com/gobuffalo/buffalo v1.1.0 h1:6y1fUC47QWevaM1ImukJFHNgxiRIT+Y74VcP4ZQaz80= github.com/gobuffalo/buffalo v1.1.0/go.mod h1:lLsx9Y8bFYu9uvQyIEB3M0QA908ChHUPjwOGumZWARU= github.com/gobuffalo/envy v1.10.2 h1:EIi03p9c3yeuRCFPOKcSfajzkLb3hrRjEpHGI8I2Wo4= github.com/gobuffalo/envy v1.10.2/go.mod h1:qGAGwdvDsaEtPhfBzb3o0SfDea8ByGn9j8bKmVft9z8= github.com/gobuffalo/events v1.4.3 h1:JYDq7NbozP10zaN9Ijfem6Ozox2KacU2fU38RyquXM8= github.com/gobuffalo/events v1.4.3/go.mod h1:2BwfpV5X63t8xkUcVqIv4IbyAobJazRSVu1F1pgf3rc= -github.com/gobuffalo/fizz v1.14.4 h1:8uume7joF6niTNWN582IQ2jhGTUoa9g1fiV/tIoGdBs= -github.com/gobuffalo/fizz v1.14.4/go.mod h1:9/2fGNXNeIFOXEEgTPJwiK63e44RjG+Nc4hfMm1ArGM= github.com/gobuffalo/flect v0.3.0/go.mod h1:5pf3aGnsvqvCj50AVni7mJJF8ICxGZ8HomberC3pXLE= github.com/gobuffalo/flect v1.0.0/go.mod h1:l9V6xSb4BlXwsxEMj3FVEub2nkdQjWhPvD8XTTlHPQc= github.com/gobuffalo/flect v1.0.2 h1:eqjPGSo2WmjgY2XlpGwo2NXgL3RucAKo4k4qQMNA5sA= github.com/gobuffalo/flect v1.0.2/go.mod h1:A5msMlrHtLqh9umBSnvabjsMrCcCpAyzglnDvkbYKHs= -github.com/gobuffalo/genny/v2 v2.1.0/go.mod h1:4yoTNk4bYuP3BMM6uQKYPvtP6WsXFGm2w2EFYZdRls8= github.com/gobuffalo/github_flavored_markdown v1.1.3/go.mod h1:IzgO5xS6hqkDmUh91BW/+Qxo/qYnvfzoz3A7uLkg77I= github.com/gobuffalo/github_flavored_markdown v1.1.4 h1:WacrEGPXUDX+BpU1GM/Y0ADgMzESKNWls9hOTG1MHVs= github.com/gobuffalo/github_flavored_markdown v1.1.4/go.mod h1:Vl9686qrVVQou4GrHRK/KOG3jCZOKLUqV8MMOAYtlso= @@ -68,8 +49,6 @@ github.com/gobuffalo/logger v1.0.7 h1:LTLwWelETXDYyqF/ASf0nxaIcdEOIJNxRokPcfI/xb github.com/gobuffalo/logger v1.0.7/go.mod h1:u40u6Bq3VVvaMcy5sRBclD8SXhBYPS0Qk95ubt+1xJM= github.com/gobuffalo/meta v0.3.3 h1:GwPWdbdnp4JrKASvMLa03OtmzISq7z/nE7T6aMqzoYM= github.com/gobuffalo/meta v0.3.3/go.mod h1:o4B099IUFUfK4555Guqxz1zHAqyuUQ/KtHXi8WvVeFE= -github.com/gobuffalo/middleware v1.0.0 h1:7k3jWjdit45aK5Ri9DAKBKAp1QL3bXe2PCtWBBomMww= -github.com/gobuffalo/middleware v1.0.0/go.mod h1:ubE1XogeGL39dXeS0PEKLeEAdFcGXRMMwTW3RGXK/b4= github.com/gobuffalo/mw-csrf v1.0.2 h1:V/y6S6WPNlmxlXD6SPpQCHvm5GqcUuY6/bUrJd0zSZM= github.com/gobuffalo/mw-csrf v1.0.2/go.mod h1:lCddfZCNS+/t/Jj9b1iQsOCzouCzDqKMbZqaz/nC7Vo= github.com/gobuffalo/mw-forcessl v1.0.2 h1:U3HIib5CJ17xpnKMuuzDs5kRuY9UrSuSUkuM611TJ3U= @@ -80,43 +59,22 @@ github.com/gobuffalo/mw-paramlogger v1.0.2 h1:+NHJ7EeUx7cbTZstSTYtoQY1Lhs8xncltv github.com/gobuffalo/mw-paramlogger v1.0.2/go.mod h1:LzzUM7ujFZ7JCsgWA2GHemvhcHodXjD34cyEFmoAdX4= github.com/gobuffalo/nulls v0.4.2 h1:GAqBR29R3oPY+WCC7JL9KKk9erchaNuV6unsOSZGQkw= github.com/gobuffalo/nulls v0.4.2/go.mod h1:EElw2zmBYafU2R9W4Ii1ByIj177wA/pc0JdjtD0EsH8= -github.com/gobuffalo/packd v1.0.2/go.mod h1:sUc61tDqGMXON80zpKGp92lDb86Km28jfvX7IAyxFT8= -github.com/gobuffalo/plush/v4 v4.1.16/go.mod h1:6t7swVsarJ8qSLw1qyAH/KbrcSTwdun2ASEQkOznakg= github.com/gobuffalo/plush/v4 v4.1.18 h1:bnPjdMTEUQHqj9TNX2Ck3mxEXYZa+0nrFMNM07kpX9g= github.com/gobuffalo/plush/v4 v4.1.18/go.mod h1:xi2tJIhFI4UdzIL8sxZtzGYOd2xbBpcFbLZlIPGGZhU= -github.com/gobuffalo/pop/v6 v6.1.1 h1:eUDBaZcb0gYrmFnKwpuTEUA7t5ZHqNfvS4POqJYXDZY= -github.com/gobuffalo/pop/v6 v6.1.1/go.mod h1:1n7jAmI1i7fxuXPZjZb0VBPQDbksRtCoFnrDV5IsvaI= github.com/gobuffalo/refresh v1.13.3 h1:HYQlI6RiqWUf2yzCXvUHAYqm9M9/teVnox+mjzo/9rQ= github.com/gobuffalo/refresh v1.13.3/go.mod h1:NkzgLKZGk5suOvgvOD0/VALog0fH29Ib7fwym9JmRxA= -github.com/gobuffalo/suite/v4 v4.0.4 h1:q5Tnn1sv5N7jWufkq51RtUcsvWz4zDtAl/0uu3F23nE= -github.com/gobuffalo/suite/v4 v4.0.4/go.mod h1:bASFS5vBqxzFX947kyUmct4bqRgaOuFXs34GUs/LGDA= github.com/gobuffalo/tags/v3 v3.1.4 h1:X/ydLLPhgXV4h04Hp2xlbI2oc5MDaa7eub6zw8oHjsM= github.com/gobuffalo/tags/v3 v3.1.4/go.mod h1:ArRNo3ErlHO8BtdA0REaZxijuWnWzF6PUXngmMXd2I0= -github.com/gobuffalo/validate v2.0.4+incompatible h1:ZTxozrIw8qQ5nfhShmc4izjYPTsPhfdXTdhXOd5OS9o= -github.com/gobuffalo/validate v2.0.4+incompatible/go.mod h1:N+EtDe0J8252BgfzQUChBgfd6L93m9weay53EWFVsMM= github.com/gobuffalo/validate/v3 v3.3.3 h1:o7wkIGSvZBYBd6ChQoLxkz2y1pfmhbI4jNJYh6PuNJ4= github.com/gobuffalo/validate/v3 v3.3.3/go.mod h1:YC7FsbJ/9hW/VjQdmXPvFqvRis4vrRYFxr69WiNZw6g= -github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= -github.com/gofrs/uuid v4.3.1+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA= github.com/gofrs/uuid v4.4.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= -github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= -github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= +github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c= github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= @@ -127,96 +85,39 @@ github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyC github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI= github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= -github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo= -github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= -github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8= -github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= -github.com/jackc/pgconn v0.0.0-20190420214824-7e0022ef6ba3/go.mod h1:jkELnwuX+w9qN5YIfX0fl88Ehu4XC3keFuOJJk9pcnA= -github.com/jackc/pgconn v0.0.0-20190824142844-760dd75542eb/go.mod h1:lLjNuW/+OfW9/pnVKPazfWOgNfH2aPem8YQ7ilXGvJE= -github.com/jackc/pgconn v0.0.0-20190831204454-2fabfa3c18b7/go.mod h1:ZJKsE/KZfsUgOEh9hBm+xYTstcNHg7UPMVJqRfQxq4s= -github.com/jackc/pgconn v1.8.0/go.mod h1:1C2Pb36bGIP9QHGBYCjnyhqu7Rv3sGshaQUvmfGIB/o= -github.com/jackc/pgconn v1.9.0/go.mod h1:YctiPyvzfU11JFxoXokUOOKQXQmDMoJL9vJzHH8/2JY= -github.com/jackc/pgconn v1.9.1-0.20210724152538-d89c8390a530/go.mod h1:4z2w8XhRbP1hYxkpTuBjTS3ne3J48K83+u0zoyvg2pI= -github.com/jackc/pgconn v1.13.0/go.mod h1:AnowpAqO4CMIIJNZl2VJp+KrkAZciAkhEl0W0JIobpI= -github.com/jackc/pgconn v1.14.0 h1:vrbA9Ud87g6JdFWkHTJXppVce58qPIdP7N8y0Ml/A7Q= -github.com/jackc/pgconn v1.14.0/go.mod h1:9mBNlny0UvkgJdCDvdVHYSjI+8tD2rnKK69Wz8ti++E= -github.com/jackc/pgio v1.0.0 h1:g12B9UwVnzGhueNavwioyEEpAmqMe1E/BN9ES+8ovkE= -github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8= -github.com/jackc/pgmock v0.0.0-20190831213851-13a1b77aafa2/go.mod h1:fGZlG77KXmcq05nJLRkk0+p82V8B8Dw8KN2/V9c/OAE= -github.com/jackc/pgmock v0.0.0-20201204152224-4fe30f7445fd/go.mod h1:hrBW0Enj2AZTNpt/7Y5rr2xe/9Mn757Wtb2xeBzPv2c= -github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65 h1:DadwsjnMwFjfWc9y5Wi/+Zz7xoE5ALHsRQlOctkOiHc= -github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65/go.mod h1:5R2h2EEX+qri8jOWMbJCtaPWkrrNc7OHwsp2TCqp7ak= -github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= -github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= -github.com/jackc/pgproto3 v1.1.0/go.mod h1:eR5FA3leWg7p9aeAqi37XOTgTIbkABlvcPB3E5rlc78= -github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190420180111-c116219b62db/go.mod h1:bhq50y+xrl9n5mRYyCBFKkpRVTLYJVWeCc+mEAI3yXA= -github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190609003834-432c2951c711/go.mod h1:uH0AWtUmuShn0bcesswc4aBTWGvw0cAxIJp+6OB//Wg= -github.com/jackc/pgproto3/v2 v2.0.0-rc3/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM= -github.com/jackc/pgproto3/v2 v2.0.0-rc3.0.20190831210041-4c03ce451f29/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM= -github.com/jackc/pgproto3/v2 v2.0.6/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= -github.com/jackc/pgproto3/v2 v2.1.1/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= -github.com/jackc/pgproto3/v2 v2.3.1/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= -github.com/jackc/pgproto3/v2 v2.3.2 h1:7eY55bdBeCz1F2fTzSz69QC+pG46jYq9/jtSPiJ5nn0= -github.com/jackc/pgproto3/v2 v2.3.2/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= -github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b/go.mod h1:vsD4gTJCa9TptPL8sPkXrLZ+hDuNrZCnj29CQpr4X1E= -github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= -github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgtype v0.0.0-20190421001408-4ed0de4755e0/go.mod h1:hdSHsc1V01CGwFsrv11mJRHWJ6aifDLfdV3aVjFF0zg= -github.com/jackc/pgtype v0.0.0-20190824184912-ab885b375b90/go.mod h1:KcahbBH1nCMSo2DXpzsoWOAfFkdEtEJpPbVLq8eE+mc= -github.com/jackc/pgtype v0.0.0-20190828014616-a8802b16cc59/go.mod h1:MWlu30kVJrUS8lot6TQqcg7mtthZ9T0EoIBFiJcmcyw= -github.com/jackc/pgtype v1.8.1-0.20210724151600-32e20a603178/go.mod h1:C516IlIV9NKqfsMCXTdChteoXmwgUceqaLfjg2e3NlM= -github.com/jackc/pgtype v1.12.0/go.mod h1:LUMuVrfsFfdKGLw+AFFVv6KtHOFMwRgDDzBt76IqCA4= -github.com/jackc/pgtype v1.14.0 h1:y+xUdabmyMkJLyApYuPj38mW+aAIqCe5uuBB51rH3Vw= -github.com/jackc/pgtype v1.14.0/go.mod h1:LUMuVrfsFfdKGLw+AFFVv6KtHOFMwRgDDzBt76IqCA4= -github.com/jackc/pgx/v4 v4.0.0-20190420224344-cc3461e65d96/go.mod h1:mdxmSJJuR08CZQyj1PVQBHy9XOp5p8/SHH6a0psbY9Y= -github.com/jackc/pgx/v4 v4.0.0-20190421002000-1b8f0016e912/go.mod h1:no/Y67Jkk/9WuGR0JG/JseM9irFbnEPbuWV2EELPNuM= -github.com/jackc/pgx/v4 v4.0.0-pre1.0.20190824185557-6972a5742186/go.mod h1:X+GQnOEnf1dqHGpw7JmHqHc1NxDoalibchSk9/RWuDc= -github.com/jackc/pgx/v4 v4.12.1-0.20210724153913-640aa07df17c/go.mod h1:1QD0+tgSXP7iUjYm9C1NxKhny7lq6ee99u/z+IHFcgs= -github.com/jackc/pgx/v4 v4.17.2/go.mod h1:lcxIZN44yMIrWI78a5CpucdD14hX0SBDbNRvjDBItsw= -github.com/jackc/pgx/v4 v4.18.1 h1:YP7G1KABtKpB5IHrO9vYwSrCOhs7p3uqhvhhQBptya0= -github.com/jackc/pgx/v4 v4.18.1/go.mod h1:FydWkUyadDmdNH/mHnGob881GawxeEm7TcMCzkb+qQE= -github.com/jackc/puddle v0.0.0-20190413234325-e4ced69a3a2b/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= -github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= -github.com/jackc/puddle v1.1.3/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= -github.com/jackc/puddle v1.3.0/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g= github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ= github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= -github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= -github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= -github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lestrrat-go/backoff/v2 v2.0.8 h1:oNb5E5isby2kiro9AgdHLv5N5tint1AnDVVf2E2un5A= +github.com/lestrrat-go/backoff/v2 v2.0.8/go.mod h1:rHP/q/r9aT27n24JQLa7JhSQZCKBBOiM/uP402WwN8Y= +github.com/lestrrat-go/blackmagic v1.0.2 h1:Cg2gVSc9h7sz9NOByczrbUvLopQmXrfFx//N+AkAr5k= +github.com/lestrrat-go/blackmagic v1.0.2/go.mod h1:UrEqBzIR2U6CnzVyUtfM6oZNMt/7O7Vohk2J0OGSAtU= +github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE= +github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E= +github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI= +github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4= +github.com/lestrrat-go/jwx v1.2.29 h1:QT0utmUJ4/12rmsVQrJ3u55bycPkKqGYuGT4tyRhxSQ= +github.com/lestrrat-go/jwx v1.2.29/go.mod h1:hU8k2l6WF0ncx20uQdOmik/Gjg6E3/wIRtXSNFeZuB8= +github.com/lestrrat-go/option v1.0.0/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= +github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU= +github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw= -github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/luna-duclos/instrumentedsql v1.1.3 h1:t7mvC0z1jUt5A0UQ6I/0H31ryymuQRnJcWCiqV3lSAA= -github.com/luna-duclos/instrumentedsql v1.1.3/go.mod h1:9J1njvFds+zN7y85EDhN9XNQLANWwZt2ULeIC8yMNYs= -github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= -github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= @@ -224,7 +125,6 @@ github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APP github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= -github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U= github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/microcosm-cc/bluemonday v1.0.20/go.mod h1:yfBmMi8mxvaZut3Yytv+jTXRY8mxyjJ0/kQBTElld50= @@ -232,54 +132,28 @@ github.com/microcosm-cc/bluemonday v1.0.24 h1:NGQoPtwGVcbGkKfvyYk1yRqknzBuoMiUrO github.com/microcosm-cc/bluemonday v1.0.24/go.mod h1:ArQySAMps0790cHSkdPEJ7bGkF2VePWH773hsJNSHf8= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= -github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/monoculum/formam v3.5.5+incompatible h1:iPl5csfEN96G2N2mGu8V/ZB62XLf9ySTpC8KRH6qXec= github.com/monoculum/formam v3.5.5+incompatible/go.mod h1:RKgILGEJq24YyJ2ban8EO0RUVSJlF1pGsEvoLEACr/Q= github.com/nicksnyder/go-i18n v1.10.1 h1:isfg77E/aCD7+0lD/D00ebR2MV5vgeQ276WYyDaCRQc= github.com/nicksnyder/go-i18n v1.10.1/go.mod h1:e4Di5xjP9oTVrC6y3C7C0HoSYXjSbhh/dU0eUV32nB4= -github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= -github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= -github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= -github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= -github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= -github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= -github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= -github.com/onsi/gomega v1.32.0 h1:JRYU78fJ1LPxlckP6Txi/EYqJvjtMrDC04/MM5XRHPk= -github.com/onsi/gomega v1.32.0/go.mod h1:a4x4gW6Pz2yK1MAmvluYme5lvYTn61afQ2ETw/8n4Lg= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/psanford/memfs v0.0.0-20210214183328-a001468d78ef h1:NKxTG6GVGbfMXc2mIk+KphcH6hagbVXhcFkbTgYleTI= github.com/psanford/memfs v0.0.0-20210214183328-a001468d78ef/go.mod h1:tcaRap0jS3eifrEEllL6ZMd9dg8IlDpi2S1oARrQ+NI= -github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= -github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= -github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= -github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= -github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e h1:zWKUYT07mGmVBH+9UgnHXd/ekCK99C8EbDSAt5qsjXE= -github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e/go.mod h1:Yow6lPLSAXx2ifx470yD/nUe22Dv5vBvxK/UK9UUTVs= github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= -github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4= -github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= -github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= @@ -294,100 +168,49 @@ github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRM github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= -github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/unrolled/secure v1.13.0/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40= github.com/unrolled/secure v1.14.0 h1:u9vJTU/pR4Bny0ntLUMxdfLtmIRGvQf2sEFuA0TG9AE= github.com/unrolled/secure v1.14.0/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= -go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= -go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= -go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= -go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= -go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= -go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= -go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= -golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= -golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= -golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc= -golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= -golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA= +golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220826154423-83b083e8dc8b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.0.0-20221002022538-bcab6841153b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo= -golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220929204114-8fcdb60fdcc0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -398,65 +221,43 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= -golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= +golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20220722155259-a9ba230a4035/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.16.0 h1:m+B6fahuftsE9qjo0VWp2FW0mB3MTJvR0BaMQrq0pmE= -golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= +golang.org/x/term v0.18.0 h1:FcHjZXDMxI8mM3nwhX9HlKop4C0YQvCVCdwYl2wOtE8= +golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190823170909-c4a336ef6a2f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= diff --git a/mc_web_console_front/middleware/middleware.go b/mc_web_console_front/middleware/middleware.go new file mode 100644 index 00000000..8ef85734 --- /dev/null +++ b/mc_web_console_front/middleware/middleware.go @@ -0,0 +1,133 @@ +package middleware + +import ( + "context" + "fmt" + "log" + "os" + + "github.com/gobuffalo/buffalo" + "github.com/golang-jwt/jwt" + "github.com/lestrrat-go/jwx/jwk" +) + +var MCIAMMANAGER = os.Getenv("MCIAMMANAGER") + +var ( + jwkSet jwk.Set +) + +type CustomClaims struct { + *jwt.StandardClaims + Exp int `json:"exp"` + // Iat int `json:"iat"` + // Jti string `json:"jti"` + // Iss string `json:"iss"` + // Aud string `json:"aud"` + Sub string `json:"sub"` + // Typ string `json:"typ"` + // Azp string `json:"azp"` + // SessionState string `json:"session_state"` + // Acr string `json:"acr"` + // AllowedOrigins []string `json:"allowed-origins"` + // + RealmAccess struct { + Roles []string `json:"roles"` + } `json:"realm_access"` + // + // Scope string `json:"scope"` + // Sid string `json:"sid"` + Upn string `json:"upn"` + // EmailVerified bool `json:"email_verified"` + // Name string `json:"name"` + // Groups []string `json:"groups"` + PreferredUsername string `json:"preferred_username"` + // RealmRole []string `json:"realmRole"` + // GivenName string `json:"given_name"` + // FamilyName string `json:"family_name"` + // Email string `json:"email"` +} + +func init() { + var err error + jwkSet, err = jwk.Fetch(context.Background(), MCIAMMANAGER+"/api/auth/certs") + if err != nil { + panic("failed to fetch JWK: " + err.Error()) + } +} + +func Middleware(role string) buffalo.MiddlewareFunc { + return func(next buffalo.Handler) buffalo.Handler { + return func(c buffalo.Context) error { + accessToken := c.Session().Get("Authorization") + if _, ok := accessToken.(string); !ok { + log.Println("token is not exist") + return c.Redirect(303, "/auth/unauthorized") + } + isvalid, err := IsTokenValid(c, accessToken.(string)) + if err != nil { + log.Println(err.Error()) + return c.Redirect(303, "/auth/unauthorized") + } + if !isvalid { + log.Println("token is invalid") + return c.Redirect(303, "/auth/unauthorized") + } + if !IsTokenHasRole(c, role) { + log.Println("role is invalid") + return c.Redirect(303, "/auth/unauthorized") + } + return next(c) + } + } +} + +func IsTokenValid(c buffalo.Context, tokenString string) (bool, error) { + token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, keyfunction) + if err != nil { + return false, fmt.Errorf("failed to parse token: %s", err.Error()) + } + + if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid { + c.Set("Sub", claims.Sub) + c.Set("PreferredUsername", claims.PreferredUsername) + c.Set("RealmAccessRoles", claims.RealmAccess.Roles) + c.Set("Upn", claims.Upn) + return true, nil + } else { + return false, nil + } +} + +func IsTokenHasRole(c buffalo.Context, role string) bool { + if role == "" { + return true + } + realmAccess := c.Value("RealmAccessRoles").([]string) + return contains(realmAccess, role) +} + +func keyfunction(token *jwt.Token) (interface{}, error) { + if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + } + kid := token.Header["kid"].(string) + keys, nokey := jwkSet.LookupKeyID(kid) + if !nokey { + return nil, fmt.Errorf("no keys found for kid: %s", kid) + } + var raw interface{} + if err := keys.Raw(&raw); err != nil { + return nil, fmt.Errorf("failed to get key: %s", err) + } + return raw, nil +} + +func contains(slice []string, item string) bool { + for _, v := range slice { + if v == item { + return true + } + } + return false +} diff --git a/mc_web_console_front/templates/application.plush.html b/mc_web_console_front/templates/application.plush.html index ea54f2ce..5feb08d2 100644 --- a/mc_web_console_front/templates/application.plush.html +++ b/mc_web_console_front/templates/application.plush.html @@ -16,12 +16,29 @@ <%= partial("partials/layout/navbar.html") %>
    + <%= partial("partials/layout/pageheader.html") %> <%= partial("partials/layout/flash.html") %> <%= yield %> + <%= partial("partials/layout/modal.html") %> +
    +
    +
    +
    +
    + +
    +
    Preparing page
    +
    +
    +
    +
    +
    +
    +
    <%= partial("partials/layout/footer.html") %> @@ -34,7 +51,9 @@ <%= javascriptTag("common/util.js") %> <%= javascriptTag("common/api/http.js") %> <%= javascriptTag("common/storage/sessionstorage.js") %> - + <%= javascriptTag("partials/layout/navigatePages.js") %> + <%= javascriptTag("partials/layout/modal.js") %> + \ No newline at end of file diff --git a/mc_web_console_front/templates/pages/auth/logout.html b/mc_web_console_front/templates/pages/auth/logout.html new file mode 100644 index 00000000..3b125c16 --- /dev/null +++ b/mc_web_console_front/templates/pages/auth/logout.html @@ -0,0 +1,35 @@ +
    + +
    + + + +
    +
    +

    Logout

    + + + +
    +
    + + + +
    +
    + + +<%= javascriptTag("pages/auth/login.js") %> \ No newline at end of file diff --git a/mc_web_console_front/templates/pages/auth/unauthorized.html b/mc_web_console_front/templates/pages/auth/unauthorized.html new file mode 100644 index 00000000..04899616 --- /dev/null +++ b/mc_web_console_front/templates/pages/auth/unauthorized.html @@ -0,0 +1,35 @@ +
    + +
    + + + +
    +
    +

    Unauthorized

    + + + +
    +
    + + + +
    +
    + + +<%= javascriptTag("pages/auth/login.js") %> \ No newline at end of file diff --git a/mc_web_console_front/templates/pages/operation/dashboard/ns.html b/mc_web_console_front/templates/pages/operation/dashboard/ns.html index fd95f327..04baa9df 100644 --- a/mc_web_console_front/templates/pages/operation/dashboard/ns.html +++ b/mc_web_console_front/templates/pages/operation/dashboard/ns.html @@ -1,7 +1,12 @@
    -
    -
    - -
    +
    +
    +
    + <%= partial("partials/operation/dashboard/mcisserver.html") %> +
    +
    + <%= partial("partials/operation/dashboard/mcisserverprint.html") %> +
    +
    \ No newline at end of file diff --git a/mc_web_console_front/templates/pages/operation/manage/mcis.html b/mc_web_console_front/templates/pages/operation/manage/mcis.html index fd95f327..16214f98 100644 --- a/mc_web_console_front/templates/pages/operation/manage/mcis.html +++ b/mc_web_console_front/templates/pages/operation/manage/mcis.html @@ -1,7 +1,858 @@
    -
    -
    +
    + +
    +
    +
    +
    +
    +

    MCIS Status

    +
    +
    +
    +
    +
    +
    +

    0

    +
    +
    +
    + +
    +
    +
    +

    + 0 +

    +
    +
    +
    + +
    +
    +
    +

    + 0 +

    +
    +
    +
    + +
    +
    +
    +

    + 0 +

    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +

    Server Status

    +
    + +
    +
    +
    +
    +
    +

    0

    +
    +
    +
    + +
    +
    +
    +

    + 0 +

    +
    +
    +
    + +
    +
    +
    +

    + 0 +

    +
    +
    +
    + +
    +
    +
    +

    + 0 +

    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + +
    +
    +
    +
    + Field +
    + +
    + +
    +
    + Type +
    + +
    + +
    +
    + Filter +
    + + +
    +
    +
    + +
    + +
    +
    +
    +
    +
    + <%= partial("partials/operation/manage/mcisinfo.html") %> +
    +
    +
    + + + + +
    +
    + + + + + + + + + + + + + +
    + +
    +
    +
    +
    +

    Create MCIS

    +
    + +
    +
    + + +
    + +
    + + + +
    + +
    + + +
    + +
    +
    +
    +
      +
    • + + +
    • +
    +
    +
    +
    +
    + + +
    +
    + +
    +
    +
    +

    Steps

    +
      +
    • +
      MCIS Name
      +
      MCIS Name input ex) mcis01
      +
    • +
    • +
      Order received
      +
      Lorem ipsum dolor sit amet.
      +
    • +
    +
    + +
    +
      +
    • Step one
    • +
    • Step two
    • +
    • Step three
    • +
    • Step four
    • +
    • Step five
    • +
    +
    +
    +
    -
    \ No newline at end of file + + + +
    +
    + + + + + + + + + + + +
    + +
    +
    +
    +
    +

    Extend VM

    +
    + +
    +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    +
    +
    +
      +
    • + + +
    • +
    +
    +
    +
    +
    + + +
    +
    + +
    +
    +
    +

    Steps

    +
      +
    • +
      MCIS Name
      +
      MCIS Name input ex) mcis01
      +
    • +
    • +
      Order received
      +
      Lorem ipsum dolor sit amet.
      +
    • +
    +
    + +
    +
      +
    • Step one
    • +
    • Step two
    • +
    • Step three
    • +
    • Step four
    • +
    • Step five
    • +
    +
    +
    +
    +
    +
    +
    +
    + + + <%= partial("partials/operation/manage/mciscreate.html") %> + + + + <%= partial("partials/operation/manage/serverrecommandation.html") %> + + + +<%= javascriptTag("pages/operation/manage/mcis.js") %> diff --git a/mc_web_console_front/templates/pages/operation/monitoring/mcis.html b/mc_web_console_front/templates/pages/operation/monitoring/mcis.html index fd95f327..5a8769a8 100644 --- a/mc_web_console_front/templates/pages/operation/monitoring/mcis.html +++ b/mc_web_console_front/templates/pages/operation/monitoring/mcis.html @@ -1,7 +1,9 @@ -
    -
    -
    - -
    -
    -
    \ No newline at end of file +
    +
    +
    +
    +
    +
    +
    +
    +<%= javascriptTag("common/server_info_monitoringcard.js") %> diff --git a/mc_web_console_front/templates/pages/operation/workflow/create.html b/mc_web_console_front/templates/pages/operation/workflow/create.html new file mode 100644 index 00000000..282972e1 --- /dev/null +++ b/mc_web_console_front/templates/pages/operation/workflow/create.html @@ -0,0 +1,8 @@ +
    + + + +
    + +<%= javascriptTag("pages/operation/workflow/createworkflow.js") %> \ No newline at end of file diff --git a/mc_web_console_front/templates/pages/operation/workflow/manage.html b/mc_web_console_front/templates/pages/operation/workflow/manage.html new file mode 100644 index 00000000..a960455b --- /dev/null +++ b/mc_web_console_front/templates/pages/operation/workflow/manage.html @@ -0,0 +1,7 @@ +
    + + +
    + +<%= javascriptTag("pages/operation/workflow/manageworkflow.js") %> \ No newline at end of file diff --git a/mc_web_console_front/templates/pages/platformsetting/configuration/role.html b/mc_web_console_front/templates/pages/platformsetting/configuration/role.html new file mode 100644 index 00000000..33bd014b --- /dev/null +++ b/mc_web_console_front/templates/pages/platformsetting/configuration/role.html @@ -0,0 +1,391 @@ +
    +
    + + +
    + +
    +
    + + +
    +
    +
    +
    + Field +
    + +
    + +
    +
    + Type +
    + +
    + +
    +
    + Filter +
    + + +
    +
    +
    + +
    + +
    +
    +
    +
    + + + +
    + + +
    + +
    +
    +
    +
    +

    Role

    +
    + +
    +
    + + + +
    + +
    + + +
    + +
    + + +
    +
    + +
    +
    + + +
    +
    +
    +
    +
    +

    Create a new Role

    +
    + +
    +
    + + + +
    + +
    + + +
    + +
    + + +
    +
    +
    + + +
    +
    +
    + +<%= javascriptTag("pages/configuration/role/manage.js") %> \ No newline at end of file diff --git a/mc_web_console_front/templates/pages/platformsetting/configuration/workspace.html b/mc_web_console_front/templates/pages/platformsetting/configuration/workspace.html new file mode 100644 index 00000000..c84438a3 --- /dev/null +++ b/mc_web_console_front/templates/pages/platformsetting/configuration/workspace.html @@ -0,0 +1,403 @@ +
    +
    + + +
    + +
    +
    + + +
    +
    +
    +
    + Field +
    + +
    + +
    +
    + Type +
    + +
    + +
    +
    + Filter +
    + + +
    +
    +
    + +
    + +
    +
    +
    +
    + + + +
    + + +
    + +
    +
    +
    +
    +

    Workspace

    +
    + +
    +
    + + + + +
    + +
    + + +
    + +
    + + +
    +
    + +
    +
    + + +
    +
    +
    +
    +
    +

    Create a new Workspace

    +
    + +
    +
    + + + + +
    + +
    + + +
    + +
    + + +
    +
    +
    + + +
    +
    +
    + +<%= javascriptTag("pages/configuration/workspace/manage.js") %> \ No newline at end of file diff --git a/mc_web_console_front/templates/partials/layout/_modal.html b/mc_web_console_front/templates/partials/layout/_modal.html new file mode 100644 index 00000000..e3264acf --- /dev/null +++ b/mc_web_console_front/templates/partials/layout/_modal.html @@ -0,0 +1,53 @@ + + + + + + + + \ No newline at end of file diff --git a/mc_web_console_front/templates/partials/layout/_navbar.html b/mc_web_console_front/templates/partials/layout/_navbar.html index ddc9a270..e315436d 100644 --- a/mc_web_console_front/templates/partials/layout/_navbar.html +++ b/mc_web_console_front/templates/partials/layout/_navbar.html @@ -118,7 +118,9 @@

    Last updates

    -
    <%= if (name) { %> +
    + <%= if (name) { %> + <%= name %> <% } %>
    @@ -139,7 +141,7 @@

    Last updates

    - - -
    diff --git a/mc_web_console_front/templates/partials/layout/_sidebar.html b/mc_web_console_front/templates/partials/layout/_sidebar.html index db4e4c5a..95d1959c 100644 --- a/mc_web_console_front/templates/partials/layout/_sidebar.html +++ b/mc_web_console_front/templates/partials/layout/_sidebar.html @@ -184,11 +184,40 @@

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + <%= javascriptTag("partials/layout/sidebar.js") %> \ No newline at end of file diff --git a/mc_web_console_front/templates/partials/operation/dashboard/_mcisrunning.html b/mc_web_console_front/templates/partials/operation/dashboard/_mcisrunning.html new file mode 100644 index 00000000..f7ae0d7e --- /dev/null +++ b/mc_web_console_front/templates/partials/operation/dashboard/_mcisrunning.html @@ -0,0 +1,8 @@ + +
    + + + + + +<%= javascriptTag("partials/operation/dashboard/mcisrunning.js") %> diff --git a/mc_web_console_front/templates/partials/operation/dashboard/_mcisserver.html b/mc_web_console_front/templates/partials/operation/dashboard/_mcisserver.html new file mode 100644 index 00000000..4ec2b7b8 --- /dev/null +++ b/mc_web_console_front/templates/partials/operation/dashboard/_mcisserver.html @@ -0,0 +1,48 @@ + + +
    +
    +

    MCIS / server

    +
    +
    +
    +
    + + + + + + + + + +
    +
    +
    1
    +
    + / + + 1 + +
    +
    +
    +
    0
    +
    +
    0
    +
    +
    0
    +
    +
    +
    +
    +
    +
    +
    +
    + +<%= javascriptTag("partials/operation/dashboard/mcisserver.js") %> \ No newline at end of file diff --git a/mc_web_console_front/templates/partials/operation/dashboard/_mcisserverprint.html b/mc_web_console_front/templates/partials/operation/dashboard/_mcisserverprint.html new file mode 100644 index 00000000..a53a82e7 --- /dev/null +++ b/mc_web_console_front/templates/partials/operation/dashboard/_mcisserverprint.html @@ -0,0 +1,329 @@ + + + diff --git a/mc_web_console_front/templates/partials/operation/manage/_connectionservicemap.html b/mc_web_console_front/templates/partials/operation/manage/_connectionservicemap.html new file mode 100644 index 00000000..94819c6b --- /dev/null +++ b/mc_web_console_front/templates/partials/operation/manage/_connectionservicemap.html @@ -0,0 +1,11 @@ +
    +
    +
    +
    + Example Image +
    +
    +
    +
    + +<%#= javascriptTag("partials/operation/worldmap.js") %> \ No newline at end of file diff --git a/mc_web_console_front/templates/partials/operation/manage/_connectiontab.html b/mc_web_console_front/templates/partials/operation/manage/_connectiontab.html new file mode 100644 index 00000000..5d993a13 --- /dev/null +++ b/mc_web_console_front/templates/partials/operation/manage/_connectiontab.html @@ -0,0 +1,57 @@ +
    +
    +
    +
    +
    + Connection Name +
    +
    + +
    +
    +
    +
    + Credential +
    +
    + +
    +
    +
    +
    + Cloud Provider(CP) +
    +
    + +
    +
    +
    +
    + Driver File Name +
    +
    + +
    +
    +
    +
    + Region +
    +
    + +
    +
    +
    +
    + Available Zone +
    +
    + +
    +
    +
    +
    + <%= partial("partials/operation/manage/connectionservicemap.html") %> +
    +
    +
    \ No newline at end of file diff --git a/mc_web_console_front/templates/partials/operation/manage/_detailtab.html b/mc_web_console_front/templates/partials/operation/manage/_detailtab.html new file mode 100644 index 00000000..42bf42e4 --- /dev/null +++ b/mc_web_console_front/templates/partials/operation/manage/_detailtab.html @@ -0,0 +1,104 @@ +
    +
    +
    +
    +
    +
    Server ID
    +
    +
    +
    +
    Server Status
    +
    +
    +
    +
    Server Spec
    +
    +
    +
    +
    Public DNS(IPv4)
    +
    +
    +
    +
    Public IP(IPv4)
    +
    +
    +
    +
    Region
    +
    +
    +
    +
    Zone
    +
    +
    +
    +
    Security Group
    +
    +
    +
    +
    Private DNS
    +
    +
    +
    +
    Private IP
    +
    +
    +
    +
    Image ID
    +
    +
    +
    +
    +
    +
    +
    +
    Platform
    +
    +
    +
    +
    Operating System
    +
    +
    +
    +
    VPC ID
    +
    + +
    +
    +
    +
    subnet ID
    +
    + +
    +
    +
    +
    Network Interface
    +
    +
    +
    +
    Root Device Type
    +
    +
    +
    +
    Root Device
    +
    +
    +
    +
    Block Device
    +
    +
    +
    +
    Keypair Name
    +
    +
    +
    +
    Access ID / Pwd
    +
    +
    +
    +
    User ID / Pwd
    +
    +
    +
    +
    +
    +
    \ No newline at end of file diff --git a/mc_web_console_front/templates/partials/operation/manage/_mciscreate.html b/mc_web_console_front/templates/partials/operation/manage/_mciscreate.html new file mode 100644 index 00000000..ad817118 --- /dev/null +++ b/mc_web_console_front/templates/partials/operation/manage/_mciscreate.html @@ -0,0 +1,168 @@ +
    +
    +
    +
    +
    +

    Server Configuration

    +
    +
    +
    +
    +
    + + +
    +
    + +
    +
    + + + + + + + +
    + +
    +
    + +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    + + + 1 +
    +
    +
    +
    + + +
    +
    +
    +
    + +
    + +
    +
    +
    + +<%= javascriptTag("partials/operation/manage/mciscreate.js") %> \ No newline at end of file diff --git a/mc_web_console_front/templates/partials/operation/manage/_mcisinfo.html b/mc_web_console_front/templates/partials/operation/manage/_mcisinfo.html new file mode 100644 index 00000000..2e5c837b --- /dev/null +++ b/mc_web_console_front/templates/partials/operation/manage/_mcisinfo.html @@ -0,0 +1,60 @@ + + +
    + +
    +

    + MCIS Info +

    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    Name
    +
    +
    +
    +
    Status
    +
    +
    +
    +
    Provider
    +
    + +
    +
    +
    +
    Description
    +
    +
    +
    +
    +
    +
    + +
    +
    + <%= partial("partials/operation/manage/serverlist_status.html") %> +
    +
    + +
    +
    + <%= partial("partials/operation/manage/serverinfo.html") %> +
    +
    +
    +
    diff --git a/mc_web_console_front/templates/partials/operation/manage/_monitoringtab.html b/mc_web_console_front/templates/partials/operation/manage/_monitoringtab.html new file mode 100644 index 00000000..5a8769a8 --- /dev/null +++ b/mc_web_console_front/templates/partials/operation/manage/_monitoringtab.html @@ -0,0 +1,9 @@ +
    +
    +
    +
    +
    +
    +
    +
    +<%= javascriptTag("common/server_info_monitoringcard.js") %> diff --git a/mc_web_console_front/templates/partials/operation/manage/_serverdetailinfo.html b/mc_web_console_front/templates/partials/operation/manage/_serverdetailinfo.html new file mode 100644 index 00000000..ad253180 --- /dev/null +++ b/mc_web_console_front/templates/partials/operation/manage/_serverdetailinfo.html @@ -0,0 +1,19 @@ +
    +
    +
    +
    +

    + Server Detail Info + + +

    +
    +
    + +
    +
    +
    +
    + <%= partial("partials/operation/manage/servertabcards.html") %> +
    +
    diff --git a/mc_web_console_front/templates/partials/operation/manage/_serverinfo.html b/mc_web_console_front/templates/partials/operation/manage/_serverinfo.html new file mode 100644 index 00000000..1fb0cad1 --- /dev/null +++ b/mc_web_console_front/templates/partials/operation/manage/_serverinfo.html @@ -0,0 +1,148 @@ + +
    + +
    +

    + Server Info + + +

    +
    +
    +
    +
    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    Name
    +
    +
    +
    +
    +
    +
    Description
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    Operating System
    +
    +
    +
    +
    +
    +
    Architecture
    +
    +
    +
    +
    +
    +
    VMSpecName
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    StartTime
    +
    +
    +
    +
    +
    +
    Public IP
    +
    +
    +
    +
    +
    +
    / DNS
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    Private IP
    +
    +
    d
    +
    +
    +
    +
    / DNS
    +
    +
    +
    + +
    +
    +
    ConfigName
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    VMID
    +
    +
    +
    +
    +
    +
    Region
    +
    +
    + +
    +
    +
    +
    Zone
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + <%= partial("partials/operation/manage/serverdetailinfo.html") %> +
    +
    +
    + diff --git a/mc_web_console_front/templates/partials/operation/manage/_serverlist_status.html b/mc_web_console_front/templates/partials/operation/manage/_serverlist_status.html new file mode 100644 index 00000000..8ccef113 --- /dev/null +++ b/mc_web_console_front/templates/partials/operation/manage/_serverlist_status.html @@ -0,0 +1,351 @@ + diff --git a/mc_web_console_front/templates/partials/operation/manage/_serverrecommandation.html b/mc_web_console_front/templates/partials/operation/manage/_serverrecommandation.html new file mode 100644 index 00000000..8e67dacb --- /dev/null +++ b/mc_web_console_front/templates/partials/operation/manage/_serverrecommandation.html @@ -0,0 +1,149 @@ + + + + + + <%= javascriptTag("partials/operation/manage/serverrecommandation.js") %> \ No newline at end of file diff --git a/mc_web_console_front/templates/partials/operation/manage/_servertabcards.html b/mc_web_console_front/templates/partials/operation/manage/_servertabcards.html new file mode 100644 index 00000000..dd061e76 --- /dev/null +++ b/mc_web_console_front/templates/partials/operation/manage/_servertabcards.html @@ -0,0 +1,39 @@ + + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    + <%= partial("partials/operation/manage/detailtab.html") %> +
    +
    + <%= partial("partials/operation/manage/connectiontab.html") %> +
    + +
    + <%= partial("partials/operation/manage/monitoringtab.html") %> +
    +
    +
    +
    +
    +
    +
    +
    \ No newline at end of file diff --git a/mc_web_console_front/templatesOld/_debug/tabler/navigation.html b/mc_web_console_front/templatesOld/_debug/tabler/navigation.html index 3602802b..ce611b64 100644 --- a/mc_web_console_front/templatesOld/_debug/tabler/navigation.html +++ b/mc_web_console_front/templatesOld/_debug/tabler/navigation.html @@ -1156,7 +1156,7 @@

    Last updates

    - Tabler + Tabler