From d71816d8a884d99193798dea706d7785a3f1179e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=90=9A=E8=87=B4=E8=BF=9C?= Date: Wed, 17 Jun 2020 11:09:57 +0800 Subject: [PATCH] Feat master (#263) * remove outdated codes * feat: merged next * feat: update action * feat: update README * Delete .DS_Store --- CHANGELOG.md => .asf.yaml | 35 +- .browserslistrc | 2 - .dockerignore | 1 + .editorconfig | 31 +- .env.development | 11 - .env.production | 5 - .eslintignore | 7 +- .eslintrc.js | 43 +- .github/workflows/api_ut.yml | 18 + .gitignore | 52 +- .prettierignore | 21 + .prettierrc.js | 5 + .stylelintrc.js | 5 + DISCLAIMER | 5 - Dockerfile | 19 + LICENSE | 206 - NOTICE | 5 - README-dashboard.md | 47 + README.md | 112 +- api/Dockerfile | 49 + src/App.vue => api/README.md | 15 +- api/build.sh | 30 + api/conf.json | 19 + api/conf/conf.go | 104 + api/conf/conf.json | 19 + .../schema/consumers.ts => api/conf/mysql.go | 52 +- api/docker-compose.yml | 9 + api/errno/error.go | 98 + babel.config.js => api/filter/cors.go | 19 +- api/filter/logging.go | 84 + api/filter/recover.go | 120 + .../plugins.ts => api/filter/request_id.go | 30 +- api/go.mod | 15 + api/go.sum | 89 + api/log/log.go | 147 + api/main.go | 65 + src/api/users.ts => api/route/healthz.go | 35 +- api/route/plugin.go | 58 + api/route/route.go | 242 + api/route/ssl.go | 153 + api/script/db/schema.sql | 31 + src/store/index.ts => api/service/base.go | 43 +- api/service/plugin.go | 61 + api/service/route.go | 560 + api/service/route_test.go | 139 + api/service/ssl.go | 300 + postcss.config.js => api/utils/copy.go | 27 +- api/utils/http.go | 113 + compose/README.md | 56 + compose/apisix_conf/config.yaml | 137 + compose/docker-compose.yml | 124 + compose/grafana_conf/config/grafana.ini | 756 + .../dashboards/apisix_http_prometheus.json | 956 + .../provisioning/dashboards/all.yaml | 11 + .../provisioning/datasources/all.yaml | 9 + compose/manager_conf/build.sh | 20 + compose/pics/grafana_1.png | Bin 0 -> 57816 bytes compose/pics/grafana_2.png | Bin 0 -> 127932 bytes compose/pics/grafana_3.png | Bin 0 -> 103384 bytes compose/pics/grafana_4.png | Bin 0 -> 82558 bytes compose/pics/grafana_5.png | Bin 0 -> 105366 bytes compose/pics/grafana_6.png | Bin 0 -> 179132 bytes compose/pics/login.png | Bin 0 -> 84958 bytes compose/prometheus_conf/prometheus.yml | 23 + config/config.ts | 48 + config/defaultSettings.ts | 20 + config/proxy.ts | 30 + config/routes.ts | 76 + docker/nginx.conf | 21 + jest.config.js | 9 + jsconfig.json | 10 + licenses/LICENSE.ALv2 | 201 - .../LICENSE.vue-typescript-admin-template | 21 - mock/notices.ts | 105 + mock/route.ts | 5 + mock/user.ts | 154 + netlify.toml | 13 + package.json | 171 +- public/favicon.ico | Bin 9662 -> 0 bytes public/favicon.png | Bin 0 -> 85376 bytes public/home_bg.png | Bin 0 -> 203330 bytes public/icons/icon-128x128.png | Bin 0 -> 1329 bytes public/icons/icon-192x192.png | Bin 0 -> 1856 bytes public/icons/icon-512x512.png | Bin 0 -> 5082 bytes public/img/icons/favicon-16x16.png | Bin 9662 -> 0 bytes public/img/icons/favicon-32x32.png | Bin 9662 -> 0 bytes public/index.html | 43 - public/pro_icon.svg | 1 + public/robots.txt | 2 - src/access.ts | 6 + src/api/schema/routes.ts | 51 - src/api/schema/schema.ts | 24 - src/api/schema/services.ts | 51 - src/api/schema/ssl.ts | 52 - src/api/schema/upstream.ts | 50 - src/api/types.d.ts | 78 - src/app.tsx | 92 + src/assets/logo.svg | 21 + src/components/Breadcrumb/index.vue | 125 - src/components/Footer/index.tsx | 17 + src/components/Hamburger/index.vue | 75 - src/components/HeaderDropdown/index.less | 16 + src/components/HeaderDropdown/index.tsx | 19 + src/components/HeaderSearch/index.vue | 244 - src/components/LangSelect/index.vue | 77 - src/components/NoticeIcon/NoticeList.less | 103 + src/components/NoticeIcon/NoticeList.tsx | 113 + src/components/NoticeIcon/index.less | 31 + src/components/NoticeIcon/index.tsx | 124 + src/components/PageLoading/index.tsx | 5 + src/components/Pagination/index.vue | 104 - src/components/PluginDialog/index.vue | 523 - src/components/PluginForm/PluginForm.tsx | 192 + src/components/PluginForm/README.md | 9 + src/components/PluginForm/data.ts | 100 + src/components/PluginForm/index.ts | 3 + src/components/PluginForm/locales/en-US.ts | 152 + src/components/PluginForm/locales/zh-CN.ts | 152 + src/components/PluginForm/service.ts | 5 + src/components/PluginForm/transformer.ts | 90 + src/components/PluginForm/typing.d.ts | 64 + src/components/PluginModal/index.tsx | 32 + .../RightContent/AvatarDropdown.tsx | 94 + src/components/RightContent/index.less | 82 + src/components/RightContent/index.tsx | 51 + src/components/Screenfull/index.vue | 79 - src/components/VarArgs/index.vue | 128 - src/e2e/__mocks__/antd-pro-merge-less.js | 1 + src/e2e/baseLayout.e2e.js | 57 + src/global.less | 69 + src/global.tsx | 83 + src/lang/en.ts | 94 - src/lang/index.ts | 67 - src/lang/zh.ts | 102 - src/layout/components/AppMain.vue | 83 - src/layout/components/Navbar/index.vue | 195 - src/layout/components/Sidebar/SidebarItem.vue | 209 - .../components/Sidebar/SidebarItemLink.vue | 56 - src/layout/components/Sidebar/SidebarLogo.vue | 123 - src/layout/components/Sidebar/index.vue | 156 - src/layout/components/TagsView/ScrollPane.vue | 113 - src/layout/components/TagsView/index.vue | 359 - src/layout/components/index.ts | 28 - src/layout/index.vue | 192 - src/layout/mixin/resize.ts | 79 - src/locales/en-US.ts | 23 + src/locales/en-US/component.ts | 39 + src/locales/en-US/globalHeader.ts | 17 + src/locales/en-US/menu.ts | 60 + src/locales/en-US/pwa.ts | 6 + src/locales/en-US/setting.ts | 4 + src/locales/en-US/settingDrawer.ts | 31 + src/locales/zh-CN.ts | 23 + src/locales/zh-CN/component.ts | 39 + src/locales/zh-CN/globalHeader.ts | 17 + src/locales/zh-CN/menu.ts | 61 + src/locales/zh-CN/pwa.ts | 6 + src/locales/zh-CN/setting.ts | 12 + src/locales/zh-CN/settingDrawer.ts | 31 + src/main.ts | 57 - src/manifest.json | 22 + src/pages/404.tsx | 18 + src/pages/Metrics/Metrics.tsx | 54 + src/pages/Routes/Create.less | 112 + src/pages/Routes/Create.tsx | 223 + src/pages/Routes/List.tsx | 82 + .../Routes/components/ActionBar/ActionBar.tsx | 46 + .../Routes/components/ActionBar/index.ts | 1 + .../components/CreateStep3/CreateStep3.tsx | 96 + .../components/CreateStep3/PluginCard.tsx | 26 + .../components/CreateStep3/PluginDrawer.tsx | 73 + .../Routes/components/CreateStep3/index.ts | 1 + .../components/CreateStep4/CreateStep4.tsx | 35 + .../Routes/components/CreateStep4/index.ts | 1 + .../Routes/components/PanelSection/index.tsx | 16 + .../components/ResultView/ResultView.tsx | 24 + .../Routes/components/ResultView/index.ts | 1 + .../components/Step1/MatchingRulesView.tsx | 214 + .../Routes/components/Step1/MetaView.tsx | 27 + .../components/Step1/RequestConfigView.tsx | 201 + src/pages/Routes/components/Step1/index.tsx | 41 + .../Step2/HttpHeaderRewriteView.tsx | 166 + .../components/Step2/RequestRewriteView.tsx | 174 + src/pages/Routes/components/Step2/index.tsx | 20 + src/pages/Routes/constants.ts | 61 + src/pages/Routes/service.ts | 24 + src/pages/Routes/transform.ts | 176 + src/pages/Routes/typing.d.ts | 125 + src/pages/Setting/Setting.tsx | 102 + src/pages/Setting/index.ts | 2 + src/pages/Setting/service.ts | 7 + src/pages/Setting/style.less | 109 + src/pages/Setting/typingd.d.ts | 9 + src/pages/document.ejs | 193 + src/pages/ssl/Create.less | 101 + src/pages/ssl/Create.tsx | 65 + src/pages/ssl/List.tsx | 110 + .../ssl/components/CertificateForm/index.tsx | 75 + .../components/CertificateUploader/index.tsx | 97 + src/pages/ssl/components/Step1/index.tsx | 104 + src/pages/ssl/components/Step2/index.tsx | 32 + src/pages/ssl/components/Step3/index.tsx | 36 + src/pages/ssl/service.ts | 78 + src/pages/ssl/typing.d.ts | 18 + src/permission.ts | 102 - src/router/index.ts | 82 - src/router/modules/schema/consumers.ts | 56 - src/router/modules/schema/routes.ts | 56 - src/router/modules/schema/services.ts | 56 - src/router/modules/schema/ssl.ts | 56 - src/router/modules/schema/upstream.ts | 56 - src/service-worker.js | 70 + src/services/API.d.ts | 24 + src/services/login.ts | 20 + src/services/user.ts | 23 + src/settings.ts | 48 - src/shims.d.ts | 36 - src/store/modules/app.ts | 116 - src/store/modules/permission.ts | 80 - src/store/modules/settings.ts | 62 - src/store/modules/tags-view.ts | 165 - src/store/modules/user.ts | 169 - src/styles/_mixins.scss | 31 - src/styles/_svgicon.scss | 56 - src/styles/_transition.scss | 73 - src/styles/_variables.scss | 56 - src/styles/_variables.scss.d.ts | 33 - src/styles/element-variables.scss | 47 - src/styles/element-variables.scss.d.ts | 31 - src/styles/index.scss | 183 - src/transforms/global.ts | 26 + src/typings.d.ts | 40 + src/utils/cookies.ts | 44 - src/utils/index.ts | 112 - src/utils/permission.ts | 39 - src/utils/request.ts | 59 - src/utils/scroll-to.ts | 74 - src/utils/validate.ts | 39 - src/views/login/index.vue | 228 - src/views/schema/consumers/edit.vue | 266 - src/views/schema/consumers/list.vue | 222 - src/views/schema/routes/edit.vue | 549 - src/views/schema/routes/list.vue | 252 - src/views/schema/service/edit.vue | 300 - src/views/schema/service/list.vue | 215 - src/views/schema/ssl/edit.vue | 191 - src/views/schema/ssl/list.vue | 206 - src/views/schema/upstream/edit.vue | 434 - src/views/schema/upstream/list.vue | 289 - tests/PuppeteerEnvironment.js | 41 + tests/beforeTest.js | 39 + tests/getBrowser.js | 45 + tests/run-tests.js | 52 + tsconfig.json | 49 +- vue.config.js | 84 - yarn.lock | 22870 +++++++++++----- 256 files changed, 27441 insertions(+), 16413 deletions(-) rename CHANGELOG.md => .asf.yaml (62%) delete mode 100644 .browserslistrc create mode 100644 .dockerignore delete mode 100644 .env.development delete mode 100644 .env.production create mode 100644 .github/workflows/api_ut.yml create mode 100644 .prettierignore create mode 100644 .prettierrc.js create mode 100644 .stylelintrc.js delete mode 100644 DISCLAIMER create mode 100644 Dockerfile delete mode 100644 LICENSE delete mode 100644 NOTICE create mode 100644 README-dashboard.md create mode 100644 api/Dockerfile rename src/App.vue => api/README.md (78%) create mode 100644 api/build.sh create mode 100644 api/conf.json create mode 100644 api/conf/conf.go create mode 100644 api/conf/conf.json rename src/api/schema/consumers.ts => api/conf/mysql.go (52%) create mode 100644 api/docker-compose.yml create mode 100644 api/errno/error.go rename babel.config.js => api/filter/cors.go (64%) create mode 100644 api/filter/logging.go create mode 100644 api/filter/recover.go rename src/api/schema/plugins.ts => api/filter/request_id.go (60%) create mode 100644 api/go.mod create mode 100644 api/go.sum create mode 100644 api/log/log.go create mode 100644 api/main.go rename src/api/users.ts => api/route/healthz.go (69%) create mode 100644 api/route/plugin.go create mode 100644 api/route/route.go create mode 100644 api/route/ssl.go create mode 100644 api/script/db/schema.sql rename src/store/index.ts => api/service/base.go (50%) create mode 100644 api/service/plugin.go create mode 100644 api/service/route.go create mode 100644 api/service/route_test.go create mode 100644 api/service/ssl.go rename postcss.config.js => api/utils/copy.go (62%) create mode 100644 api/utils/http.go create mode 100644 compose/README.md create mode 100644 compose/apisix_conf/config.yaml create mode 100644 compose/docker-compose.yml create mode 100644 compose/grafana_conf/config/grafana.ini create mode 100644 compose/grafana_conf/dashboards/apisix_http_prometheus.json create mode 100644 compose/grafana_conf/provisioning/dashboards/all.yaml create mode 100644 compose/grafana_conf/provisioning/datasources/all.yaml create mode 100755 compose/manager_conf/build.sh create mode 100644 compose/pics/grafana_1.png create mode 100644 compose/pics/grafana_2.png create mode 100644 compose/pics/grafana_3.png create mode 100644 compose/pics/grafana_4.png create mode 100644 compose/pics/grafana_5.png create mode 100644 compose/pics/grafana_6.png create mode 100644 compose/pics/login.png create mode 100644 compose/prometheus_conf/prometheus.yml create mode 100644 config/config.ts create mode 100644 config/defaultSettings.ts create mode 100644 config/proxy.ts create mode 100644 config/routes.ts create mode 100644 docker/nginx.conf create mode 100644 jest.config.js create mode 100644 jsconfig.json delete mode 100644 licenses/LICENSE.ALv2 delete mode 100644 licenses/LICENSE.vue-typescript-admin-template create mode 100644 mock/notices.ts create mode 100644 mock/route.ts create mode 100644 mock/user.ts create mode 100644 netlify.toml delete mode 100644 public/favicon.ico create mode 100644 public/favicon.png create mode 100644 public/home_bg.png create mode 100644 public/icons/icon-128x128.png create mode 100644 public/icons/icon-192x192.png create mode 100644 public/icons/icon-512x512.png delete mode 100644 public/img/icons/favicon-16x16.png delete mode 100644 public/img/icons/favicon-32x32.png delete mode 100644 public/index.html create mode 100644 public/pro_icon.svg delete mode 100644 public/robots.txt create mode 100644 src/access.ts delete mode 100644 src/api/schema/routes.ts delete mode 100644 src/api/schema/schema.ts delete mode 100644 src/api/schema/services.ts delete mode 100644 src/api/schema/ssl.ts delete mode 100644 src/api/schema/upstream.ts delete mode 100644 src/api/types.d.ts create mode 100644 src/app.tsx create mode 100644 src/assets/logo.svg delete mode 100644 src/components/Breadcrumb/index.vue create mode 100644 src/components/Footer/index.tsx delete mode 100644 src/components/Hamburger/index.vue create mode 100644 src/components/HeaderDropdown/index.less create mode 100644 src/components/HeaderDropdown/index.tsx delete mode 100644 src/components/HeaderSearch/index.vue delete mode 100644 src/components/LangSelect/index.vue create mode 100755 src/components/NoticeIcon/NoticeList.less create mode 100644 src/components/NoticeIcon/NoticeList.tsx create mode 100644 src/components/NoticeIcon/index.less create mode 100644 src/components/NoticeIcon/index.tsx create mode 100644 src/components/PageLoading/index.tsx delete mode 100644 src/components/Pagination/index.vue delete mode 100644 src/components/PluginDialog/index.vue create mode 100644 src/components/PluginForm/PluginForm.tsx create mode 100644 src/components/PluginForm/README.md create mode 100644 src/components/PluginForm/data.ts create mode 100644 src/components/PluginForm/index.ts create mode 100644 src/components/PluginForm/locales/en-US.ts create mode 100644 src/components/PluginForm/locales/zh-CN.ts create mode 100644 src/components/PluginForm/service.ts create mode 100644 src/components/PluginForm/transformer.ts create mode 100644 src/components/PluginForm/typing.d.ts create mode 100644 src/components/PluginModal/index.tsx create mode 100644 src/components/RightContent/AvatarDropdown.tsx create mode 100644 src/components/RightContent/index.less create mode 100644 src/components/RightContent/index.tsx delete mode 100644 src/components/Screenfull/index.vue delete mode 100644 src/components/VarArgs/index.vue create mode 100644 src/e2e/__mocks__/antd-pro-merge-less.js create mode 100644 src/e2e/baseLayout.e2e.js create mode 100644 src/global.less create mode 100644 src/global.tsx delete mode 100644 src/lang/en.ts delete mode 100644 src/lang/index.ts delete mode 100644 src/lang/zh.ts delete mode 100644 src/layout/components/AppMain.vue delete mode 100644 src/layout/components/Navbar/index.vue delete mode 100644 src/layout/components/Sidebar/SidebarItem.vue delete mode 100644 src/layout/components/Sidebar/SidebarItemLink.vue delete mode 100644 src/layout/components/Sidebar/SidebarLogo.vue delete mode 100644 src/layout/components/Sidebar/index.vue delete mode 100644 src/layout/components/TagsView/ScrollPane.vue delete mode 100644 src/layout/components/TagsView/index.vue delete mode 100644 src/layout/components/index.ts delete mode 100644 src/layout/index.vue delete mode 100644 src/layout/mixin/resize.ts create mode 100644 src/locales/en-US.ts create mode 100644 src/locales/en-US/component.ts create mode 100644 src/locales/en-US/globalHeader.ts create mode 100644 src/locales/en-US/menu.ts create mode 100644 src/locales/en-US/pwa.ts create mode 100644 src/locales/en-US/setting.ts create mode 100644 src/locales/en-US/settingDrawer.ts create mode 100644 src/locales/zh-CN.ts create mode 100644 src/locales/zh-CN/component.ts create mode 100644 src/locales/zh-CN/globalHeader.ts create mode 100644 src/locales/zh-CN/menu.ts create mode 100644 src/locales/zh-CN/pwa.ts create mode 100644 src/locales/zh-CN/setting.ts create mode 100644 src/locales/zh-CN/settingDrawer.ts delete mode 100644 src/main.ts create mode 100644 src/manifest.json create mode 100644 src/pages/404.tsx create mode 100644 src/pages/Metrics/Metrics.tsx create mode 100644 src/pages/Routes/Create.less create mode 100644 src/pages/Routes/Create.tsx create mode 100644 src/pages/Routes/List.tsx create mode 100644 src/pages/Routes/components/ActionBar/ActionBar.tsx create mode 100644 src/pages/Routes/components/ActionBar/index.ts create mode 100644 src/pages/Routes/components/CreateStep3/CreateStep3.tsx create mode 100644 src/pages/Routes/components/CreateStep3/PluginCard.tsx create mode 100644 src/pages/Routes/components/CreateStep3/PluginDrawer.tsx create mode 100644 src/pages/Routes/components/CreateStep3/index.ts create mode 100644 src/pages/Routes/components/CreateStep4/CreateStep4.tsx create mode 100644 src/pages/Routes/components/CreateStep4/index.ts create mode 100644 src/pages/Routes/components/PanelSection/index.tsx create mode 100644 src/pages/Routes/components/ResultView/ResultView.tsx create mode 100644 src/pages/Routes/components/ResultView/index.ts create mode 100644 src/pages/Routes/components/Step1/MatchingRulesView.tsx create mode 100644 src/pages/Routes/components/Step1/MetaView.tsx create mode 100644 src/pages/Routes/components/Step1/RequestConfigView.tsx create mode 100644 src/pages/Routes/components/Step1/index.tsx create mode 100644 src/pages/Routes/components/Step2/HttpHeaderRewriteView.tsx create mode 100644 src/pages/Routes/components/Step2/RequestRewriteView.tsx create mode 100644 src/pages/Routes/components/Step2/index.tsx create mode 100644 src/pages/Routes/constants.ts create mode 100644 src/pages/Routes/service.ts create mode 100644 src/pages/Routes/transform.ts create mode 100644 src/pages/Routes/typing.d.ts create mode 100644 src/pages/Setting/Setting.tsx create mode 100644 src/pages/Setting/index.ts create mode 100644 src/pages/Setting/service.ts create mode 100644 src/pages/Setting/style.less create mode 100644 src/pages/Setting/typingd.d.ts create mode 100644 src/pages/document.ejs create mode 100644 src/pages/ssl/Create.less create mode 100644 src/pages/ssl/Create.tsx create mode 100644 src/pages/ssl/List.tsx create mode 100644 src/pages/ssl/components/CertificateForm/index.tsx create mode 100644 src/pages/ssl/components/CertificateUploader/index.tsx create mode 100644 src/pages/ssl/components/Step1/index.tsx create mode 100644 src/pages/ssl/components/Step2/index.tsx create mode 100644 src/pages/ssl/components/Step3/index.tsx create mode 100644 src/pages/ssl/service.ts create mode 100644 src/pages/ssl/typing.d.ts delete mode 100644 src/permission.ts delete mode 100644 src/router/index.ts delete mode 100644 src/router/modules/schema/consumers.ts delete mode 100644 src/router/modules/schema/routes.ts delete mode 100644 src/router/modules/schema/services.ts delete mode 100644 src/router/modules/schema/ssl.ts delete mode 100644 src/router/modules/schema/upstream.ts create mode 100644 src/service-worker.js create mode 100644 src/services/API.d.ts create mode 100644 src/services/login.ts create mode 100644 src/services/user.ts delete mode 100644 src/settings.ts delete mode 100644 src/shims.d.ts delete mode 100644 src/store/modules/app.ts delete mode 100644 src/store/modules/permission.ts delete mode 100644 src/store/modules/settings.ts delete mode 100644 src/store/modules/tags-view.ts delete mode 100644 src/store/modules/user.ts delete mode 100644 src/styles/_mixins.scss delete mode 100644 src/styles/_svgicon.scss delete mode 100644 src/styles/_transition.scss delete mode 100644 src/styles/_variables.scss delete mode 100644 src/styles/_variables.scss.d.ts delete mode 100644 src/styles/element-variables.scss delete mode 100644 src/styles/element-variables.scss.d.ts delete mode 100644 src/styles/index.scss create mode 100644 src/transforms/global.ts create mode 100644 src/typings.d.ts delete mode 100644 src/utils/cookies.ts delete mode 100644 src/utils/index.ts delete mode 100644 src/utils/permission.ts delete mode 100644 src/utils/request.ts delete mode 100644 src/utils/scroll-to.ts delete mode 100644 src/utils/validate.ts delete mode 100644 src/views/login/index.vue delete mode 100644 src/views/schema/consumers/edit.vue delete mode 100644 src/views/schema/consumers/list.vue delete mode 100644 src/views/schema/routes/edit.vue delete mode 100644 src/views/schema/routes/list.vue delete mode 100644 src/views/schema/service/edit.vue delete mode 100644 src/views/schema/service/list.vue delete mode 100644 src/views/schema/ssl/edit.vue delete mode 100644 src/views/schema/ssl/list.vue delete mode 100644 src/views/schema/upstream/edit.vue delete mode 100644 src/views/schema/upstream/list.vue create mode 100644 tests/PuppeteerEnvironment.js create mode 100644 tests/beforeTest.js create mode 100644 tests/getBrowser.js create mode 100644 tests/run-tests.js delete mode 100644 vue.config.js diff --git a/CHANGELOG.md b/.asf.yaml similarity index 62% rename from CHANGELOG.md rename to .asf.yaml index f2eb346c7b..fe73d207c7 100644 --- a/CHANGELOG.md +++ b/.asf.yaml @@ -1,5 +1,3 @@ - - - -# Table of Contents - -- [1.0.0](#100) - -## 1.0.0 -This release is mainly to build some basic panels and resolve License issue. +github: + description: Dashboard for Apache APISIX + homepage: https://apisix.apache.org/ + labels: + - dashboard + - api + - api-management + - apisix + - devops + - docker -### Core -- Dashboard initial. [#1](https://github.com/apache/incubator-apisix-dashboard/pull/1) -- Resolve licence issues. -- Remove unused files from the Dashboard boilerplate. -- Support panel to list, create and modify Route, Consumer, Service, SSL and Upstream. -- Support custom configuration for Plugin dialog. + enabled_merge_buttons: + squash: true + merge: false + rebase: false -[Back to TOC](#table-of-contents) + notifications: + commits: notifications@apisix.apache.org + issues: notifications@apisix.apache.org + pullrequests: notifications@apisix.apache.org diff --git a/.browserslistrc b/.browserslistrc deleted file mode 100644 index 3a455dd9c4..0000000000 --- a/.browserslistrc +++ /dev/null @@ -1,2 +0,0 @@ -> 1% -last 2 versions \ No newline at end of file diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000..3c3629e647 --- /dev/null +++ b/.dockerignore @@ -0,0 +1 @@ +node_modules diff --git a/.editorconfig b/.editorconfig index 9b384636d5..7e3649acc2 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,35 +1,16 @@ # http://editorconfig.org - -# top-most EditorConfig file root = true -# Unix-style newlines with a newline ending every file [*] -charset = utf-8 -end_of_line = lf -insert_final_newline = true -trim_trailing_whitespace = true - -# Indentation override for js(x), ts(x) and vue files -[*.{js,jsx,ts,tsx,vue}] -indent_size = 2 indent_style = space - -# Indentation override for css related files -[*.{css,styl,scss,less,sass}] indent_size = 2 -indent_style = space - -# Indentation override for html files -[*.html] -indent_size = 2 -indent_style = space +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true -# Trailing space override for markdown file [*.md] trim_trailing_whitespace = false -# Indentation override for config files -[*.{json,yml}] -indent_size = 2 -indent_style = space \ No newline at end of file +[Makefile] +indent_style = tab diff --git a/.env.development b/.env.development deleted file mode 100644 index 1e3d95141f..0000000000 --- a/.env.development +++ /dev/null @@ -1,11 +0,0 @@ -# Base api -VUE_APP_BASE_API = '' - -# vue-cli uses the VUE_CLI_BABEL_TRANSPILE_MODULES environment variable, -# to control whether the babel-plugin-dynamic-import-node plugin is enabled. -# It only does one thing by converting all import() to require(). -# This configuration can significantly increase the speed of hot updates, -# when you have a large number of pages. -# Detail: https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/babel-preset-app/index.js - -VUE_CLI_BABEL_TRANSPILE_MODULES = true \ No newline at end of file diff --git a/.env.production b/.env.production deleted file mode 100644 index edd19d0878..0000000000 --- a/.env.production +++ /dev/null @@ -1,5 +0,0 @@ - -# Base api -# Remeber to change this to your production server address -# Here I used my mock server for this project -VUE_APP_BASE_API = '/apisix/admin/' \ No newline at end of file diff --git a/.eslintignore b/.eslintignore index 4bcf40fa4c..16116a2b4b 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,3 +1,4 @@ - -dist/*.js -tests/unit/coverage \ No newline at end of file +/lambda/ +/scripts +/config +.history \ No newline at end of file diff --git a/.eslintrc.js b/.eslintrc.js index 4f0b93f5d6..b882c20e87 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,37 +1,8 @@ module.exports = { - root: true, - env: { - browser: true, - node: true, - es6: true - }, - parserOptions: { - parser: '@typescript-eslint/parser', - sourceType: 'module' - }, - plugins: [ - 'vue' - ], - rules: { - 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off', - 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', - 'space-before-function-paren': [2, 'never'], - 'vue/array-bracket-spacing': 'error', - 'vue/arrow-spacing': 'error', - 'vue/block-spacing': 'error', - 'vue/brace-style': 'error', - 'vue/comma-dangle': 'error', - 'vue/component-name-in-template-casing': 'error', - 'vue/eqeqeq': 'error', - 'vue/key-spacing': 'error', - 'vue/match-component-file-name': 'error', - 'vue/object-curly-spacing': 'error', - "camelcase": 'off' - }, - 'extends': [ - 'eslint:recommended', - 'plugin:vue/recommended', - '@vue/standard', - '@vue/typescript' - ] - } \ No newline at end of file + extends: [require.resolve('@umijs/fabric/dist/eslint')], + globals: { + ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION: true, + page: true, + REACT_APP_ENV: true, + }, +}; diff --git a/.github/workflows/api_ut.yml b/.github/workflows/api_ut.yml new file mode 100644 index 0000000000..2b3c4bb4e2 --- /dev/null +++ b/.github/workflows/api_ut.yml @@ -0,0 +1,18 @@ +name: API unit test + +on: + push: + branches: + - master + - manager + pull_request: + branches: + - master + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: use docker-compose in api + run: cd ./api && docker-compose up \ No newline at end of file diff --git a/.gitignore b/.gitignore index 2b33ebeb83..9caa19201b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,21 +1,43 @@ -.DS_Store -node_modules -/dist +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. -# local env files -.env.local -.env.*.local +# dependencies +**/node_modules +# roadhog-api-doc ignore +/src/utils/request-temp.js +_roadhog-api-doc -# Log files +# production +/dist +/.vscode + +# misc +.DS_Store npm-debug.log* -yarn-debug.log* -yarn-error.log* +yarn-error.log -# Editor directories and files +/coverage .idea +package-lock.json +*bak .vscode -*.suo -*.ntvs* -*.njsproj -*.sln -*.sw* \ No newline at end of file + +# visual studio code +.history +*.log +functions/* +.temp/** + +# umi +.umi +.umi-production + +# screenshot +screenshot +.firebase +.eslintcache + +build + +/compose/**/*.log +/compose/**/nginx.pid +/compose/etcd_data \ No newline at end of file diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000000..87715a7dfb --- /dev/null +++ b/.prettierignore @@ -0,0 +1,21 @@ +**/*.svg +package.json +.umi +.umi-production +/dist +.dockerignore +.DS_Store +.eslintignore +*.png +*.toml +docker +.editorconfig +Dockerfile* +.gitignore +.prettierignore +LICENSE +.eslintcache +*.lock +yarn-error.log +.history +CNAME diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 0000000000..7b597d7891 --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1,5 @@ +const fabric = require('@umijs/fabric'); + +module.exports = { + ...fabric.prettier, +}; diff --git a/.stylelintrc.js b/.stylelintrc.js new file mode 100644 index 0000000000..c2030787de --- /dev/null +++ b/.stylelintrc.js @@ -0,0 +1,5 @@ +const fabric = require('@umijs/fabric'); + +module.exports = { + ...fabric.stylelint, +}; diff --git a/DISCLAIMER b/DISCLAIMER deleted file mode 100644 index 70fc20cf7d..0000000000 --- a/DISCLAIMER +++ /dev/null @@ -1,5 +0,0 @@ -Apache APISIX Dashboard (incubating) is an effort undergoing incubation at The Apache Software Foundation (ASF), sponsored by the Apache Incubator PMC. -Incubation is required of all newly accepted projects until a further review indicates that the infrastructure, -communications, and decision making process have stabilized in a manner consistent with other successful ASF projects. -While incubation status is not necessarily a reflection of the completeness or stability of the code, -it does indicate that the project has yet to be fully endorsed by the ASF. \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000..72ac8d3dbb --- /dev/null +++ b/Dockerfile @@ -0,0 +1,19 @@ +# phase-build +FROM node:12-alpine as builder + +WORKDIR /usr/src/app/ +USER root + +COPY package.json /usr/src/app/ +RUN yarn + +COPY . /usr/src/app/ +RUN yarn build && rm -rf /usr/src/app/node_modules + +# phase-run +FROM nginx:1.16-alpine + +COPY ./docker/nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=builder /usr/src/app/dist /usr/share/nginx/html/dashboard + +EXPOSE 80 diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 6da9712eb9..0000000000 --- a/LICENSE +++ /dev/null @@ -1,206 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -======================================================================= - -The Apache APISIX project bundles vue-typescript-admin-template under the MIT license. -For details, see licenses/LICENSE.vue-typescript-admin-template. diff --git a/NOTICE b/NOTICE deleted file mode 100644 index f0a448373f..0000000000 --- a/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -Apache APISIX Dashboard (incubating) -Copyright 2020 The Apache Software Foundation - -This product includes software developed at -The Apache Software Foundation (http://www.apache.org/). diff --git a/README-dashboard.md b/README-dashboard.md new file mode 100644 index 0000000000..74f87484ed --- /dev/null +++ b/README-dashboard.md @@ -0,0 +1,47 @@ +# READMD for Dashboard + +This project is initialized with [Ant Design Pro](https://pro.ant.design). Follow is the quick guide for how to use. + +## Environment Prepare + +1. Make sure you have `Node.js` installed on your machine. +2. Install [yarn](https://yarnpkg.com/). +3. Install `node_modules`: + +```bash +$ yarn +``` + +### Start project + +```bash +yarn start:no-mock +``` + +### Build project + +```bash +yarn build +``` + +### Check code style + +```bash +yarn lint +``` + +You can also use script to auto fix some lint error: + +```bash +yarn lint:fix +``` + +### Test code + +```bash +yarn test +``` + +## More + +You can view full document on our [official website](https://pro.ant.design). And welcome any feedback in our [github](https://github.com/ant-design/ant-design-pro). diff --git a/README.md b/README.md index 438999c3ed..8b13b91773 100644 --- a/README.md +++ b/README.md @@ -1,110 +1,12 @@ - +# Apache APISIX Dashboard -# apisix_dashboard +Dashboard for [Apache APISIX](https://github.com/apache/incubator-apisix-dashboard) -## Overview +## Deploy with Docker -Dashboard for APISIX & based on ElementUI. +Please refer to [Deploy with Docker README](./compose/README.md) -## Documentation +## More -[Docs](https://armour.github.io/vue-typescript-admin-docs) - -[Vue Config Docs](https://cli.vuejs.org/zh/config/#publicpath) - -## Project Structure - -```bash -├── public # public static assets -│ │── img/ # static image files -│ │── favicon.ico # favicon -│ │── index.html # index.html template -│ └── robots.txt # robots file -├── src # main source code -│ ├── api/ # api service -│ ├── components/ # global components -│ ├── lang/ # i18n language -│ ├── layout/ # global layout -│ ├── router/ # router -│ ├── store/ # store -│ ├── styles/ # global css -│ ├── utils/ # global utils -│ ├── views/ # views -│ ├── App.vue # main app component -│ ├── main.ts # app entry file -│ ├── permission.ts # permission authentication -│ ├── settings.ts # setting file -│ └── shims.d.ts # type definition shims -├── licenses # license files for ALv2 and boilerplate -├── .browserslistrc # browserslist config file (to support Autoprefixer) -├── .editorconfig # editor code format consistency config -├── .env.xxx # env variable configuration -├── .eslintrc.js # eslint config -├── .eslintignore # eslint ignore config -├── .gitignore # git ignore config -├── babel.config.js # babel config -├── LICENSE # license file -├── NOTICE # notice file -├── package.json # package.json -├── postcss.config.js # postcss config -├── README.md # some information about APISIX -├── tsconfig.json # typescript config -├── vue.config.js # vue-cli config -└── yarn.lock # keep exact versions of each dependency -``` - -## Project setup -> Make sure Node.js 8.12.0 or higher, and Yarn are installed on your machine: https://yarnpkg.com/en/docs/install - -### Install dependencies - -```bash -yarn install -``` - -### Compiles and hot-reloads for development - -```bash -yarn run serve -``` - -### Compiles and minifies for production - -```bash -yarn run build:prod -``` - -### Lints and fixes files - -```bash -yarn run lint -``` - -### Customize Vue configuration - -See [Configuration Reference](https://cli.vuejs.org/config/). - -## Browsers support - -Modern browsers and Internet Explorer 10+. - -| [IE / Edge](http://godban.github.io/browsers-support-badges/)
IE / Edge | [Firefox](http://godban.github.io/browsers-support-badges/)
Firefox | [Chrome](http://godban.github.io/browsers-support-badges/)
Chrome | [Safari](http://godban.github.io/browsers-support-badges/)
Safari | -| --------- | --------- | --------- | --------- | -| IE10, IE11, Edge| last 2 versions| last 2 versions| last 2 versions +1. More infomation about the frontend Dashboard, please refer to [README for Dashboard](./README-dashboard.md) +2. If you need the dashboard built with Vue.js, please refer to [master-vue](https://github.com/apache/incubator-apisix-dashboard/tree/master-vue). diff --git a/api/Dockerfile b/api/Dockerfile new file mode 100644 index 0000000000..85092a15a6 --- /dev/null +++ b/api/Dockerfile @@ -0,0 +1,49 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +FROM golang:1.13.8 AS build-env + +WORKDIR /go/src/github.com/apisix/manager-api +COPY . . +RUN mkdir /root/manager-api \ + && go env -w GOPROXY=https://goproxy.io,direct \ + && export GOPROXY=https://goproxy.io \ + && go build -o /root/manager-api/manager-api \ + && mv /go/src/github.com/apisix/manager-api/build.sh /root/manager-api/ \ + && mv /go/src/github.com/apisix/manager-api/conf.json /root/manager-api/ \ + && rm -rf /go/src/github.com/apisix/manager-api \ + && rm -rf /etc/localtime \ + && ln -s /usr/share/zoneinfo/Hongkong /etc/localtime \ + && dpkg-reconfigure -f noninteractive tzdata + +FROM alpine:3.11 + +RUN mkdir /root/manager-api \ + && apk update \ + && apk add ca-certificates \ + && update-ca-certificates \ + && apk add --no-cache libc6-compat \ + && echo "hosts: files dns" > /etc/nsswitch.conf \ + && rm -rf /var/cache/apk/* + + +WORKDIR /root/manager-api +COPY --from=build-env /root/manager-api/* /root/manager-api/ +COPY --from=build-env /usr/share/zoneinfo/Hongkong /etc/localtime +EXPOSE 8080 +RUN chmod +x ./build.sh +CMD ["/root/manager-api/build.sh"] diff --git a/src/App.vue b/api/README.md similarity index 78% rename from src/App.vue rename to api/README.md index adf29313a1..24befa61a7 100644 --- a/src/App.vue +++ b/api/README.md @@ -17,17 +17,6 @@ # --> - +# manager-api - +This is a back-end project that the dashboard depends on, implemented through golang. diff --git a/api/build.sh b/api/build.sh new file mode 100644 index 0000000000..086fe73c51 --- /dev/null +++ b/api/build.sh @@ -0,0 +1,30 @@ +#!/bin/sh +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +pwd=`pwd` + +sed -i -e "s%#mysqlAddress#%`echo $MYSQL_SERVER_ADDRESS`%g" ${pwd}/conf.json +sed -i -e "s%#mysqlUser#%`echo $MYSQL_USER`%g" ${pwd}/conf.json +sed -i -e "s%#mysqlPWD#%`echo $MYSQL_PASSWORD`%g" ${pwd}/conf.json +sed -i -e "s%#syslogAddress#%`echo $SYSLOG_HOST`%g" ${pwd}/conf.json +sed -i -e "s%#apisixBaseUrl#%`echo $APISIX_BASE_URL`%g" ${pwd}/conf.json +sed -i -e "s%#apisixApiKey#%`echo $APISIX_API_KEY`%g" ${pwd}/conf.json + +cd /root/manager-api +exec ./manager-api + diff --git a/api/conf.json b/api/conf.json new file mode 100644 index 0000000000..31cbcce97d --- /dev/null +++ b/api/conf.json @@ -0,0 +1,19 @@ +{ + "conf": { + "mysql":{ + "address": "#mysqlAddress#", + "user": "#mysqlUser#", + "password": "#mysqlPWD#", + "maxConns": 50, + "maxIdleConns": 25, + "maxLifeTime": 10 + }, + "syslog": { + "host": "#syslogAddress#" + }, + "apisix": { + "base_url": "#apisixBaseUrl#", + "api_key": "#apisixApiKey#" + } + } +} diff --git a/api/conf/conf.go b/api/conf/conf.go new file mode 100644 index 0000000000..58197890e2 --- /dev/null +++ b/api/conf/conf.go @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conf + +import ( + "fmt" + "github.com/tidwall/gjson" + "io/ioutil" + "os" + "path/filepath" + "runtime" +) + +const ServerPort = 8080 +const PROD = "prod" +const BETA = "beta" +const DEV = "dev" +const LOCAL = "local" +const confPath = "/root/manager-api/conf.json" +const RequestId = "requestId" + +var ( + ENV string + basePath string + ApiKey = "edd1c9f034335f136f87ad84b625c8f1" + BaseUrl = "http://127.0.0.1:9080/apisix/admin" +) + +func init() { + setEnvironment() + initMysql() + initApisix() +} + +func setEnvironment() { + if env := os.Getenv("ENV"); env == "" { + ENV = LOCAL + } else { + ENV = env + } + _, basePath, _, _ = runtime.Caller(1) +} + +func configurationPath() string { + if ENV == LOCAL { + return filepath.Join(filepath.Dir(basePath), "conf.json") + } else { + return confPath + } +} + +type mysqlConfig struct { + Address string + User string + Password string + + MaxConns int + MaxIdleConns int + MaxLifeTime int +} + +var MysqlConfig mysqlConfig + +func initMysql() { + filePath := configurationPath() + if configurationContent, err := ioutil.ReadFile(filePath); err != nil { + panic(fmt.Sprintf("fail to read configuration: %s", filePath)) + } else { + configuration := gjson.ParseBytes(configurationContent) + mysqlConf := configuration.Get("conf.mysql") + MysqlConfig.Address = mysqlConf.Get("address").String() + MysqlConfig.User = mysqlConf.Get("user").String() + MysqlConfig.Password = mysqlConf.Get("password").String() + MysqlConfig.MaxConns = int(mysqlConf.Get("maxConns").Int()) + MysqlConfig.MaxIdleConns = int(mysqlConf.Get("maxIdleConns").Int()) + MysqlConfig.MaxLifeTime = int(mysqlConf.Get("maxLifeTime").Int()) + } +} + +func initApisix() { + filePath := configurationPath() + if configurationContent, err := ioutil.ReadFile(filePath); err != nil { + panic(fmt.Sprintf("fail to read configuration: %s", filePath)) + } else { + configuration := gjson.ParseBytes(configurationContent) + apisixConf := configuration.Get("conf.apisix") + BaseUrl = apisixConf.Get("base_url").String() + ApiKey = apisixConf.Get("api_key").String() + } +} diff --git a/api/conf/conf.json b/api/conf/conf.json new file mode 100644 index 0000000000..95fe86e8c9 --- /dev/null +++ b/api/conf/conf.json @@ -0,0 +1,19 @@ +{ + "conf":{ + "mysql":{ + "address": "127.0.0.1:3306", + "user": "root", + "password": "123456", + "maxConns": 50, + "maxIdleConns": 25, + "maxLifeTime": 10 + }, + "syslog":{ + "host": "localhost" + }, + "apisix":{ + "base_url": "http://127.0.0.1:9080/apisix/admin", + "api_key": "edd1c9f034335f136f87ad84b625c8f1" + } + } +} \ No newline at end of file diff --git a/src/api/schema/consumers.ts b/api/conf/mysql.go similarity index 52% rename from src/api/schema/consumers.ts rename to api/conf/mysql.go index 06b72d8e68..62e0f9e7f2 100644 --- a/src/api/schema/consumers.ts +++ b/api/conf/mysql.go @@ -14,37 +14,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package conf -import request from '@/utils/request' +import ( + "fmt" + "github.com/jinzhu/gorm" + _ "github.com/jinzhu/gorm/dialects/mysql" + "time" +) -import { IConsumerData } from '../types' +var db *gorm.DB -export const defaultConsumerData: IConsumerData = { - username: '', - plugins: {} +func DB() *gorm.DB { + return db } -export const updateOrCreateConsumer = (data: IConsumerData) => - request({ - url: '/consumers', - method: 'PUT', - data - }) +// InitializeMysql creates mysql's *sqlDB instance +func InitializeMysql() { + dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", MysqlConfig.User, + MysqlConfig.Password, MysqlConfig.Address, "manager") + if tmp, err := gorm.Open("mysql", dsn); err != nil { + panic(fmt.Sprintf("fail to connect to DB: %s for %s", err.Error(), dsn)) + } else { + db = tmp + db.LogMode(true) + db.DB().SetMaxOpenConns(MysqlConfig.MaxConns) + db.DB().SetMaxIdleConns(MysqlConfig.MaxIdleConns) + db.DB().SetConnMaxLifetime(time.Duration(MysqlConfig.MaxLifeTime) * time.Minute) + } -export const getList = () => - request({ - url: '/consumers', - method: 'GET' - }) - -export const get = (username: string) => - request({ - url: `/consumers/${username}`, - method: 'GET' - }) - -export const removeConsumer = (username: string) => - request({ - url: `/consumers/${username}`, - method: 'DELETE' - }) +} diff --git a/api/docker-compose.yml b/api/docker-compose.yml new file mode 100644 index 0000000000..79760d7ae4 --- /dev/null +++ b/api/docker-compose.yml @@ -0,0 +1,9 @@ +version: "3" + +services: + manager: + image: golang:1.13.8 + volumes: + - .:/go/src/github.com/apisix/manager-api + working_dir: /go/src/github.com/apisix/manager-api + command: go test -v github.com/apisix/manager-api/service diff --git a/api/errno/error.go b/api/errno/error.go new file mode 100644 index 0000000000..20b7e2435d --- /dev/null +++ b/api/errno/error.go @@ -0,0 +1,98 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package errno + +import ( + "encoding/json" + "fmt" +) + +type Message struct { + Code string + Msg string +} + +var ( + //AA 01 api-manager-api + SystemSuccess = Message{"010000", "success"} + SystemError = Message{"010001", "system error"} + BadRequestError = Message{Code: "010002", Msg: "Request format error"} + NotFoundError = Message{Code: "010003", Msg: "No resources found"} + + //BB 01 config module + ConfEnvError = Message{"010101", "Environment variable not found: %s"} + ConfFilePathError = Message{"010102", "Error loading configuration file: %s"} + + // BB 02 route module + RouteRequestError = Message{"010201", "Route request parameters are abnormal: %s"} + ApisixRouteCreateError = Message{"010202", "Failed to create APISIX route: %s"} + DBRouteCreateError = Message{"010203", "Route storage failure: %s"} + ApisixRouteUpdateError = Message{"010204", "Update APISIX routing failed: %s"} + ApisixRouteDeleteError = Message{"010205", "Failed to remove APISIX route: %s"} + DBRouteUpdateError = Message{"010206", "Route update failed: %s"} + DBRouteDeleteError = Message{"010207", "Route remove failed: %s"} + + // 03 plugin module + ApisixPluginListError = Message{"010301", "List APISIX plugins failed: %s"} + ApisixPluginSchemaError = Message{"010301", "Find APISIX plugin schema failed: %s"} +) + +type ManagerError struct { + TraceId string + Code string + Msg string + Data interface{} +} + +// toString +func (e *ManagerError) Error() string { + return e.Msg +} + +func FromMessage(m Message, args ...interface{}) *ManagerError { + return &ManagerError{TraceId: "", Code: m.Code, Msg: fmt.Sprintf(m.Msg, args...)} +} + +func (e *ManagerError) Response() map[string]interface{} { + return map[string]interface{}{ + "code": e.Code, + "msg": e.Msg, + } +} + +func (e *ManagerError) ItemResponse(data interface{}) map[string]interface{} { + return map[string]interface{}{ + "code": e.Code, + "msg": e.Msg, + "data": data, + } +} + +func (e *ManagerError) ListResponse(count, list interface{}) map[string]interface{} { + return map[string]interface{}{ + "code": e.Code, + "msg": e.Msg, + "count": count, + "list": list, + } +} + +func Success() []byte { + w := FromMessage(SystemSuccess).Response() + result, _ := json.Marshal(w) + return result +} diff --git a/babel.config.js b/api/filter/cors.go similarity index 64% rename from babel.config.js rename to api/filter/cors.go index e7708a0dbf..f2c7ac1537 100644 --- a/babel.config.js +++ b/api/filter/cors.go @@ -14,9 +14,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package filter -module.exports = { - presets: [ - '@vue/app' - ] +import "github.com/gin-gonic/gin" + +func CORS() gin.HandlerFunc { + return func(c *gin.Context) { + c.Writer.Header().Set("Access-Control-Allow-Origin", "*") + c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") + c.Writer.Header().Set("Access-Control-Allow-Headers", "*") + c.Writer.Header().Set("Access-Control-Allow-Methods", "*") + if c.Request.Method == "OPTIONS" { + c.AbortWithStatus(204) + return + } + c.Next() + } } diff --git a/api/filter/logging.go b/api/filter/logging.go new file mode 100644 index 0000000000..22f55288b4 --- /dev/null +++ b/api/filter/logging.go @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package filter + +import ( + "bytes" + "github.com/apisix/manager-api/errno" + "github.com/gin-gonic/gin" + "github.com/sirupsen/logrus" + "time" +) + +func RequestLogHandler() gin.HandlerFunc { + return func(c *gin.Context) { + start, host, remoteIP, path, method := time.Now(), c.Request.Host, c.ClientIP(), c.Request.URL.Path, c.Request.Method + var val interface{} + if method == "GET" { + val = c.Request.URL.Query() + } else { + val, _ = c.GetRawData() + } + c.Set("requestBody", val) + uuid, _ := c.Get("X-Request-Id") + + param, _ := c.Get("requestBody") + switch param.(type) { + case []byte: + param = string(param.([]byte)) + default: + } + + blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer} + c.Writer = blw + c.Next() + latency := time.Now().Sub(start) / 1000000 + statusCode := c.Writer.Status() + respBody := blw.body.String() + if uuid == "" { + uuid = c.Writer.Header().Get("X-Request-Id") + } + var errs []string + for _, err := range c.Errors { + if e, ok := err.Err.(*errno.ManagerError); ok { + errs = append(errs, e.Error()) + } + } + logger.WithFields(logrus.Fields{ + "requestId": uuid, + "latency": latency, + "remoteIp": remoteIP, + "method": method, + "path": path, + "statusCode": statusCode, + "host": host, + "params": param, + "respBody": respBody, + "errMsg": errs, + }).Info("") + } +} + +type bodyLogWriter struct { + gin.ResponseWriter + body *bytes.Buffer +} + +func (w bodyLogWriter) Write(b []byte) (int, error) { + w.body.Write(b) + return w.ResponseWriter.Write(b) +} diff --git a/api/filter/recover.go b/api/filter/recover.go new file mode 100644 index 0000000000..433331f110 --- /dev/null +++ b/api/filter/recover.go @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package filter + +import ( + "bytes" + "fmt" + "github.com/apisix/manager-api/log" + "github.com/gin-gonic/gin" + "github.com/sirupsen/logrus" + "io/ioutil" + "net/http" + "runtime" + "time" +) + +var ( + logger = log.GetLogger() + dunno = []byte("???") + centerDot = []byte("·") + dot = []byte(".") + slash = []byte("/") +) + +func RecoverHandler() gin.HandlerFunc { + return func(c *gin.Context) { + defer func() { + if err := recover(); err != nil { + uuid := c.Writer.Header().Get("X-Request-Id") + logger.WithFields(logrus.Fields{ + "uuid": uuid, + }) + stack := stack(3) + logger.Errorf("[Recovery] %s panic recovered:\n\n%s\n%s", timeFormat(time.Now()), err, stack) + c.AbortWithStatus(http.StatusInternalServerError) + } + }() + c.Next() + } +} + +func WrapGo(f func(...interface{}), args ...interface{}) { + defer func() { + if err := recover(); err != nil { + stack := stack(3) + logger.Errorf("[Recovery] %s panic recovered:\n\n%s\n%s", timeFormat(time.Now()), err, stack) + } + }() + f(args...) +} + +func stack(skip int) []byte { + buf := new(bytes.Buffer) // the returned data + // loaded file. + var lines [][]byte + var lastFile string + for i := skip; ; i++ { + pc, file, line, ok := runtime.Caller(i) + if !ok { + break + } + // Print this much at least. If we can't find the source, it won't show. + fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc) + if file != lastFile { + data, err := ioutil.ReadFile(file) + if err != nil { + continue + } + lines = bytes.Split(data, []byte{'\n'}) + lastFile = file + } + fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line)) + } + return buf.Bytes() +} + +// source returns a space-trimmed slice of the n'th line. +func source(lines [][]byte, n int) []byte { + n-- // in stack trace, lines are 1-indexed but our array is 0-indexed + if n < 0 || n >= len(lines) { + return dunno + } + return bytes.TrimSpace(lines[n]) +} + +// function returns, if possible, the name of the function containing the PC. +func function(pc uintptr) []byte { + fn := runtime.FuncForPC(pc) + if fn == nil { + return dunno + } + name := []byte(fn.Name()) + if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 { + name = name[lastslash+1:] + } + if period := bytes.Index(name, dot); period >= 0 { + name = name[period+1:] + } + name = bytes.Replace(name, centerDot, dot, -1) + return name +} + +func timeFormat(t time.Time) string { + var timeString = t.Format("2006/01/02 - 15:04:05") + return timeString +} diff --git a/src/api/schema/plugins.ts b/api/filter/request_id.go similarity index 60% rename from src/api/schema/plugins.ts rename to api/filter/request_id.go index bc71e9605f..2992869ac6 100644 --- a/src/api/schema/plugins.ts +++ b/api/filter/request_id.go @@ -14,11 +14,29 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package filter -import request from '@/utils/request' +import ( + "github.com/gin-gonic/gin" + "github.com/satori/go.uuid" +) -export const getPluginList = () => - request({ - url: '/plugins/list', - method: 'get' - }) +func RequestId() gin.HandlerFunc { + return func(c *gin.Context) { + // Check for incoming header, use it if exists + requestId := c.Request.Header.Get("X-Request-Id") + + // Create request id with UUID4 + if requestId == "" { + u4 := uuid.NewV4() + requestId = u4.String() + } + + // Expose it for use in the application + c.Set("X-Request-Id", requestId) + + // Set X-Request-Id header + c.Writer.Header().Set("X-Request-Id", requestId) + c.Next() + } +} diff --git a/api/go.mod b/api/go.mod new file mode 100644 index 0000000000..45372ec421 --- /dev/null +++ b/api/go.mod @@ -0,0 +1,15 @@ +module github.com/apisix/manager-api + +go 1.13 + +require ( + github.com/gin-contrib/pprof v1.3.0 + github.com/gin-gonic/gin v1.6.3 + github.com/go-sql-driver/mysql v1.5.0 + github.com/jinzhu/gorm v1.9.12 + github.com/satori/go.uuid v1.2.0 + github.com/sirupsen/logrus v1.6.0 + github.com/stretchr/testify v1.4.0 + github.com/tidwall/gjson v1.6.0 + gopkg.in/resty.v1 v1.12.0 +) diff --git a/api/go.sum b/api/go.sum new file mode 100644 index 0000000000..9e3e3e32a6 --- /dev/null +++ b/api/go.sum @@ -0,0 +1,89 @@ +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/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= +github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0= +github.com/gin-contrib/pprof v1.3.0 h1:G9eK6HnbkSqDZBYbzG4wrjCsA4e+cvYAHUZw6W+W9K0= +github.com/gin-contrib/pprof v1.3.0/go.mod h1:waMjT1H9b179t3CxuG1cV3DHpga6ybizwfBaM5OXaB0= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.6.2/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= +github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14= +github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= +github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= +github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY= +github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= +github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= +github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/jinzhu/gorm v1.9.12 h1:Drgk1clyWT9t9ERbzHza6Mj/8FY/CqMyVzOiHviMo6Q= +github.com/jinzhu/gorm v1.9.12/go.mod h1:vhTjlKSJUTWNtcbQtrMBFCxy7eXTzeCAzfL5fBZT/Qs= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= +github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8= +github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= +github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-sqlite3 v2.0.1+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +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/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= +github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= +github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I= +github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +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 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/tidwall/gjson v1.6.0 h1:9VEQWz6LLMUsUl6PueE49ir4Ka6CzLymOAZDxpFsTDc= +github.com/tidwall/gjson v1.6.0/go.mod h1:P256ACg0Mn+j1RXIDXoss50DeIABTYK1PULOJHhxOls= +github.com/tidwall/match v1.0.1 h1:PnKP62LPNxHKTwvHHZZzdOAOCtsJTjo6dZLCwpKm5xc= +github.com/tidwall/match v1.0.1/go.mod h1:LujAq0jyVjBy028G1WhWfIzbpQfMO8bBZ6Tyb0+pL9E= +github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= +github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= +github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= +github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= +github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= +github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +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-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +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/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/resty.v1 v1.12.0 h1:CuXP0Pjfw9rOuY6EP+UvtNvt5DSqHpIxILZKT/quCZI= +gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/api/log/log.go b/api/log/log.go new file mode 100644 index 0000000000..c1645e85ee --- /dev/null +++ b/api/log/log.go @@ -0,0 +1,147 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package log + +import ( + "bufio" + "fmt" + "github.com/apisix/manager-api/conf" + "github.com/sirupsen/logrus" + "os" + "runtime" + "strings" +) + +var logEntry *logrus.Entry + +func GetLogger() *logrus.Entry { + if logEntry == nil { + var log = logrus.New() + setNull(log) + log.SetLevel(logrus.DebugLevel) + if conf.ENV != conf.LOCAL { + log.SetLevel(logrus.ErrorLevel) + } + log.SetFormatter(&logrus.JSONFormatter{}) + logEntry = log.WithFields(logrus.Fields{ + "app": "manager-api", + }) + if hook, err := createHook(); err == nil { + log.AddHook(hook) + } + } + return logEntry +} + +func setNull(log *logrus.Logger) { + src, err := os.OpenFile(os.DevNull, os.O_APPEND|os.O_WRONLY, os.ModeAppend) + if err != nil { + fmt.Println("err", err) + } + writer := bufio.NewWriter(src) + log.SetOutput(writer) +} + +type Hook struct { + Formatter func(file, function string, line int) string +} + +func createHook() (*Hook, error) { + return &Hook{ + func(file, function string, line int) string { + return fmt.Sprintf("%s:%d", file, line) + }, + }, nil +} + +func (hook *Hook) Fire(entry *logrus.Entry) error { + str := hook.Formatter(findCaller(5)) + en := entry.WithField("line", str) + en.Level = entry.Level + en.Message = entry.Message + en.Time = entry.Time + line, err := en.String() + if err != nil { + fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err) + return err + } + switch en.Level { + case logrus.PanicLevel: + fmt.Print(line) + return nil + case logrus.FatalLevel: + fmt.Print(line) + return nil + case logrus.ErrorLevel: + fmt.Print(line) + return nil + case logrus.WarnLevel: + fmt.Print(line) + return nil + case logrus.InfoLevel: + fmt.Print(line) + return nil + case logrus.DebugLevel: + fmt.Print(line) + return nil + default: + return nil + } +} + +func (hook *Hook) Levels() []logrus.Level { + return logrus.AllLevels +} + +func findCaller(skip int) (string, string, int) { + var ( + pc uintptr + file string + function string + line int + ) + for i := 0; i < 10; i++ { + pc, file, line = getCaller(skip + i) + if !strings.HasPrefix(file, "logrus") { + break + } + } + if pc != 0 { + frames := runtime.CallersFrames([]uintptr{pc}) + frame, _ := frames.Next() + function = frame.Function + } + return file, function, line +} + +func getCaller(skip int) (uintptr, string, int) { + pc, file, line, ok := runtime.Caller(skip) + if !ok { + return 0, "", 0 + } + n := 0 + for i := len(file) - 1; i > 0; i-- { + if file[i] == '/' { + n += 1 + if n >= 2 { + file = file[i+1:] + break + } + } + } + return pc, file, line +} diff --git a/api/main.go b/api/main.go new file mode 100644 index 0000000000..3d756dd7dc --- /dev/null +++ b/api/main.go @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package main + +import ( + "fmt" + "github.com/apisix/manager-api/conf" + "github.com/apisix/manager-api/filter" + "github.com/apisix/manager-api/log" + "github.com/apisix/manager-api/route" + "github.com/gin-contrib/pprof" + "github.com/gin-gonic/gin" + "net/http" + "time" +) + +var logger = log.GetLogger() + +func setUpRouter() *gin.Engine { + if conf.ENV != conf.LOCAL && conf.ENV != conf.BETA { + gin.SetMode(gin.DebugMode) + } else { + gin.SetMode(gin.ReleaseMode) + } + r := gin.New() + + r.Use(filter.CORS(), filter.RequestId(), filter.RequestLogHandler(), filter.RecoverHandler()) + route.AppendHealthCheck(r) + route.AppendRoute(r) + route.AppendSsl(r) + route.AppendPlugin(r) + + pprof.Register(r) + + return r +} + +func main() { + // init + conf.InitializeMysql() + // routes + r := setUpRouter() + addr := fmt.Sprintf(":%d", conf.ServerPort) + s := &http.Server{ + Addr: addr, + Handler: r, + ReadTimeout: time.Duration(1000) * time.Millisecond, + WriteTimeout: time.Duration(5000) * time.Millisecond, + } + s.ListenAndServe() +} diff --git a/src/api/users.ts b/api/route/healthz.go similarity index 69% rename from src/api/users.ts rename to api/route/healthz.go index 591b7876dc..97dcd04526 100644 --- a/src/api/users.ts +++ b/api/route/healthz.go @@ -14,25 +14,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package route -import request from '@/utils/request' +import ( + "github.com/apisix/manager-api/log" + "github.com/gin-gonic/gin" + "net/http" +) -export const getUserInfo = (data: any) => - request({ - url: '/users/info', - method: 'post', - data - }) +var logger = log.GetLogger() -export const login = (data: any) => - request({ - url: '/users/login', - method: 'post', - data - }) +func healthzHandler() gin.HandlerFunc { + return func(c *gin.Context) { + c.Copy() + c.String(http.StatusOK, "pong") + } +} -export const logout = () => - request({ - url: '/users/logout', - method: 'post' - }) +func AppendHealthCheck(r *gin.Engine) *gin.Engine { + r.GET("/ping", healthzHandler()) + return r +} diff --git a/api/route/plugin.go b/api/route/plugin.go new file mode 100644 index 0000000000..0032b134fd --- /dev/null +++ b/api/route/plugin.go @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package route + +import ( + "encoding/json" + "github.com/apisix/manager-api/errno" + "github.com/apisix/manager-api/service" + "github.com/gin-gonic/gin" + "net/http" +) + +func AppendPlugin(r *gin.Engine) *gin.Engine { + r.GET("/apisix/admin/plugins", listPlugin) + r.GET("/apisix/admin/schema/plugins/:name", findSchema) + return r +} + +func findSchema(c *gin.Context) { + name := c.Param("name") + request := &service.ApisixPluginRequest{Name: name} + if result, err := request.Schema(); err != nil { + e := errno.FromMessage(errno.ApisixPluginSchemaError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } else { + resp, _ := json.Marshal(result) + c.Data(http.StatusOK, service.ContentType, resp) + } +} + +func listPlugin(c *gin.Context) { + request := &service.ApisixPluginRequest{} + if result, err := request.List(); err != nil { + e := errno.FromMessage(errno.ApisixPluginListError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } else { + resp, _ := json.Marshal(result) + c.Data(http.StatusOK, service.ContentType, resp) + } +} diff --git a/api/route/route.go b/api/route/route.go new file mode 100644 index 0000000000..efc95d220a --- /dev/null +++ b/api/route/route.go @@ -0,0 +1,242 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package route + +import ( + "encoding/json" + "github.com/apisix/manager-api/conf" + "github.com/apisix/manager-api/errno" + "github.com/apisix/manager-api/service" + "github.com/gin-gonic/gin" + "github.com/satori/go.uuid" + "net/http" + "strconv" +) + +func AppendRoute(r *gin.Engine) *gin.Engine { + r.POST("/apisix/admin/routes", createRoute) + r.GET("/apisix/admin/routes/:rid", findRoute) + r.GET("/apisix/admin/routes", listRoute) + r.PUT("/apisix/admin/routes/:rid", updateRoute) + r.DELETE("/apisix/admin/routes/:rid", deleteRoute) + return r +} + +func listRoute(c *gin.Context) { + db := conf.DB() + size, _ := strconv.Atoi(c.Query("size")) + page, _ := strconv.Atoi(c.Query("page")) + if size == 0 { + size = 10 + } + isSearch := true + if name, exist := c.GetQuery("name"); exist { + db = db.Where("name like ? ", "%"+name+"%") + isSearch = false + } + if description, exist := c.GetQuery("description"); exist { + db = db.Where("description like ? ", "%"+description+"%") + isSearch = false + } + if host, exist := c.GetQuery("host"); exist { + db = db.Where("hosts like ? ", "%"+host+"%") + isSearch = false + } + if uri, exist := c.GetQuery("uri"); exist { + db = db.Where("uris like ? ", "%"+uri+"%") + isSearch = false + } + if ip, exist := c.GetQuery("ip"); exist { + db = db.Where("upstream_nodes like ? ", "%"+ip+"%") + isSearch = false + } + // search + if isSearch { + if search, exist := c.GetQuery("search"); exist { + db = db.Where("name like ? ", "%"+search+"%"). + Or("description like ? ", "%"+search+"%"). + Or("hosts like ? ", "%"+search+"%"). + Or("uris like ? ", "%"+search+"%"). + Or("upstream_nodes like ? ", "%"+search+"%") + } + } + // todo params check + // mysql + routeList := []service.Route{} + var count int + if err := db.Order("priority, update_time desc").Table("routes").Offset((page - 1) * size).Limit(size).Find(&routeList).Count(&count).Error; err != nil { + e := errno.FromMessage(errno.RouteRequestError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } else { + responseList := make([]service.RouteResponse, 0) + for _, r := range routeList { + response := &service.RouteResponse{} + response.Parse(&r) + responseList = append(responseList, *response) + } + result := &service.ListResponse{Count: count, Data: responseList} + resp, _ := json.Marshal(result) + c.Data(http.StatusOK, service.ContentType, resp) + } +} + +func deleteRoute(c *gin.Context) { + rid := c.Param("rid") + // todo params check + // delete from apisix + request := &service.ApisixRouteRequest{} + if _, err := request.Delete(rid); err != nil { + e := errno.FromMessage(errno.ApisixRouteDeleteError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusInternalServerError, e.Response()) + return + } else { + // delete from mysql + rd := &service.Route{} + rd.ID = uuid.FromStringOrNil(rid) + if err := conf.DB().Delete(rd).Error; err != nil { + e := errno.FromMessage(errno.DBRouteDeleteError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusInternalServerError, e.Response()) + return + } + } + c.Data(http.StatusOK, service.ContentType, errno.Success()) +} +func updateRoute(c *gin.Context) { + rid := c.Param("rid") + // todo params check + param, exist := c.Get("requestBody") + if !exist || len(param.([]byte)) < 1 { + e := errno.FromMessage(errno.RouteRequestError, "route create with no post data") + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } + routeRequest := &service.RouteRequest{} + if err := routeRequest.Parse(param); err != nil { + e := errno.FromMessage(errno.RouteRequestError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } + logger.Info(routeRequest.Plugins) + + arr := service.ToApisixRequest(routeRequest) + logger.Info(arr) + if resp, err := arr.Update(rid); err != nil { + e := errno.FromMessage(errno.ApisixRouteUpdateError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusInternalServerError, e.Response()) + return + } else { + // update mysql + if rd, err := service.ToRoute(routeRequest, arr, uuid.FromStringOrNil(rid), resp); err != nil { + c.AbortWithStatusJSON(http.StatusInternalServerError, err.Response()) + return + } else { + if err := conf.DB().Model(&service.Route{}).Update(rd).Error; err != nil { + e := errno.FromMessage(errno.DBRouteUpdateError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusInternalServerError, e.Response()) + return + } + logger.Info(rd) + } + } + c.Data(http.StatusOK, service.ContentType, errno.Success()) +} + +func findRoute(c *gin.Context) { + rid := c.Param("rid") + // todo params check + // find from apisix + request := &service.ApisixRouteRequest{} + if response, err := request.FindById(rid); err != nil { + e := errno.FromMessage(errno.RouteRequestError, err.Error()+" route ID: "+rid) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } else { + // transfer response to dashboard struct + if result, err := response.Parse(); err != nil { + e := errno.FromMessage(errno.RouteRequestError, err.Error()+" route ID: "+rid) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } else { + // need to find name from mysql temporary + route := &service.Route{} + if err := conf.DB().Table("routes").Where("id=?", rid).First(&route).Error; err != nil { + e := errno.FromMessage(errno.RouteRequestError, err.Error()+" route ID: "+rid) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } + result.Name = route.Name + resp, _ := json.Marshal(result) + c.Data(http.StatusOK, service.ContentType, resp) + } + } +} + +func createRoute(c *gin.Context) { + u4 := uuid.NewV4() + rid := u4.String() + // todo params check + param, exist := c.Get("requestBody") + if !exist || len(param.([]byte)) < 1 { + e := errno.FromMessage(errno.RouteRequestError, "route create with no post data") + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } + routeRequest := &service.RouteRequest{} + if err := routeRequest.Parse(param); err != nil { + e := errno.FromMessage(errno.RouteRequestError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } + logger.Info(routeRequest.Plugins) + + arr := service.ToApisixRequest(routeRequest) + logger.Info(arr) + if resp, err := arr.Create(rid); err != nil { + e := errno.FromMessage(errno.ApisixRouteCreateError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusInternalServerError, e.Response()) + return + } else { + // update mysql + if rd, err := service.ToRoute(routeRequest, arr, u4, resp); err != nil { + c.AbortWithStatusJSON(http.StatusInternalServerError, err.Response()) + return + } else { + logger.Info(rd) + if err := conf.DB().Create(rd).Error; err != nil { + e := errno.FromMessage(errno.DBRouteCreateError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusInternalServerError, e.Response()) + return + } + } + } + c.Data(http.StatusOK, service.ContentType, errno.Success()) +} diff --git a/api/route/ssl.go b/api/route/ssl.go new file mode 100644 index 0000000000..2a9d6f7a19 --- /dev/null +++ b/api/route/ssl.go @@ -0,0 +1,153 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package route + +import ( + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + "github.com/satori/go.uuid" + + "github.com/apisix/manager-api/errno" + "github.com/apisix/manager-api/service" +) + +const contentType = "application/json" + +func AppendSsl(r *gin.Engine) *gin.Engine { + r.POST("/apisix/admin/check_ssl_cert", sslCheck) + r.GET("/apisix/admin/ssls", sslList) + r.POST("/apisix/admin/ssls", sslCreate) + r.GET("/apisix/admin/ssls/:id", sslItem) + r.PUT("/apisix/admin/ssls/:id", sslUpdate) + r.DELETE("/apisix/admin/ssls/:id", sslDelete) + return r +} + +func sslList(c *gin.Context) { + size, _ := strconv.Atoi(c.DefaultQuery("size", "10")) + page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + // todo params check + resp, err := service.SslList(page, size) + + if err != nil { + e := errno.FromMessage(errno.RouteRequestError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } + + c.Data(http.StatusOK, service.ContentType, resp) +} + +func sslItem(c *gin.Context) { + id := c.Param("id") + + // todo params check + resp, err := service.SslItem(id) + + if err != nil { + e := errno.FromMessage(errno.RouteRequestError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } + + c.Data(http.StatusOK, service.ContentType, resp) +} + +func sslCheck(c *gin.Context) { + // todo params check + param, exist := c.Get("requestBody") + + if !exist || len(param.([]byte)) < 1 { + e := errno.FromMessage(errno.RouteRequestError, "route create with no post data") + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } + + resp, err := service.SslCheck(param) + if err != nil { + e := errno.FromMessage(errno.RouteRequestError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } + + c.Data(http.StatusOK, contentType, resp) +} + +func sslCreate(c *gin.Context) { + // todo params check + param, exist := c.Get("requestBody") + + u4 := uuid.NewV4() + + if !exist || len(param.([]byte)) < 1 { + e := errno.FromMessage(errno.RouteRequestError, "route create with no post data") + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } + + if err := service.SslCreate(param, u4.String()); err != nil { + e := errno.FromMessage(errno.ApisixRouteCreateError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusInternalServerError, e.Response()) + return + } + + c.Data(http.StatusOK, contentType, errno.Success()) +} + +func sslUpdate(c *gin.Context) { + // todo params check + param, exist := c.Get("requestBody") + + id := c.Param("id") + + if !exist || len(param.([]byte)) < 1 { + e := errno.FromMessage(errno.RouteRequestError, "route create with no post data") + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } + + if err := service.SslUpdate(param, id); err != nil { + e := errno.FromMessage(errno.ApisixRouteCreateError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusInternalServerError, e.Response()) + return + } + + c.Data(http.StatusOK, contentType, errno.Success()) +} + +func sslDelete(c *gin.Context) { + id := c.Param("id") + // todo params check + if err := service.SslDelete(id); err != nil { + e := errno.FromMessage(errno.RouteRequestError, err.Error()) + logger.Error(e.Msg) + c.AbortWithStatusJSON(http.StatusBadRequest, e.Response()) + return + } + + c.Data(http.StatusOK, service.ContentType, errno.Success()) +} diff --git a/api/script/db/schema.sql b/api/script/db/schema.sql new file mode 100644 index 0000000000..69f088cd93 --- /dev/null +++ b/api/script/db/schema.sql @@ -0,0 +1,31 @@ +-- this is a db script for init +CREATE DATABASE `manager`; +use `manager`; +CREATE TABLE `routes` ( + `id` varchar(64) NOT NULL unique, + `name` varchar(200) NOT NULL unique, -- not support yet + `description` varchar(200) DEFAULT NULL, + `hosts` text, + `uris` text, + `upstream_nodes` text, + `upstream_id` varchar(32) , -- fk + `priority` int NOT NULL DEFAULT 0, + `state` int NOT NULL DEFAULT 1, -- 1-normal 0-disable + `content` text, + `content_admin_api` text, + `create_time` bigint(20), + `update_time` bigint(20), + + PRIMARY KEY (`id`) +) DEFAULT CHARSET=utf8; +CREATE TABLE `ssls` ( + `id` char(36) NOT NULL DEFAULT '', + `public_key` text NOT NULL, + `snis` text NOT NULL, + `validity_start` bigint(20) unsigned NOT NULL, + `validity_end` bigint(20) unsigned NOT NULL, + `status` tinyint(1) unsigned NOT NULL DEFAULT '1', + `create_time` bigint(20) unsigned NOT NULL, + `update_time` bigint(20) unsigned NOT NULL, + PRIMARY KEY (`id`) +) DEFAULT CHARSET=utf8; \ No newline at end of file diff --git a/src/store/index.ts b/api/service/base.go similarity index 50% rename from src/store/index.ts rename to api/service/base.go index aa389a938d..6ee57b536e 100644 --- a/src/store/index.ts +++ b/api/service/base.go @@ -14,24 +14,35 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package service -import Vue from 'vue' -import Vuex from 'vuex' -import { IAppState } from './modules/app' -import { IUserState } from './modules/user' -import { ITagsViewState } from './modules/tags-view' -import { IPermissionState } from './modules/permission' -import { ISettingsState } from './modules/settings' +import ( + "github.com/jinzhu/gorm" + "github.com/satori/go.uuid" + "time" +) -Vue.use(Vuex) +// Base contains common columns for all tables. +type Base struct { + ID uuid.UUID `json:"id",sql:"type:uuid;primary_key;"` + CreateTime int64 `json:"create_time"` + UpdateTime int64 `json:"update_time"` +} -export interface IRootState { - app: IAppState - user: IUserState - tagsView: ITagsViewState - permission: IPermissionState - settings: ISettingsState +// BeforeCreate will set a UUID rather than numeric ID. +func (base *Base) BeforeCreate(scope *gorm.Scope) error { + timestamp := time.Now().Unix() + err := scope.SetColumn("UpdateTime", timestamp) + err = scope.SetColumn("CreateTime", timestamp) + if len(base.ID) == 0 { + uuid := uuid.NewV4() + err = scope.SetColumn("ID", uuid) + return err + } + return err } -// Declare empty store first, dynamically register all modules later. -export default new Vuex.Store({}) +func (base *Base) BeforeSave(scope *gorm.Scope) error { + err := scope.SetColumn("UpdateTime", time.Now().Unix()) + return err +} diff --git a/api/service/plugin.go b/api/service/plugin.go new file mode 100644 index 0000000000..92cd6c3d65 --- /dev/null +++ b/api/service/plugin.go @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package service + +import ( + "encoding/json" + "fmt" + "github.com/apisix/manager-api/conf" + "github.com/apisix/manager-api/utils" +) + +type ApisixPluginRequest struct { + Name string `json:"name"` +} + +func (apr *ApisixPluginRequest) Schema() (map[string]interface{}, error) { + url := fmt.Sprintf("%s/schema/plugins/%s", conf.BaseUrl, apr.Name) + if resp, err := utils.Get(url); err != nil { + logger.Error(err.Error()) + return nil, err + } else { + arresp := make(map[string]interface{}) + if err := json.Unmarshal(resp, &arresp); err != nil { + logger.Error(err.Error()) + return nil, err + } else { + return arresp, nil + } + } +} + +func (apr *ApisixPluginRequest) List() ([]string, error) { + + url := fmt.Sprintf("%s/plugins/list", conf.BaseUrl) + if resp, err := utils.Get(url); err != nil { + logger.Error(err.Error()) + return nil, err + } else { + var arresp []string + if err := json.Unmarshal(resp, &arresp); err != nil { + logger.Error(err.Error()) + return nil, err + } else { + return arresp, nil + } + } +} diff --git a/api/service/route.go b/api/service/route.go new file mode 100644 index 0000000000..dae72786b3 --- /dev/null +++ b/api/service/route.go @@ -0,0 +1,560 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package service + +import ( + "encoding/json" + "fmt" + "github.com/apisix/manager-api/conf" + "github.com/apisix/manager-api/errno" + "github.com/apisix/manager-api/log" + "github.com/apisix/manager-api/utils" + "github.com/satori/go.uuid" + "time" +) + +const ( + ContentType = "application/json" + HTTP = "http" + HTTPS = "https" + SCHEME = "scheme" + WEBSOCKET = "websocket" + REDIRECT = "redirect" + PROXY_REWRIETE = "proxy-rewrite" + UPATHTYPE_STATIC = "static" + UPATHTYPE_REGX = "regx" + UPATHTYPE_KEEP = "keep" +) + +var logger = log.GetLogger() + +func (r *RouteRequest) Parse(body interface{}) error { + if err := json.Unmarshal(body.([]byte), r); err != nil { + r = nil + return err + } else { + if r.Uris == nil || len(r.Uris) < 1 { + r.Uris = []string{"/*"} + } + } + return nil +} + +func (arr *ApisixRouteRequest) Parse(r *RouteRequest) { + arr.Desc = r.Desc + arr.Priority = r.Priority + arr.Methods = r.Methods + arr.Uris = r.Uris + arr.Hosts = r.Hosts + arr.Vars = r.Vars + arr.Upstream = r.Upstream + arr.Plugins = r.Plugins +} + +func (rd *Route) Parse(r *RouteRequest, arr *ApisixRouteRequest) error { + //rd.Name = arr.Name + rd.Description = arr.Desc + // todo transfer + rd.Hosts = "" + rd.Uris = "" + rd.UpstreamNodes = "" + rd.UpstreamId = "" + if content, err := json.Marshal(r); err != nil { + return err + } else { + rd.Content = string(content) + } + timestamp := time.Now().Unix() + rd.CreateTime = timestamp + return nil +} + +func (arr *ApisixRouteRequest) FindById(rid string) (*ApisixRouteResponse, error) { + url := fmt.Sprintf("%s/routes/%s", conf.BaseUrl, rid) + if resp, err := utils.Get(url); err != nil { + logger.Error(err.Error()) + return nil, err + } else { + var arresp ApisixRouteResponse + if err := json.Unmarshal(resp, &arresp); err != nil { + logger.Error(err.Error()) + return nil, err + } else { + return &arresp, nil + } + } +} + +func (arr *ApisixRouteRequest) Update(rid string) (*ApisixRouteResponse, error) { + url := fmt.Sprintf("%s/routes/%s", conf.BaseUrl, rid) + if b, err := json.Marshal(arr); err != nil { + return nil, err + } else { + if resp, err := utils.Patch(url, b); err != nil { + logger.Error(err.Error()) + return nil, err + } else { + var arresp ApisixRouteResponse + if err := json.Unmarshal(resp, &arresp); err != nil { + logger.Error(err.Error()) + return nil, err + } else { + return &arresp, nil + } + } + } +} + +func (arr *ApisixRouteRequest) Create(rid string) (*ApisixRouteResponse, error) { + url := fmt.Sprintf("%s/routes/%s", conf.BaseUrl, rid) + if b, err := json.Marshal(arr); err != nil { + return nil, err + } else { + fmt.Println(string(b)) + if resp, err := utils.Put(url, b); err != nil { + logger.Error(err.Error()) + return nil, err + } else { + var arresp ApisixRouteResponse + if err := json.Unmarshal(resp, &arresp); err != nil { + logger.Error(err.Error()) + return nil, err + } else { + return &arresp, nil + } + } + } +} + +func (arr *ApisixRouteRequest) Delete(rid string) (*ApisixRouteResponse, error) { + url := fmt.Sprintf("%s/routes/%s", conf.BaseUrl, rid) + if resp, err := utils.Delete(url); err != nil { + logger.Error(err.Error()) + return nil, err + } else { + var arresp ApisixRouteResponse + if err := json.Unmarshal(resp, &arresp); err != nil { + logger.Error(err.Error()) + return nil, err + } else { + return &arresp, nil + } + } +} + +type RouteRequest struct { + ID string `json:"id,omitempty"` + Name string `json:"name"` + Desc string `json:"desc,omitempty"` + Priority int64 `json:"priority,omitempty"` + Methods []string `json:"methods,omitempty"` + Uris []string `json:"uris"` + Hosts []string `json:"hosts,omitempty"` + Protocols []string `json:"protocols,omitempty"` + Redirect *Redirect `json:"redirect,omitempty"` + Vars [][]string `json:"vars,omitempty"` + Upstream *Upstream `json:"upstream,omitempty"` + UpstreamProtocol string `json:"upstream_protocol,omitempty"` + UpstreamPath *UpstreamPath `json:"upstream_path,omitempty"` + UpstreamHeader map[string]string `json:"upstream_header,omitempty"` + Plugins map[string]interface{} `json:"plugins"` +} + +func (r *ApisixRouteResponse) Parse() (*RouteRequest, error) { + o := r.Node.Value + + //Protocols from vars and upstream + protocols := make([]string, 0) + if o.Upstream != nil && o.Upstream.EnableWebsocket { + protocols = append(protocols, WEBSOCKET) + } + flag := true + for _, t := range o.Vars { + if t[0] == SCHEME { + flag = false + protocols = append(protocols, t[2]) + } + } + if flag { + protocols = append(protocols, HTTP) + protocols = append(protocols, HTTPS) + } + //Redirect from plugins + redirect := &Redirect{} + upstreamProtocol := UPATHTYPE_KEEP + upstreamHeader := make(map[string]string) + upstreamPath := &UpstreamPath{} + for k, v := range o.Plugins { + if k == REDIRECT { + if bytes, err := json.Marshal(v); err != nil { + return nil, err + } else { + if err := json.Unmarshal(bytes, redirect); err != nil { + return nil, err + } + } + + } + if k == PROXY_REWRIETE { + pr := &ProxyRewrite{} + if bytes, err := json.Marshal(v); err != nil { + return nil, err + } else { + if err := json.Unmarshal(bytes, pr); err != nil { + return nil, err + } else { + if pr.Scheme != "" { + upstreamProtocol = pr.Scheme + } + upstreamHeader = pr.Headers + if pr.RegexUri == nil || len(pr.RegexUri) < 2 { + upstreamPath.UPathType = UPATHTYPE_STATIC + upstreamPath.To = pr.Uri + } else { + upstreamPath.UPathType = UPATHTYPE_REGX + upstreamPath.From = pr.RegexUri[0] + upstreamPath.To = pr.RegexUri[1] + } + } + } + } + } + //Vars + requestVars := make([][]string, 0) + for _, t := range o.Vars { + if t[0] != SCHEME { + requestVars = append(requestVars, t) + } + } + //Plugins + requestPlugins := utils.CopyMap(o.Plugins) + delete(requestPlugins, REDIRECT) + + // check if upstream is not exist + if o.Upstream == nil { + upstreamProtocol = "" + upstreamHeader = nil + upstreamPath = nil + } + if upstreamPath.UPathType == "" { + upstreamPath = nil + } + result := &RouteRequest{ + ID: o.Id, + Desc: o.Desc, + Priority: o.Priority, + Methods: o.Methods, + Uris: o.Uris, + Hosts: o.Hosts, + Redirect: redirect, + Upstream: o.Upstream, + UpstreamProtocol: upstreamProtocol, + UpstreamPath: upstreamPath, + UpstreamHeader: upstreamHeader, + Protocols: protocols, + Vars: requestVars, + Plugins: requestPlugins, + } + return result, nil +} + +type Redirect struct { + HttpToHttps bool `json:"http_to_https,omitempty"` + Code int64 `json:"code,omitempty"` + Uri string `json:"uri,omitempty"` +} + +type ProxyRewrite struct { + Uri string `json:"uri"` + RegexUri []string `json:"regex_uri"` + Scheme string `json:"scheme"` + Host string `json:"host"` + Headers map[string]string `json:"headers"` +} + +func (r ProxyRewrite) MarshalJSON() ([]byte, error) { + m := make(map[string]interface{}) + if r.RegexUri != nil { + m["regex_uri"] = r.RegexUri + } + if r.Uri != "" { + m["uri"] = r.Uri + } + if r.Scheme != UPATHTYPE_KEEP && r.Scheme != "" { + m["scheme"] = r.Scheme + } + if r.Host != "" { + m["host"] = r.Host + } + if r.Headers != nil && len(r.Headers) > 0 { + m["headers"] = r.Headers + } + if result, err := json.Marshal(m); err != nil { + return nil, err + } else { + return result, nil + } +} + +func (r Redirect) MarshalJSON() ([]byte, error) { + m := make(map[string]interface{}) + if r.HttpToHttps { + m["http_to_https"] = true + } else { + m["code"] = r.Code + m["uri"] = r.Uri + } + if result, err := json.Marshal(m); err != nil { + return nil, err + } else { + return result, nil + } +} + +type Upstream struct { + UType string `json:"type"` + Nodes map[string]int64 `json:"nodes"` + Timeout UpstreamTimeout `json:"timeout"` + EnableWebsocket bool `json:"enable_websocket"` +} + +type UpstreamTimeout struct { + Connect int64 `json:"connect"` + Send int64 `json:"send"` + Read int64 `json:"read"` +} + +type UpstreamPath struct { + UPathType string `json:"type"` + From string `json:"from"` + To string `json:"to"` +} + +type ApisixRouteRequest struct { + Desc string `json:"desc,omitempty"` + Priority int64 `json:"priority"` + Methods []string `json:"methods,omitempty"` + Uris []string `json:"uris,omitempty"` + Hosts []string `json:"hosts,omitempty"` + Vars [][]string `json:"vars,omitempty"` + Upstream *Upstream `json:"upstream,omitempty"` + Plugins map[string]interface{} `json:"plugins,omitempty"` + //Name string `json:"name"` +} + +// ApisixRouteResponse is response from apisix admin api +type ApisixRouteResponse struct { + Action string `json:"action"` + Node *Node `json:"node"` +} + +type Node struct { + Value Value `json:"value"` + ModifiedIndex uint64 `json:"modifiedIndex"` +} + +type Value struct { + Id string `json:"id"` + Name string `json:"name"` + Desc string `json:"desc,omitempty"` + Priority int64 `json:"priority"` + Methods []string `json:"methods"` + Uris []string `json:"uris"` + Hosts []string `json:"hosts"` + Vars [][]string `json:"vars"` + Upstream *Upstream `json:"upstream,omitempty"` + UpstreamId string `json:"upstream_id,omitempty"` + Plugins map[string]interface{} `json:"plugins"` +} + +type Route struct { + Base + Name string `json:"name"` + Description string `json:"description,omitempty"` + Hosts string `json:"hosts"` + Uris string `json:"uris"` + UpstreamNodes string `json:"upstream_nodes"` + UpstreamId string `json:"upstream_id"` + Priority int64 `json:"priority"` + Content string `json:"content"` + ContentAdminApi string `json:"content_admin_api"` +} + +type RouteResponse struct { + Base + Name string `json:"name"` + Description string `json:"description,omitempty"` + Hosts []string `json:"hosts,omitempty"` + Uris []string `json:"uris,omitempty"` + Upstream *Upstream `json:"upstream,omitempty"` + UpstreamId string `json:"upstream_id,omitempty"` + Priority int64 `json:"priority"` +} + +type ListResponse struct { + Count int `json:"count"` + Data interface{} `json:"data"` +} + +func (rr *RouteResponse) Parse(r *Route) { + rr.Base = r.Base + rr.Name = r.Name + rr.Description = r.Description + rr.UpstreamId = r.UpstreamId + rr.Priority = r.Priority + // hosts + if len(r.Hosts) > 0 { + var hosts []string + if err := json.Unmarshal([]byte(r.Hosts), &hosts); err == nil { + rr.Hosts = hosts + } else { + logger.Error(err.Error()) + } + } + + // uris + if len(r.Uris) > 0 { + var uris []string + if err := json.Unmarshal([]byte(r.Uris), &uris); err == nil { + rr.Uris = uris + } + } + + // uris + var resp ApisixRouteResponse + if err := json.Unmarshal([]byte(r.ContentAdminApi), &resp); err == nil { + rr.Upstream = resp.Node.Value.Upstream + } +} + +// RouteRequest -> ApisixRouteRequest +func ToApisixRequest(routeRequest *RouteRequest) *ApisixRouteRequest { + // redirect -> plugins + plugins := utils.CopyMap(routeRequest.Plugins) + redirect := routeRequest.Redirect + if redirect != nil { + plugins["redirect"] = redirect + } + + logger.Info(routeRequest.Plugins) + + // scheme https and not http -> vars ['scheme', '==', 'https'] + pMap := utils.Set2Map(routeRequest.Protocols) + + arr := &ApisixRouteRequest{} + arr.Parse(routeRequest) + + // protocols[websokect] -> upstream + if pMap[WEBSOCKET] == 1 && arr.Upstream != nil { + arr.Upstream.EnableWebsocket = true + } + vars := utils.CopyStrings(routeRequest.Vars) + if pMap[HTTP] != 1 || pMap[HTTPS] != 1 { + if pMap[HTTP] == 1 { + vars = append(vars, []string{SCHEME, "==", HTTP}) + } + if pMap[HTTPS] == 1 { + vars = append(vars, []string{SCHEME, "==", HTTPS}) + } + } + if len(vars) > 0 { + arr.Vars = vars + } else { + arr.Vars = nil + } + + // upstream protocol + if arr.Upstream != nil { + pr := &ProxyRewrite{} + pr.Scheme = routeRequest.UpstreamProtocol + // upstream path + proxyPath := routeRequest.UpstreamPath + if proxyPath != nil { + if proxyPath.UPathType == UPATHTYPE_STATIC { + pr.Uri = proxyPath.To + pr.RegexUri = nil + } else { + pr.RegexUri = []string{proxyPath.From, proxyPath.To} + } + } + // upstream headers + pr.Headers = routeRequest.UpstreamHeader + if proxyPath != nil { + plugins[PROXY_REWRIETE] = pr + } + } + + if plugins != nil && len(plugins) > 0 { + arr.Plugins = plugins + } else { + arr.Plugins = nil + } + return arr +} + +func ToRoute(routeRequest *RouteRequest, + arr *ApisixRouteRequest, + u4 uuid.UUID, + resp *ApisixRouteResponse) (*Route, *errno.ManagerError) { + rd := &Route{} + if err := rd.Parse(routeRequest, arr); err != nil { + e := errno.FromMessage(errno.DBRouteCreateError, err.Error()) + return nil, e + } + if rd.Name == "" { + rd.Name = routeRequest.Name + } + rd.ID = u4 + // content_admin_api + if respStr, err := json.Marshal(resp); err != nil { + e := errno.FromMessage(errno.DBRouteCreateError, err.Error()) + return nil, e + } else { + rd.ContentAdminApi = string(respStr) + } + // hosts + hosts := resp.Node.Value.Hosts + if hb, err := json.Marshal(hosts); err != nil { + e := errno.FromMessage(errno.DBRouteCreateError, err.Error()) + logger.Warn(e.Msg) + } else { + rd.Hosts = string(hb) + } + // uris + uris := resp.Node.Value.Uris + if ub, err := json.Marshal(uris); err != nil { + e := errno.FromMessage(errno.DBRouteCreateError, err.Error()) + logger.Warn(e.Msg) + } else { + rd.Uris = string(ub) + } + // upstreamNodes + if resp.Node.Value.Upstream != nil { + nodes := resp.Node.Value.Upstream.Nodes + ips := make([]string, 0) + for k, _ := range nodes { + ips = append(ips, k) + } + if nb, err := json.Marshal(ips); err != nil { + e := errno.FromMessage(errno.DBRouteCreateError, err.Error()) + logger.Warn(e.Msg) + } else { + rd.UpstreamNodes = string(nb) + } + } + return rd, nil +} diff --git a/api/service/route_test.go b/api/service/route_test.go new file mode 100644 index 0000000000..82652ce0d2 --- /dev/null +++ b/api/service/route_test.go @@ -0,0 +1,139 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package service + +import ( + "encoding/json" + "github.com/stretchr/testify/assert" + "testing" +) + +func TestRedirectMarshal(t *testing.T) { + a := assert.New(t) + r := &Redirect{ + HttpToHttps: true, + Code: 302, + Uri: "/hello", + } + if result, err := json.Marshal(r); err != nil { + t.Error(err.Error()) + } else { + h := make(map[string]interface{}) + json.Unmarshal(result, &h) + a.Equal(1, len(h)) + a.Equal(nil, h["code"]) + a.Equal(true, h["http_to_https"]) + } +} + +func TestToApisixRequest_RediretPlugins(t *testing.T) { + rr := &RouteRequest{ + ID: "u guess a uuid", + Name: "a special name", + Desc: "any description", + Priority: 0, + Methods: []string{"GET"}, + Uris: []string{}, + Hosts: []string{"www.baidu.com"}, + Protocols: []string{"http", "https", "websocket"}, + Redirect: &Redirect{HttpToHttps: true, Code: 200, Uri: "/hello"}, + Vars: [][]string{}, + } + ar := ToApisixRequest(rr) + a := assert.New(t) + a.Equal(1, len(ar.Plugins)) + a.NotEqual(nil, ar.Plugins["redirect"]) +} + +func TestToApisixRequest_Vars(t *testing.T) { + rr := &RouteRequest{ + ID: "u guess a uuid", + Name: "a special name", + Desc: "any description", + Priority: 0, + Methods: []string{"GET"}, + Uris: []string{}, + Hosts: []string{"www.baidu.com"}, + Protocols: []string{"http", "https", "websocket"}, + Redirect: &Redirect{HttpToHttps: true, Code: 200, Uri: "/hello"}, + Vars: [][]string{}, + } + ar := ToApisixRequest(rr) + a := assert.New(t) + b, err := json.Marshal(ar) + a.Equal(nil, err) + + m := make(map[string]interface{}) + err = json.Unmarshal(b, &m) + a.Equal(nil, err) + t.Log(m["vars"]) + a.Equal(nil, m["vars"]) +} + +func TestToApisixRequest_Upstream(t *testing.T) { + nodes := make(map[string]int64) + nodes["127.0.0.1:8080"] = 100 + upstream := &Upstream{ + UType: "roundrobin", + Nodes: nodes, + Timeout: UpstreamTimeout{15, 15, 15}, + } + rr := &RouteRequest{ + ID: "u guess a uuid", + Name: "a special name", + Desc: "any description", + Priority: 0, + Methods: []string{"GET"}, + Uris: []string{}, + Hosts: []string{"www.baidu.com"}, + Protocols: []string{"http", "https", "websocket"}, + Redirect: &Redirect{HttpToHttps: true, Code: 200, Uri: "/hello"}, + Vars: [][]string{}, + Upstream: upstream, + } + ar := ToApisixRequest(rr) + a := assert.New(t) + a.Equal("roundrobin", ar.Upstream.UType) + a.Equal(true, ar.Upstream.EnableWebsocket) +} + +func TestToApisixRequest_UpstreamUnable(t *testing.T) { + nodes := make(map[string]int64) + nodes["127.0.0.1:8080"] = 100 + upstream := &Upstream{ + UType: "roundrobin", + Nodes: nodes, + Timeout: UpstreamTimeout{15, 15, 15}, + } + rr := &RouteRequest{ + ID: "u guess a uuid", + Name: "a special name", + Desc: "any description", + Priority: 0, + Methods: []string{"GET"}, + Uris: []string{}, + Hosts: []string{"www.baidu.com"}, + Protocols: []string{"http", "https"}, + Redirect: &Redirect{HttpToHttps: true, Code: 200, Uri: "/hello"}, + Vars: [][]string{}, + Upstream: upstream, + } + ar := ToApisixRequest(rr) + a := assert.New(t) + a.Equal("roundrobin", ar.Upstream.UType) + a.Equal(false, ar.Upstream.EnableWebsocket) +} diff --git a/api/service/ssl.go b/api/service/ssl.go new file mode 100644 index 0000000000..839e3b8abe --- /dev/null +++ b/api/service/ssl.go @@ -0,0 +1,300 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package service + +import ( + "crypto/tls" + "crypto/x509" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + + "github.com/satori/go.uuid" + + "github.com/apisix/manager-api/conf" + "github.com/apisix/manager-api/errno" + "github.com/apisix/manager-api/utils" +) + +type Ssl struct { + Base + ValidityStart uint64 `json:"validity_start"` + ValidityEnd uint64 `json:"validity_end"` + Snis string `json:"snis"` + Status uint64 `json:"status"` + PublicKey string `json:"public_key,omitempty"` +} + +type SslDto struct { + Base + ValidityStart uint64 `json:"validity_start"` + ValidityEnd uint64 `json:"validity_end"` + Snis []string `json:"snis"` + Status uint64 `json:"status"` + PublicKey string `json:"public_key,omitempty"` +} + +type SslRequest struct { + ID string `json:"id,omitempty"` + PublicKey string `json:"cert"` + PrivateKey string `json:"key"` + Snis []string `json:"snis"` +} + +// ApisixSslResponse is response from apisix admin api +type ApisixSslResponse struct { + Action string `json:"action"` + Node *SslNode `json:"node"` +} + +type SslNode struct { + Value SslRequest `json:"value"` + ModifiedIndex uint64 `json:"modifiedIndex"` +} + +func (req *SslRequest) Parse(body interface{}) { + if err := json.Unmarshal(body.([]byte), req); err != nil { + req = nil + logger.Error(errno.FromMessage(errno.RouteRequestError, err.Error()).Msg) + } +} + +func (sslDto *SslDto) Parse(ssl *Ssl) error { + sslDto.ID = ssl.ID + sslDto.ValidityStart = ssl.ValidityStart + sslDto.ValidityEnd = ssl.ValidityEnd + + var snis []string + _ = json.Unmarshal([]byte(ssl.Snis), &snis) + sslDto.Snis = snis + + sslDto.Status = ssl.Status + sslDto.PublicKey = ssl.PublicKey + sslDto.CreateTime = ssl.CreateTime + sslDto.UpdateTime = ssl.UpdateTime + + return nil +} + +func SslList(page, size int) ([]byte, error) { + var count int + sslList := []Ssl{} + if err := conf.DB().Table("ssls").Offset((page - 1) * size).Limit(size).Find(&sslList).Count(&count).Error; err != nil { + return nil, err + } + + sslDtoList := []SslDto{} + + for _, ssl := range sslList { + sslDto := SslDto{} + sslDto.Parse(&ssl) + + sslDtoList = append(sslDtoList, sslDto) + } + + data := errno.FromMessage(errno.SystemSuccess).ListResponse(count, sslDtoList) + + return json.Marshal(data) +} + +func SslItem(id string) ([]byte, error) { + ssl := &Ssl{} + if err := conf.DB().Table("ssls").Where("id = ?", id).First(ssl).Error; err != nil { + return nil, err + } + + sslDto := &SslDto{} + sslDto.Parse(ssl) + + data := errno.FromMessage(errno.SystemSuccess).ItemResponse(sslDto) + + return json.Marshal(data) +} + +func SslCheck(param interface{}) ([]byte, error) { + sslReq := &SslRequest{} + sslReq.Parse(param) + + ssl, err := ParseCert(sslReq.PublicKey, sslReq.PrivateKey) + + if err != nil { + return nil, err + } + + ssl.PublicKey = "" + + sslDto := &SslDto{} + sslDto.Parse(ssl) + + data := errno.FromMessage(errno.SystemSuccess).ItemResponse(sslDto) + + return json.Marshal(data) +} + +func SslCreate(param interface{}, id string) error { + sslReq := &SslRequest{} + sslReq.Parse(param) + + ssl, err := ParseCert(sslReq.PublicKey, sslReq.PrivateKey) + + if err != nil { + return err + } + + // first admin api + var snis []string + _ = json.Unmarshal([]byte(ssl.Snis), &snis) + sslReq.Snis = snis + + if _, err := sslReq.PutToApisix(id); err != nil { + return err + } + // then mysql + ssl.ID = uuid.FromStringOrNil(id) + if err := conf.DB().Create(ssl).Error; err != nil { + return err + } + + return nil +} + +func SslUpdate(param interface{}, id string) error { + sslReq := &SslRequest{} + sslReq.Parse(param) + + ssl, err := ParseCert(sslReq.PublicKey, sslReq.PrivateKey) + + if err != nil { + return err + } + + // first admin api + var snis []string + _ = json.Unmarshal([]byte(ssl.Snis), &snis) + sslReq.Snis = snis + + if _, err := sslReq.PutToApisix(id); err != nil { + return err + } + + // then mysql + ssl.ID = uuid.FromStringOrNil(id) + data := Ssl{PublicKey: ssl.PublicKey, Snis: ssl.Snis, ValidityStart: ssl.ValidityStart, ValidityEnd: ssl.ValidityEnd} + if err := conf.DB().Model(&ssl).Updates(data).Error; err != nil { + return err + } + + return nil +} + +func SslDelete(id string) error { + // delete from apisix + request := &SslRequest{} + request.ID = id + if _, err := request.DeleteFromApisix(); err != nil { + return err + } + // delete from mysql + ssl := &Ssl{} + ssl.ID = uuid.FromStringOrNil(id) + if err := conf.DB().Delete(ssl).Error; err != nil { + return err + } + + return nil +} + +func (req *SslRequest) PutToApisix(rid string) (*ApisixSslResponse, error) { + url := fmt.Sprintf("%s/ssl/%s", conf.BaseUrl, rid) + if data, err := json.Marshal(req); err != nil { + return nil, err + } else { + if resp, err := utils.Put(url, data); err != nil { + logger.Error(url) + logger.Error(string(data)) + logger.Error(err.Error()) + return nil, err + } else { + var arresp ApisixSslResponse + if err := json.Unmarshal(resp, &arresp); err != nil { + logger.Error(err.Error()) + return nil, err + } else { + return &arresp, nil + } + } + } +} + +func (req *SslRequest) DeleteFromApisix() (*ApisixSslResponse, error) { + id := req.ID + url := fmt.Sprintf("%s/ssl/%s", conf.BaseUrl, id) + + if resp, err := utils.Delete(url); err != nil { + logger.Error(err.Error()) + return nil, err + } else { + var arresp ApisixSslResponse + if err := json.Unmarshal(resp, &arresp); err != nil { + logger.Error(err.Error()) + return nil, err + } else { + return &arresp, nil + } + } +} + +func ParseCert(crt, key string) (*Ssl, error) { + // print private key + certDERBlock, _ := pem.Decode([]byte(crt)) + if certDERBlock == nil { + return nil, errors.New("Certificate resolution failed") + } + // match + _, err := tls.X509KeyPair([]byte(crt), []byte(key)) + if err != nil { + return nil, err + } + + x509Cert, err := x509.ParseCertificate(certDERBlock.Bytes) + + if err != nil { + return nil, errors.New("Certificate resolution failed") + } else { + ssl := Ssl{} + + //domain + snis := []byte{} + if x509Cert.DNSNames == nil || len(x509Cert.DNSNames) < 1 { + tmp := []string{} + if x509Cert.Subject.CommonName != "" { + tmp = []string{x509Cert.Subject.CommonName} + } + snis, _ = json.Marshal(tmp) + } else { + snis, _ = json.Marshal(x509Cert.DNSNames) + } + ssl.Snis = string(snis) + + ssl.ValidityStart = uint64(x509Cert.NotBefore.Unix()) + ssl.ValidityEnd = uint64(x509Cert.NotAfter.Unix()) + ssl.PublicKey = crt + + return &ssl, nil + } +} diff --git a/postcss.config.js b/api/utils/copy.go similarity index 62% rename from postcss.config.js rename to api/utils/copy.go index a5e9c1db50..30f228a27b 100644 --- a/postcss.config.js +++ b/api/utils/copy.go @@ -14,9 +14,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package utils -module.exports = { - plugins: { - autoprefixer: {} - } +func CopyMap(origin map[string]interface{}) map[string]interface{} { + result := make(map[string]interface{}) + for k, v := range origin { + result[k] = v + } + return result +} + +func CopyStrings(origin [][]string) [][]string { + result := make([][]string, 0) + for _, s := range origin { + result = append(result, s) + } + return result +} + +func Set2Map(origin []string) map[string]int { + result := make(map[string]int) + for _, s := range origin { + result[s] = 1 + } + return result } diff --git a/api/utils/http.go b/api/utils/http.go new file mode 100644 index 0000000000..119cf0be9e --- /dev/null +++ b/api/utils/http.go @@ -0,0 +1,113 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package utils + +import ( + "fmt" + "github.com/apisix/manager-api/conf" + "github.com/apisix/manager-api/log" + "gopkg.in/resty.v1" + "net/http" + "time" +) + +const timeout = 3000 + +var logger = log.GetLogger() + +func Get(url string) ([]byte, error) { + r := resty.New(). + SetTimeout(time.Duration(timeout)*time.Millisecond). + R(). + SetHeader("content-type", "application/json"). + SetHeader("X-API-KEY", conf.ApiKey) + resp, err := r.Get(url) + if err != nil { + return nil, err + } + if resp.StatusCode() != http.StatusOK { + return nil, fmt.Errorf("status: %d, body: %s", resp.StatusCode(), resp.Body()) + } + return resp.Body(), nil +} + +func Post(url string, bytes []byte) ([]byte, error) { + r := resty.New(). + SetTimeout(time.Duration(timeout)*time.Millisecond). + R(). + SetHeader("content-type", "application/json"). + SetHeader("X-API-KEY", conf.ApiKey) + r.SetBody(bytes) + resp, err := r.Post(url) + if err != nil { + return nil, err + } + if resp.StatusCode() != http.StatusOK && resp.StatusCode() != http.StatusCreated { + return nil, fmt.Errorf("status: %d, body: %s", resp.StatusCode(), resp.Body()) + } + return resp.Body(), nil +} + +func Put(url string, bytes []byte) ([]byte, error) { + r := resty.New(). + SetTimeout(time.Duration(timeout)*time.Millisecond). + R(). + SetHeader("content-type", "application/json"). + SetHeader("X-API-KEY", conf.ApiKey) + r.SetBody(bytes) + resp, err := r.Put(url) + if err != nil { + return nil, err + } + if resp.StatusCode() != http.StatusOK && resp.StatusCode() != http.StatusCreated { + return nil, fmt.Errorf("status: %d, body: %s", resp.StatusCode(), resp.Body()) + } + return resp.Body(), nil +} + +func Patch(url string, bytes []byte) ([]byte, error) { + r := resty.New(). + SetTimeout(time.Duration(timeout)*time.Millisecond). + R(). + SetHeader("content-type", "application/json"). + SetHeader("X-API-KEY", conf.ApiKey) + r.SetBody(bytes) + resp, err := r.Patch(url) + if err != nil { + return nil, err + } + if resp.StatusCode() != http.StatusOK { + return nil, fmt.Errorf("status: %d, body: %s", resp.StatusCode(), resp.Body()) + } + return resp.Body(), nil +} + +func Delete(url string) ([]byte, error) { + r := resty.New(). + SetTimeout(time.Duration(timeout)*time.Millisecond). + R(). + SetHeader("content-type", "application/json"). + SetHeader("X-API-KEY", conf.ApiKey) + resp, err := r.Delete(url) + if err != nil { + return nil, err + } + if resp.StatusCode() != http.StatusOK { + return nil, fmt.Errorf("status: %d, body: %s", resp.StatusCode(), resp.Body()) + } + return resp.Body(), nil +} diff --git a/compose/README.md b/compose/README.md new file mode 100644 index 0000000000..7d7c7ce30b --- /dev/null +++ b/compose/README.md @@ -0,0 +1,56 @@ +## Deploy + +```sh +$ cd incubator-apisix-dashboard/compose + +$ chmod +x ./manager_conf/build.sh + +$ docker-compose -p dashboard up -d +``` + +## Usage + +### 1. login dashboard + +Visit `http://127.0.0.1/dashboard/` in the browser, +Enter `http://127.0.0.1:8080/apisix/admin` into the first input box, this is the backend management service address + +![login](pics/login.png) + +now, click `save`. + +### 2. If you want to display the grafana metric dashboard, please fill in the grafana shared link as follows + +1.get grafana shared link + +Visit `http://127.0.0.1:3000/?search=open&orgId=1` + +![login](pics/grafana_1.png) + +click `Apache APISIX` dashboard, and you can see the page as follow + +![login](pics/grafana_2.png) + +click the button `shard dashboard` on the right of `Apache APISIX` + +![login](pics/grafana_3.png) + +copy the link, and then return to dashboard on the step 1 + +![login](pics/grafana_4.png) + +click metric on the left, and then the config button + +Paste shared link + +![login](pics/grafana_5.png) + +save, and you can see the metrics + +![login](pics/grafana_6.png) + + + + + + diff --git a/compose/apisix_conf/config.yaml b/compose/apisix_conf/config.yaml new file mode 100644 index 0000000000..bbdc65b95d --- /dev/null +++ b/compose/apisix_conf/config.yaml @@ -0,0 +1,137 @@ +apisix: + node_listen: 9080 # APISIX listening port + enable_heartbeat: true + enable_admin: true + enable_admin_cors: true # Admin API support CORS response headers. + enable_debug: false + enable_dev_mode: false # Sets nginx worker_processes to 1 if set to true + enable_reuseport: true # Enable nginx SO_REUSEPORT switch if set to true. + enable_ipv6: true + config_center: etcd # etcd: use etcd to store the config value + # yaml: fetch the config value from local yaml file `/your_path/conf/apisix.yaml` + + #proxy_protocol: # Proxy Protocol configuration + # listen_http_port: 9181 # The port with proxy protocol for http, it differs from node_listen and port_admin. + # This port can only receive http request with proxy protocol, but node_listen & port_admin + # can only receive http request. If you enable proxy protocol, you must use this port to + # receive http request with proxy protocol + # listen_https_port: 9182 # The port with proxy protocol for https + # enable_tcp_pp: true # Enable the proxy protocol for tcp proxy, it works for stream_proxy.tcp option + # enable_tcp_pp_to_upstream: true # Enables the proxy protocol to the upstream server + + proxy_cache: # Proxy Caching configuration + cache_ttl: 10s # The default caching time if the upstream does not specify the cache time + zones: # The parameters of a cache + - name: disk_cache_one # The name of the cache, administrator can be specify + # which cache to use by name in the admin api + memory_size: 50m # The size of shared memory, it's used to store the cache index + disk_size: 1G # The size of disk, it's used to store the cache data + disk_path: "/tmp/disk_cache_one" # The path to store the cache data + cache_levels: "1:2" # The hierarchy levels of a cache + # - name: disk_cache_two + # memory_size: 50m + # disk_size: 1G + # disk_path: "/tmp/disk_cache_two" + # cache_levels: "1:2" + +# allow_admin: # http://nginx.org/en/docs/http/ngx_http_access_module.html#allow +# - 127.0.0.0/24 # If we don't set any IP list, then any IP access is allowed by default. +# - 172.17.0.0/24 + # - "::/64" + # port_admin: 9180 # use a separate port + + # Default token when use API to call for Admin API. + # *NOTE*: Highly recommended to modify this value to protect APISIX's Admin API. + # Disabling this configuration item means that the Admin API does not + # require any authentication. + admin_key: + - + name: "admin" + key: edd1c9f034335f136f87ad84b625c8f1 + role: admin # admin: manage all configuration data + # viewer: only can view configuration data + - + name: "viewer" + key: 4054f7cf07e344346cd3f287985e76a2 + role: viewer + router: + http: 'radixtree_uri' # radixtree_uri: match route by uri(base on radixtree) + # radixtree_host_uri: match route by host + uri(base on radixtree) + ssl: 'radixtree_sni' # radixtree_sni: match route by SNI(base on radixtree) + # stream_proxy: # TCP/UDP proxy + # tcp: # TCP proxy port list + # - 9100 + # - 9101 + # udp: # UDP proxy port list + # - 9200 + # - 9211 + dns_resolver: # default DNS resolver, with disable IPv6 and enable local DNS + - 127.0.0.11 + - 114.114.114.114 + - 223.5.5.5 + - 1.1.1.1 + - 8.8.8.8 + dns_resolver_valid: 30 # valid time for dns result 30 seconds + resolver_timeout: 5 # resolver timeout + ssl: + enable: true + enable_http2: true + listen_port: 9443 + ssl_protocols: "TLSv1 TLSv1.1 TLSv1.2 TLSv1.3" + ssl_ciphers: "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA" + +nginx_config: # config for render the template to genarate nginx.conf + error_log: "logs/error.log" + error_log_level: "warn" # warn,error + worker_rlimit_nofile: 20480 # the number of files a worker process can open, should be larger than worker_connections + event: + worker_connections: 10620 + http: + access_log: "logs/access.log" + keepalive_timeout: 60s # timeout during which a keep-alive client connection will stay open on the server side. + client_header_timeout: 60s # timeout for reading client request header, then 408 (Request Time-out) error is returned to the client + client_body_timeout: 60s # timeout for reading client request body, then 408 (Request Time-out) error is returned to the client + send_timeout: 10s # timeout for transmitting a response to the client.then the connection is closed + underscores_in_headers: "on" # default enables the use of underscores in client request header fields + real_ip_header: "X-Real-IP" # http://nginx.org/en/docs/http/ngx_http_realip_module.html#real_ip_header + real_ip_from: # http://nginx.org/en/docs/http/ngx_http_realip_module.html#set_real_ip_from + - 127.0.0.1 + - 'unix:' + #lua_shared_dicts: # add custom shared cache to nginx.conf + # ipc_shared_dict: 100m # custom shared cache, format: `cache-key: cache-size` + +etcd: + host: # it's possible to define multiple etcd hosts addresses of the same etcd cluster. + - "http://192.17.5.10:2379" # multiple etcd address + prefix: "/apisix" # apisix configurations prefix + timeout: 3 # 3 seconds + +plugins: # plugin list + - example-plugin + - limit-req + - limit-count + - limit-conn + - key-auth + - basic-auth + - prometheus + - node-status + - jwt-auth + - zipkin + - ip-restriction + - grpc-transcode + - serverless-pre-function + - serverless-post-function + - openid-connect + - proxy-rewrite + - redirect + - response-rewrite + - fault-injection + - udp-logger + - wolf-rbac + - proxy-cache + - tcp-logger + - proxy-mirror + - kafka-logger + - cors +stream_plugins: + - mqtt-proxy diff --git a/compose/docker-compose.yml b/compose/docker-compose.yml new file mode 100644 index 0000000000..859e390acf --- /dev/null +++ b/compose/docker-compose.yml @@ -0,0 +1,124 @@ +version: "3" + +services: + apisix: + image: apache/apisix:latest + restart: always + volumes: + - ./apisix_log:/usr/local/apisix/logs + - ./apisix_conf/config.yaml:/usr/local/apisix/conf/config.yaml:ro + depends_on: + - etcd + ##network_mode: host + ports: + - "9080:9080/tcp" + - "9443:9443/tcp" + networks: + apisix-dashboard: + ipv4_address: 192.17.5.11 + + etcd: + image: gcr.io/etcd-development/etcd:v3.3.12 + command: /usr/local/bin/etcd --advertise-client-urls http://0.0.0.0:2379 --listen-client-urls http://0.0.0.0:2379 + restart: always + volumes: + - ./etcd_data:/etcd_data + environment: + ETCD_DATA_DIR: /etcd_data + ports: + - "2379:2379/tcp" + networks: + apisix-dashboard: + ipv4_address: 192.17.5.10 + + web1: + image: ruby:2-alpine + command: sh -c "mkdir -p /tmp/www && echo 'web1' > /tmp/www/web1.txt && ruby -run -ehttpd /tmp/www -p8000" + restart: always + ports: + - "9081:8000/tcp" + networks: + apisix-dashboard: + ipv4_address: 192.17.5.12 + + web2: + image: ruby:2-alpine + command: sh -c "mkdir -p /tmp/www && echo 'web2' > /tmp/www/web2.txt && ruby -run -ehttpd /tmp/www -p8000" + restart: always + ports: + - "9082:8000/tcp" + networks: + apisix-dashboard: + ipv4_address: 192.17.5.13 + + mysql: + image: mysql:latest + restart: always + ports: + - "3309:3306/tcp" + environment: + - MYSQL_ROOT_PASSWORD=123456 + volumes: + - /tmp/datadir:/var/lib/mysql + - /tmp/conf.d:/etc/mysql/conf.d + - ../api/script/db:/docker-entrypoint-initdb.d + networks: + apisix-dashboard: + ipv4_address: 192.17.5.14 + + manager: + build: + context: ./../api + dockerfile: Dockerfile + restart: always + ports: + - "8080:8080/tcp" + environment: + - ENV=prod + volumes: + - ./manager_conf/build.sh:/root/manager-api/build.sh + networks: + apisix-dashboard: + ipv4_address: 192.17.5.15 + + prometheus: + image: prom/prometheus + hostname: prometheus + restart: always + volumes: + - ./prometheus_conf/prometheus.yml:/etc/prometheus/prometheus.yml + ports: + - "9090:9090" + networks: + apisix-dashboard: + ipv4_address: 192.17.5.16 + + grafana: + image: grafana/grafana + container_name: grafana + hostname: grafana + restart: always + ports: + - "3000:3000" + volumes: + - "./grafana_conf/provisioning:/etc/grafana/provisioning" + - "./grafana_conf/dashboards:/var/lib/grafana/dashboards" + - "./grafana_conf/config/grafana.ini:/etc/grafana/grafana.ini" + networks: + apisix-dashboard: + ipv4_address: 192.17.5.17 + + dashboard: + build: + context: ./.. + dockerfile: Dockerfile + restart: always + ports: + - "80:80/tcp" + +networks: + apisix-dashboard: + driver: bridge + ipam: + config: + - subnet: 192.17.0.0/16 \ No newline at end of file diff --git a/compose/grafana_conf/config/grafana.ini b/compose/grafana_conf/config/grafana.ini new file mode 100644 index 0000000000..cb6a7376c5 --- /dev/null +++ b/compose/grafana_conf/config/grafana.ini @@ -0,0 +1,756 @@ +##################### Grafana Configuration Example ##################### +# +# Everything has defaults so you only need to uncomment things you want to +# change + +# possible values : production, development +;app_mode = production + +# instance name, defaults to HOSTNAME environment variable value or hostname if HOSTNAME var is empty +;instance_name = ${HOSTNAME} + +#################################### Paths #################################### +[paths] +# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used) +;data = /var/lib/grafana + +# Temporary files in `data` directory older than given duration will be removed +;temp_data_lifetime = 24h + +# Directory where grafana can store logs +;logs = /var/log/grafana + +# Directory where grafana will automatically scan and look for plugins +;plugins = /var/lib/grafana/plugins + +# folder that contains provisioning config files that grafana will apply on startup and while running. +;provisioning = conf/provisioning + +#################################### Server #################################### +[server] +# Protocol (http, https, h2, socket) +;protocol = http + +# The ip address to bind to, empty will bind to all interfaces +;http_addr = + +# The http port to use +;http_port = 3000 + +# The public facing domain name used to access grafana from a browser +;domain = localhost + +# Redirect to correct domain if host header does not match domain +# Prevents DNS rebinding attacks +;enforce_domain = false + +# The full public facing url you use in browser, used for redirects and emails +# If you use reverse proxy and sub path specify full url (with sub path) +;root_url = %(protocol)s://%(domain)s:%(http_port)s/ + +# Serve Grafana from subpath specified in `root_url` setting. By default it is set to `false` for compatibility reasons. +;serve_from_sub_path = false + +# Log web requests +;router_logging = false + +# the path relative working path +;static_root_path = public + +# enable gzip +;enable_gzip = false + +# https certs & key file +;cert_file = +;cert_key = + +# Unix socket path +;socket = + +#################################### Database #################################### +[database] +# You can configure the database connection by specifying type, host, name, user and password +# as separate properties or as on string using the url properties. + +# Either "mysql", "postgres" or "sqlite3", it's your choice +;type = sqlite3 +;host = 127.0.0.1:3306 +;name = grafana +;user = root +# If the password contains # or ; you have to wrap it with triple quotes. Ex """#password;""" +;password = + +# Use either URL or the previous fields to configure the database +# Example: mysql://user:secret@host:port/database +;url = + +# For "postgres" only, either "disable", "require" or "verify-full" +;ssl_mode = disable + +;ca_cert_path = +;client_key_path = +;client_cert_path = +;server_cert_name = + +# For "sqlite3" only, path relative to data_path setting +;path = grafana.db + +# Max idle conn setting default is 2 +;max_idle_conn = 2 + +# Max conn setting default is 0 (mean not set) +;max_open_conn = + +# Connection Max Lifetime default is 14400 (means 14400 seconds or 4 hours) +;conn_max_lifetime = 14400 + +# Set to true to log the sql calls and execution times. +;log_queries = + +# For "sqlite3" only. cache mode setting used for connecting to the database. (private, shared) +;cache_mode = private + +#################################### Cache server ############################# +[remote_cache] +# Either "redis", "memcached" or "database" default is "database" +;type = database + +# cache connectionstring options +# database: will use Grafana primary database. +# redis: config like redis server e.g. `addr=127.0.0.1:6379,pool_size=100,db=0,ssl=false`. Only addr is required. ssl may be 'true', 'false', or 'insecure'. +# memcache: 127.0.0.1:11211 +;connstr = + +#################################### Data proxy ########################### +[dataproxy] + +# This enables data proxy logging, default is false +;logging = false + +# How long the data proxy should wait before timing out default is 30 (seconds) +;timeout = 30 + +# If enabled and user is not anonymous, data proxy will add X-Grafana-User header with username into the request, default is false. +;send_user_header = false + +#################################### Analytics #################################### +[analytics] +# Server reporting, sends usage counters to stats.grafana.org every 24 hours. +# No ip addresses are being tracked, only simple counters to track +# running instances, dashboard and error counts. It is very helpful to us. +# Change this option to false to disable reporting. +;reporting_enabled = true + +# Set to false to disable all checks to https://grafana.net +# for new vesions (grafana itself and plugins), check is used +# in some UI views to notify that grafana or plugin update exists +# This option does not cause any auto updates, nor send any information +# only a GET request to http://grafana.com to get latest versions +;check_for_updates = true + +# Google Analytics universal tracking code, only enabled if you specify an id here +;google_analytics_ua_id = + +# Google Tag Manager ID, only enabled if you specify an id here +;google_tag_manager_id = + +#################################### Security #################################### +[security] +# disable creation of admin user on first start of grafana +;disable_initial_admin_creation = false + +# default admin user, created on startup +;admin_user = admin + +# default admin password, can be changed before first start of grafana, or in profile settings +;admin_password = admin + +# used for signing +;secret_key = SW2YcwTIb9zpOOhoPsMm + +# disable gravatar profile images +;disable_gravatar = false + +# data source proxy whitelist (ip_or_domain:port separated by spaces) +;data_source_proxy_whitelist = + +# disable protection against brute force login attempts +;disable_brute_force_login_protection = false + +# set to true if you host Grafana behind HTTPS. default is false. +;cookie_secure = false + +# set cookie SameSite attribute. defaults to `lax`. can be set to "lax", "strict", "none" and "disabled" +;cookie_samesite = none + +# set to true if you want to allow browsers to render Grafana in a ,