Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

Do not return instance password to the client and rework the corresponding instance migration endpoint

天舟553cd36cae3d
diff --git a/api/instance.go b/api/instance.go
index e58eb37df8..818e327ef3 100644
--- a/api/instance.go
+++ b/api/instance.go
@@ -29,9 +29,9 @@ type Instance struct {
ExternalLink string `jsonapi:"attr,externalLink"`
Host string `jsonapi:"attr,host"`
Port string `jsonapi:"attr,port"`
- // Only returns username/password if supplying query parameter 'include=secret'
- Username string `jsonapi:"attr,username"`
- Password string `jsonapi:"attr,password"`
+ Username string `jsonapi:"attr,username"`
+ // Password is not returned to the client
+ Password string
}
type InstanceCreate struct {
@@ -84,6 +84,32 @@ type InstancePatch struct {
Password *string `jsonapi:"attr,password"`
}
+// Instance migration status
+type InstanceMigrationStatus string
+
+const (
+ InstanceMigrationUnknown InstanceMigrationStatus = "UNKNOWN"
+ InstanceMigrationOK InstanceMigrationStatus = "OK"
+ InstanceMigrationNotExist InstanceMigrationStatus = "NOT_EXIST"
+)
+
+func (e InstanceMigrationStatus) String() string {
+ switch e {
+ case InstanceMigrationUnknown:
+ return "UNKNOWN"
+ case InstanceMigrationOK:
+ return "OK"
+ case InstanceMigrationNotExist:
+ return "NOT_EXIST"
+ }
+ return "UNKNOWN"
+}
+
+type InstanceMigration struct {
+ Status InstanceMigrationStatus `jsonapi:"attr,status"`
+ Error string `jsonapi:"attr,error"`
+}
+
type InstanceService interface {
CreateInstance(ctx context.Context, create *InstanceCreate) (*Instance, error)
FindInstanceList(ctx context.Context, find *InstanceFind) ([]*Instance, error)
diff --git a/api/migration.go b/api/migration.go
deleted file mode 100644
index 86c74bb6e7..0000000000
--- a/api/migration.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package api
-
-// Instance migration status
-type InstanceMigrationStatus string
-
-const (
- InstanceMigrationUnknown InstanceMigrationStatus = "UNKNOWN"
- InstanceMigrationOK InstanceMigrationStatus = "OK"
- InstanceMigrationNotExist InstanceMigrationStatus = "NOT_EXIST"
-)
-
-func (e InstanceMigrationStatus) String() string {
- switch e {
- case InstanceMigrationUnknown:
- return "UNKNOWN"
- case InstanceMigrationOK:
- return "OK"
- case InstanceMigrationNotExist:
- return "NOT_EXIST"
- }
- return "UNKNOWN"
-}
-
-type InstanceMigration struct {
- Status InstanceMigrationStatus `jsonapi:"attr,status"`
- Error string `jsonapi:"attr,error"`
-}
diff --git a/frontend/src/components/InstanceForm.vue b/frontend/src/components/InstanceForm.vue
index 2713596f02..c5b42cf790 100644
--- a/frontend/src/components/InstanceForm.vue
+++ b/frontend/src/components/InstanceForm.vue
@@ -177,8 +177,7 @@ input[type="number"] {
bg-gray-50
hover:bg-gray-100
disabled:bg-gray-50
- focus:ring-control
- focus:outline-none
+ focus:ring-control focus:outline-none
focus-visible:ring-2
focus:ring-offset-1
disabled:cursor-not-allowed
@@ -222,61 +221,21 @@ input[type="number"] {
</div>
<div class="sm:col-span-1 sm:col-start-1">
- <div class="flex flex-row items-center">
- <label for="password" class="textlabel block"> Password </label>
- <div class="ml-1 flex items-center">
- <button
- class="btn-icon"
- @click.prevent="state.showPassword = !state.showPassword"
- >
- <svg
- v-if="state.showPassword"
- class="w-6 h-6"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- xmlns="http://www.w3.org/2000/svg"
- >
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"
- ></path>
- </svg>
- <svg
- v-else
- class="w-6 h-6"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- xmlns="http://www.w3.org/2000/svg"
- >
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
- ></path>
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
- ></path>
- </svg>
- </button>
- </div>
- </div>
+ <label for="password" class="textlabel block"> Password </label>
<input
id="password"
name="password"
- autocomplete="off"
- :type="state.showPassword ? 'text' : 'password'"
+ type="text"
class="textfield mt-1 w-full"
+ autocomplete="off"
+ placeholder="sensitive - write only"
:disabled="!allowEdit"
- :value="state.instance.password"
- @input="state.instance.password = $event.target.value"
+ :value="create ? state.instance.password : state.updatedPassword"
+ @input="
+ create
+ ? (state.instance.password = $event.target.value)
+ : (state.updatedPassword = $event.target.value)
+ "
/>
</div>
</div>
@@ -341,18 +300,18 @@ input[type="number"] {
</div>
</form>
<BBAlert
- v-if="state.showCreateMigrationSchemaModal"
- :style="'INFO'"
- :okText="'Create'"
- :title="'Create migration schema?'"
- :description="'The migration schema does not exist on this instance and Bytebase needs to create it in order to manage schema migration.'"
+ v-if="state.showCreateInstanceWarningModal"
+ :style="'WARN'"
+ :okText="'Ignore and create'"
+ :title="'Connection info seems to be incorrect'"
+ :description="state.createInstanceWarning"
@ok="
() => {
- state.showCreateMigrationSchemaModal = false;
- doCreateSchema();
+ state.showCreateInstanceWarningModal = false;
+ doCreate();
}
"
- @cancel="state.showCreateMigrationSchemaModal = false"
+ @cancel="state.showCreateInstanceWarningModal = false"
>
</BBAlert>
</template>
@@ -374,7 +333,6 @@ import {
InstancePatch,
ConnectionInfo,
SqlResultSet,
- InstanceMigration,
} from "../types";
import isEmpty from "lodash-es/isEmpty";
@@ -384,9 +342,11 @@ const GRANT_STATEMENT =
interface LocalState {
originalInstance?: Instance;
instance: Instance | InstanceCreate;
- showPassword: boolean;
+ // Only used in non-create case.
+ updatedPassword: string;
connectionResult: string;
- showCreateMigrationSchemaModal: boolean;
+ showCreateInstanceWarningModal: boolean;
+ createInstanceWarning: string;
}
export default {
@@ -422,11 +382,12 @@ export default {
name: "New Instance",
engine: "MYSQL",
host: "127.0.0.1",
- username: "root",
+ username: "",
},
- showPassword: false,
+ updatedPassword: "",
connectionResult: "",
- showCreateMigrationSchemaModal: false,
+ showCreateInstanceWarningModal: false,
+ createInstanceWarning: "",
});
const allowCreate = computed(() => {
@@ -442,7 +403,10 @@ export default {
});
const valueChanged = computed(() => {
- return !isEqual(state.instance, state.originalInstance);
+ return (
+ !isEqual(state.instance, state.originalInstance) ||
+ !isEmpty(state.updatedPassword)
+ );
});
const updateInstance = (field: string, value: string) => {
@@ -453,7 +417,7 @@ export default {
emit("dismiss");
};
- const doCreateSchema = () => {
+ const tryCreate = () => {
const connectionInfo: ConnectionInfo = {
dbType: "MYSQL",
username: state.instance.username,
@@ -462,42 +426,13 @@ export default {
port: state.instance.port,
};
store
- .dispatch("migration/createkMigrationSetup", connectionInfo)
+ .dispatch("sql/ping", connectionInfo)
.then((resultSet: SqlResultSet) => {
- if (resultSet.error) {
- state.connectionResult = resultSet.error;
- } else {
+ if (isEmpty(resultSet.error)) {
doCreate();
- }
- });
- };
-
- // We will first check if migration schema exists on the instance.
- // If it doesn't, we will ask user to allow Bytebase to create that schema before proceeding to creating the instance.
- const tryCreate = () => {
- const connectionInfo: ConnectionInfo = {
- dbType: "MYSQL",
- username: state.instance.username,
- password: state.instance.password,
- host: state.instance.host,
- port: state.instance.port,
- };
- store
- .dispatch("migration/checkMigrationSetup", connectionInfo)
- .then((migration: InstanceMigration) => {
- switch (migration.status) {
- case "UNKNOWN": {
- state.connectionResult = migration.error;
- break;
- }
- case "NOT_EXIST": {
- state.showCreateMigrationSchemaModal = true;
- break;
- }
- case "OK": {
- doCreate();
- break;
- }
+ } else {
+ state.createInstanceWarning = `Bytebase is unable to connect the instance with the provided connection info. Please check the input is correct. You can still ignore this warning to proceed creating the instance, and fix the connection info later. Error detail: ${resultSet.error}`;
+ state.showCreateInstanceWarningModal = true;
}
});
};
@@ -505,11 +440,7 @@ export default {
// We will also create the database * denoting all databases
// and its RW data source. The username, password is actually
// stored in that data source object instead of in the instance self.
- // 1. Conceptually, data source is the proper place to store connnection info (thinking of DSN)
- // 2. Instance info will sometimes be pulled when fetching other resoures (like database)
- // in order to display the relevant info. In those cases, we don't want to include sensitive
- // info such as username/password there. It's harder to redact this on the instance. Thus the
- // only option is to split those information into a separate resource which won't be pulled together.
+ // Conceptually, data source is the proper place to store connnection info (thinking of DSN)
const doCreate = () => {
store
.dispatch("instance/createInstance", state.instance)
@@ -528,6 +459,9 @@ export default {
key: "instance.create",
newState: true,
});
+
+ // After creating the instance, we will check if migration schema exists on the instance.
+ setTimeout(() => {}, 1000);
});
};
@@ -548,8 +482,8 @@ export default {
if (state.instance.username != state.originalInstance!.username) {
patchedInstance.username = state.instance.username;
}
- if (state.instance.password != state.originalInstance!.password) {
- patchedInstance.password = state.instance.password;
+ if (!isEmpty(state.updatedPassword)) {
+ patchedInstance.password = state.updatedPassword;
}
store
@@ -561,6 +495,7 @@ export default {
state.originalInstance = instance;
// Make hard copy since we are going to make equal comparsion to determine the update button enable state.
state.instance = cloneDeep(state.originalInstance!);
+ state.updatedPassword = "";
store.dispatch("notification/pushNotification", {
module: "bytebase",
@@ -584,7 +519,9 @@ export default {
const connectionInfo: ConnectionInfo = {
dbType: "MYSQL",
username: state.instance.username,
- password: state.instance.password,
+ password: props.create
+ ? state.instance.password
+ : state.updatedPassword,
host: state.instance.host,
port: state.instance.port,
};
@@ -607,7 +544,6 @@ export default {
valueChanged,
updateInstance,
cancel,
- doCreateSchema,
tryCreate,
doCreate,
doUpdate,
diff --git a/frontend/src/store/index.ts b/frontend/src/store/index.ts
index eceb6d0040..6197311590 100644
--- a/frontend/src/store/index.ts
+++ b/frontend/src/store/index.ts
@@ -31,9 +31,6 @@ import router from "./modules/router";
import command from "./modules/command";
import notification from "./modules/notification";
-// migration module
-import migration from "./modules/migration";
-
// Debug module
import debug from "./modules/debug";
@@ -66,7 +63,6 @@ export const store: Store<any> = createStore({
router,
command,
notification,
- migration,
debug,
},
strict: !isProd,
diff --git a/frontend/src/store/modules/instance.ts b/frontend/src/store/modules/instance.ts
index 2df1dffb91..93e1b4bd0c 100644
--- a/frontend/src/store/modules/instance.ts
+++ b/frontend/src/store/modules/instance.ts
@@ -14,6 +14,8 @@ import {
empty,
EMPTY_ID,
Principal,
+ InstanceMigration,
+ SqlResultSet,
} from "../../types";
function convert(
@@ -49,6 +51,8 @@ function convert(
creator,
updater,
environment,
+ // Password is not returned by the server, we just take extra caution here to redact it.
+ password: "",
};
}
@@ -124,9 +128,7 @@ const actions = {
{ commit, rootGetters }: any,
instanceId: InstanceId
) {
- // include=secret to return username/password when requesting the specific instance id
- const data = (await axios.get(`/api/instance/${instanceId}?include=secret`))
- .data;
+ const data = (await axios.get(`/api/instance/${instanceId}`)).data;
const instance = convert(data.data, data.included, rootGetters);
commit("setInstanceById", {
@@ -141,7 +143,7 @@ const actions = {
newInstance: InstanceCreate
) {
const data = (
- await axios.post(`/api/instance?include=secret`, {
+ await axios.post(`/api/instance`, {
data: {
type: "InstanceCreate",
attributes: newInstance,
@@ -194,6 +196,30 @@ const actions = {
commit("deleteInstanceById", instanceId);
},
+
+ async checkMigrationSetup(
+ {}: any,
+ instanceId: InstanceId
+ ): Promise<InstanceMigration> {
+ const data = (
+ await axios.get(`/api/instance/${instanceId}/migration/status`)
+ ).data.data;
+
+ return {
+ status: data.attributes.status,
+ error: data.attributes.error,
+ };
+ },
+
+ async createMigrationSetup(
+ { rootGetters }: any,
+ instanceId: InstanceId
+ ): Promise<SqlResultSet> {
+ const data = (await axios.post(`/api/instance/${instanceId}/migration`))
+ .data.data;
+
+ return rootGetters["sql/convert"](data);
+ },
};
const mutations = {
diff --git a/frontend/src/store/modules/migration.ts b/frontend/src/store/modules/migration.ts
deleted file mode 100644
index 31bfed57f8..0000000000
--- a/frontend/src/store/modules/migration.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import axios from "axios";
-import { ConnectionInfo, InstanceMigration, SqlResultSet } from "../../types";
-
-const getters = {};
-
-const actions = {
- async checkMigrationSetup(
- {}: any,
- connectionInfo: ConnectionInfo
- ): Promise<InstanceMigration> {
- const data = (
- await axios.post(`/api/migration/instance/status`, {
- data: {
- type: "connectionInfo",
- attributes: connectionInfo,
- },
- })
- ).data.data;
-
- return {
- status: data.attributes.status,
- error: data.attributes.error,
- };
- },
-
- async createkMigrationSetup(
- { rootGetters }: any,
- connectionInfo: ConnectionInfo
- ): Promise<SqlResultSet> {
- const data = (
- await axios.post(`/api/migration/instance`, {
- data: {
- type: "connectionInfo",
- attributes: connectionInfo,
- },
- })
- ).data.data;
-
- return rootGetters["sql/convert"](data);
- },
-};
-
-const mutations = {};
-
-export default {
- namespaced: true,
- getters,
- actions,
- mutations,
-};
diff --git a/frontend/src/store/modules/vcs.ts b/frontend/src/store/modules/vcs.ts
index 9432551023..375d58bbb5 100644
--- a/frontend/src/store/modules/vcs.ts
+++ b/frontend/src/store/modules/vcs.ts
@@ -75,7 +75,6 @@ const actions = {
},
async fetchVCSById({ commit }: any, vcsId: VCSId) {
- // include=secret to return username/password when requesting the specific vcs id
const data = (await axios.get(`/api/vcs/${vcsId}`)).data;
const vcs = convert(data.data);
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index fc07a6ced2..1d6c8dac84 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -23,5 +23,3 @@ export * from "./store";
export * from "./oauth";
export * from "./jsonapi";
-
-export * from "./migration";
diff --git a/frontend/src/types/instance.ts b/frontend/src/types/instance.ts
index b3b176557b..ffbf129f0d 100644
--- a/frontend/src/types/instance.ts
+++ b/frontend/src/types/instance.ts
@@ -56,3 +56,10 @@ export type InstancePatch = {
username?: string;
password?: string;
};
+
+export type InstanceMigrationStatus = "UNKNOWN" | "OK" | "NOT_EXIST";
+
+export type InstanceMigration = {
+ status: InstanceMigrationStatus;
+ error: string;
+};
diff --git a/frontend/src/types/migration.ts b/frontend/src/types/migration.ts
deleted file mode 100644
index f4072b6668..0000000000
--- a/frontend/src/types/migration.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export type InstanceMigrationStatus = "UNKNOWN" | "OK" | "NOT_EXIST";
-
-export type InstanceMigration = {
- status: InstanceMigrationStatus;
- error: string;
-};
diff --git a/frontend/src/views/InstanceDetail.vue b/frontend/src/views/InstanceDetail.vue
index 915dfc666e..10dac13ef2 100644
--- a/frontend/src/views/InstanceDetail.vue
+++ b/frontend/src/views/InstanceDetail.vue
@@ -48,10 +48,26 @@
</template>
</div>
</div>
+
+ <BBAlert
+ v-if="state.showCreateMigrationSchemaModal"
+ :style="'INFO'"
+ :okText="'Create'"
+ :title="'Create migration schema?'"
+ :description="'The migration schema does not exist on this instance and Bytebase needs to create it in order to manage schema migration.'"
+ @ok="
+ () => {
+ state.showCreateMigrationSchemaModal = false;
+ doCreateMigrationSchema();
+ }
+ "
+ @cancel="state.showCreateMigrationSchemaModal = false"
+ >
+ </BBAlert>
</template>
<script lang="ts">
-import { computed } from "vue";
+import { computed, reactive, watchEffect } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { idFromSlug } from "../utils";
@@ -59,7 +75,11 @@ import ArchiveBanner from "../components/ArchiveBanner.vue";
import DatabaseTable from "../components/DatabaseTable.vue";
import DataSourceTable from "../components/DataSourceTable.vue";
import InstanceForm from "../components/InstanceForm.vue";
-import { Instance, SqlResultSet } from "../types";
+import { Instance, InstanceMigration, SqlResultSet } from "../types";
+
+interface LocalState {
+ showCreateMigrationSchemaModal: boolean;
+}
export default {
name: "InstanceDetail",
@@ -79,9 +99,9 @@ export default {
const router = useRouter();
const store = useStore();
- const hasDataSourceFeature = computed(() =>
- store.getters["plan/feature"]("bb.data-source")
- );
+ const state = reactive<LocalState>({
+ showCreateMigrationSchemaModal: false,
+ });
const instance = computed((): Instance => {
return store.getters["instance/instanceById"](
@@ -89,6 +109,36 @@ export default {
);
});
+ const prepareMigrationStatus = () => {
+ store
+ .dispatch("instance/checkMigrationSetup", instance.value.id)
+ .then((migration: InstanceMigration) => {
+ switch (migration.status) {
+ case "UNKNOWN": {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "CRITICAL",
+ title: `Unable to check migration setup for instance '${instance.value.name}'.`,
+ description: migration.error,
+ });
+ break;
+ }
+ case "NOT_EXIST": {
+ state.showCreateMigrationSchemaModal = true;
+ break;
+ }
+ case "OK": {
+ break;
+ }
+ }
+ });
+ };
+ watchEffect(prepareMigrationStatus);
+
+ const hasDataSourceFeature = computed(() =>
+ store.getters["plan/feature"]("bb.data-source")
+ );
+
const databaseList = computed(() => {
return store.getters["database/databaseListByInstanceId"](
instance.value.id
@@ -139,6 +189,27 @@ export default {
});
};
+ const doCreateMigrationSchema = () => {
+ store
+ .dispatch("instance/createMigrationSetup", instance.value.id)
+ .then((resultSet: SqlResultSet) => {
+ if (resultSet.error) {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "CRITICAL",
+ title: `Failed to create migration schema for instance '${instance.value.name}'.`,
+ description: resultSet.error,
+ });
+ } else {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "SUCCESS",
+ title: `Successfully created migration schema for '${instance.value.name}'.`,
+ });
+ }
+ });
+ };
+
const syncSchema = () => {
store
.dispatch("sql/syncSchema", instance.value.id)
@@ -162,12 +233,14 @@ export default {
};
return {
+ state,
hasDataSourceFeature,
instance,
databaseList,
tryAddDatabase,
doArchive,
doRestore,
+ doCreateMigrationSchema,
syncSchema,
};
},
diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csv
index 429b157273..3e0be9bf06 100644
--- a/server/acl_casbin_policy_dba.csv
+++ b/server/acl_casbin_policy_dba.csv
@@ -20,6 +20,8 @@ p, DBA, /instance, POST
p, DBA, /instance, GET
p, DBA, /instance/{id}, GET
p, DBA, /instance/{id}, PATCH
+p, DBA, /instance/{id}/migration, POST
+p, DBA, /instance/{id}/migration/status, GET
p, DBA, /database, POST
p, DBA, /database, GET
p, DBA, /database/{id}, GET
@@ -45,6 +47,4 @@ p, DBA, /vcs, GET
p, DBA, /vcs/{id}, GET
p, DBA, /vcs/{id}, PATCH
p, DBA, /vcs/{id}, DELETE
-p, DBA, /vcs/{id}/repository, GET
-p, DBA, /migration/instance/status, POST
-p, DBA, /migration/instance, POST
\ No newline at end of file
+p, DBA, /vcs/{id}/repository, GET
\ No newline at end of file
diff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csv
index 29a0f6f1f5..c96790071a 100644
--- a/server/acl_casbin_policy_owner.csv
+++ b/server/acl_casbin_policy_owner.csv
@@ -25,6 +25,8 @@ p, OWNER, /instance, POST
p, OWNER, /instance, GET
p, OWNER, /instance/{id}, GET
p, OWNER, /instance/{id}, PATCH
+p, OWNER, /instance/{id}/migration, POST
+p, OWNER, /instance/{id}/migration/status, GET
p, OWNER, /database, POST
p, OWNER, /database, GET
p, OWNER, /database/{id}, GET
@@ -50,6 +52,4 @@ p, OWNER, /vcs, GET
p, OWNER, /vcs/{id}, GET
p, OWNER, /vcs/{id}, PATCH
p, OWNER, /vcs/{id}, DELETE
-p, OWNER, /vcs/{id}/repository, GET
-p, OWNER, /migration/instance/status, POST
-p, OWNER, /migration/instance, POST
+p, OWNER, /vcs/{id}/repository, GET
\ No newline at end of file
diff --git a/server/instance.go b/server/instance.go
index 38a2055f0a..6836f9f6be 100644
--- a/server/instance.go
+++ b/server/instance.go
@@ -8,6 +8,7 @@ import (
"github.com/bytebase/bytebase"
"github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/db"
"github.com/google/jsonapi"
"github.com/labstack/echo/v4"
)
@@ -152,6 +153,85 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
}
return nil
})
+
+ g.POST("/instance/:instanceId/migration", func(c echo.Context) error {
+ id, err := strconv.Atoi(c.Param("instanceId"))
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
+ }
+
+ instance, err := s.ComposeInstanceById(context.Background(), id, []string{})
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch instance ID: %v", id)).SetInternal(err)
+ }
+
+ resultSet := &api.SqlResultSet{}
+ db, err := db.Open(instance.Engine, db.DriverConfig{Logger: s.l}, db.ConnectionConfig{
+ Username: instance.Username,
+ Password: instance.Password,
+ Host: instance.Host,
+ Port: instance.Port,
+ })
+ if err != nil {
+ resultSet.Error = err.Error()
+ } else {
+ if err := db.SetupMigrationIfNeeded(context.Background()); err != nil {
+ resultSet.Error = err.Error()
+ }
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, resultSet); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal migration setup status response for host:port: %v:%v", instance.Host, instance.Port)).SetInternal(err)
+ }
+ return nil
+ })
+
+ g.GET("/instance/:instanceId/migration/status", func(c echo.Context) error {
+ id, err := strconv.Atoi(c.Param("instanceId"))
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)
+ }
+
+ instance, err := s.ComposeInstanceById(context.Background(), id, []string{})
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch instance ID: %v", id)).SetInternal(err)
+ }
+
+ instanceMigration := &api.InstanceMigration{}
+ db, err := db.Open(instance.Engine, db.DriverConfig{Logger: s.l}, db.ConnectionConfig{
+ Username: instance.Username,
+ Password: instance.Password,
+ Host: instance.Host,
+ Port: instance.Port,
+ })
+ if err != nil {
+ instanceMigration.Status = api.InstanceMigrationUnknown
+ instanceMigration.Error = err.Error()
+ } else {
+ setup, err := db.NeedsSetupMigration(context.Background())
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to check migration setup status for host:port: %v:%v", instance.Host, instance.Port)).SetInternal(err)
+ }
+ if setup {
+ instanceMigration.Status = api.InstanceMigrationNotExist
+ } else {
+ instanceMigration.Status = api.InstanceMigrationOK
+ }
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, instanceMigration); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal migration setup status response for host:port: %v:%v", instance.Host, instance.Port)).SetInternal(err)
+ }
+ return nil
+ })
}
func (s *Server) ComposeInstanceById(ctx context.Context, id int, includeList []string) (*api.Instance, error) {
@@ -188,14 +268,10 @@ func (s *Server) ComposeInstanceRelationship(ctx context.Context, instance *api.
return err
}
- if bytebase.FindString(includeList, SECRET_KEY) >= 0 {
- return s.ComposeInstanceSecret(context.Background(), instance)
- }
-
- return nil
+ return s.ComposeInstanceAdminDataSource(context.Background(), instance)
}
-func (s *Server) ComposeInstanceSecret(ctx context.Context, instance *api.Instance) error {
+func (s *Server) ComposeInstanceAdminDataSource(ctx context.Context, instance *api.Instance) error {
dataSourceFind := &api.DataSourceFind{
InstanceId: &instance.ID,
}
diff --git a/server/migration.go b/server/migration.go
deleted file mode 100644
index b776d8d9b5..0000000000
--- a/server/migration.go
+++ /dev/null
@@ -1,77 +0,0 @@
-package server
-
-import (
- "context"
- "fmt"
- "net/http"
-
- "github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/db"
- "github.com/google/jsonapi"
- "github.com/labstack/echo/v4"
-)
-
-func (s *Server) registerMigrationRoutes(g *echo.Group) {
- g.POST("/migration/instance", func(c echo.Context) error {
- connectionInfo := &api.ConnectionInfo{}
- if err := jsonapi.UnmarshalPayload(c.Request().Body, connectionInfo); err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, "Malformatted instance migration status request").SetInternal(err)
- }
-
- resultSet := &api.SqlResultSet{}
- db, err := db.Open(connectionInfo.DBType, db.DriverConfig{Logger: s.l}, db.ConnectionConfig{
- Username: connectionInfo.Username,
- Password: connectionInfo.Password,
- Host: connectionInfo.Host,
- Port: connectionInfo.Port,
- })
- if err != nil {
- resultSet.Error = err.Error()
- } else {
- if err := db.SetupMigrationIfNeeded(context.Background()); err != nil {
- resultSet.Error = err.Error()
- }
- }
-
- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, resultSet); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal migration setup status response for host:port: %v:%v", connectionInfo.Host, connectionInfo.Port)).SetInternal(err)
- }
- return nil
- })
-
- g.POST("/migration/instance/status", func(c echo.Context) error {
- connectionInfo := &api.ConnectionInfo{}
- if err := jsonapi.UnmarshalPayload(c.Request().Body, connectionInfo); err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, "Malformatted instance migration status request").SetInternal(err)
- }
-
- instanceMigration := &api.InstanceMigration{}
- db, err := db.Open(connectionInfo.DBType, db.DriverConfig{Logger: s.l}, db.ConnectionConfig{
- Username: connectionInfo.Username,
- Password: connectionInfo.Password,
- Host: connectionInfo.Host,
- Port: connectionInfo.Port,
- })
- if err != nil {
- instanceMigration.Status = api.InstanceMigrationUnknown
- instanceMigration.Error = err.Error()
- } else {
- setup, err := db.NeedsSetupMigration(context.Background())
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to check migration setup status for host:port: %v:%v", connectionInfo.Host, connectionInfo.Port)).SetInternal(err)
- }
- if setup {
- instanceMigration.Status = api.InstanceMigrationNotExist
- } else {
- instanceMigration.Status = api.InstanceMigrationOK
- }
- }
-
- c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, instanceMigration); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal migration setup status response for host:port: %v:%v", connectionInfo.Host, connectionInfo.Port)).SetInternal(err)
- }
- return nil
- })
-}
diff --git a/server/schema_syncer.go b/server/schema_syncer.go
index 50d9053878..46c6949942 100644
--- a/server/schema_syncer.go
+++ b/server/schema_syncer.go
@@ -49,7 +49,7 @@ func (s *SchemaSyncer) Run() error {
}
for _, instance := range list {
- if err := s.server.ComposeInstanceSecret(context.Background(), instance); err != nil {
+ if err := s.server.ComposeInstanceAdminDataSource(context.Background(), instance); err != nil {
s.l.Error("Failed to sync instance",
zap.String("instance_name", instance.Name),
zap.String("error", err.Error()))
diff --git a/server/server.go b/server/server.go
index b3d90312be..7c52699ad3 100644
--- a/server/server.go
+++ b/server/server.go
@@ -19,10 +19,6 @@ import (
"go.uber.org/zap"
)
-const (
- SECRET_KEY = "secret"
-)
-
type Server struct {
TaskScheduler *TaskScheduler
SchemaSyncer *SchemaSyncer
@@ -164,7 +160,6 @@ func NewServer(logger *zap.Logger, host string, port int) *Server {
s.registerBookmarkRoutes(apiGroup)
s.registerSqlRoutes(apiGroup)
s.registerVCSRoutes(apiGroup)
- s.registerMigrationRoutes(apiGroup)
allRoutes, err := json.MarshalIndent(e.Routes(), "", " ")
if err != nil {
diff --git a/server/sql.go b/server/sql.go
index 97b9d6418c..073bf0c7d0 100644
--- a/server/sql.go
+++ b/server/sql.go
@@ -35,7 +35,7 @@ func (s *Server) registerSqlRoutes(g *echo.Group) {
if connectionInfo.Port != "" {
hostPort += ":" + connectionInfo.Port
}
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Failed to connect %s for user '%s' (using password: %s)", hostPort, connectionInfo.Username, usePassword)).SetInternal(err)
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Failed to connect '%s' for user '%s' (using password: %s)", hostPort, connectionInfo.Username, usePassword)).SetInternal(err)
}
resultSet := &api.SqlResultSet{}
@@ -56,7 +56,7 @@ func (s *Server) registerSqlRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted sql sync schema request").SetInternal(err)
}
- instance, err := s.ComposeInstanceById(context.Background(), sync.InstanceId, []string{SECRET_KEY})
+ instance, err := s.ComposeInstanceById(context.Background(), sync.InstanceId, []string{})
if err != nil {
if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", sync.InstanceId))
@@ -71,7 +71,15 @@ func (s *Server) registerSqlRoutes(g *echo.Group) {
Port: instance.Port,
})
if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Failed to connect instance: %v with user: %v", instance.Name, instance.Username)).SetInternal(err)
+ usePassword := "YES"
+ if instance.Password == "" {
+ usePassword = "NO"
+ }
+ hostPort := instance.Host
+ if instance.Port != "" {
+ hostPort += ":" + instance.Port
+ }
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Failed to connect '%s' for user '%s' (using password: %s)", hostPort, instance.Username, usePassword)).SetInternal(err)
}
resultSet := &api.SqlResultSet{}
diff --git a/server/task_executor_database_create.go b/server/task_executor_database_create.go
index 25615633b2..b1f1305777 100644
--- a/server/task_executor_database_create.go
+++ b/server/task_executor_database_create.go
@@ -38,7 +38,7 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *Ser
return true, fmt.Errorf("invalid create database payload: %w", err)
}
- if err := server.ComposeTaskRelationship(ctx, task, []string{SECRET_KEY}); err != nil {
+ if err := server.ComposeTaskRelationship(ctx, task, []string{}); err != nil {
return true, err
}
diff --git a/server/task_executor_schema_update.go b/server/task_executor_schema_update.go
index 22ba9e5fed..5e4e993c3c 100644
--- a/server/task_executor_schema_update.go
+++ b/server/task_executor_schema_update.go
@@ -59,7 +59,7 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Serve
return true, fmt.Errorf("empty sql statement")
}
- if err := server.ComposeTaskRelationship(ctx, task, []string{SECRET_KEY}); err != nil {
+ if err := server.ComposeTaskRelationship(ctx, task, []string{}); err != nil {
return true, err
}