Compare commits

...

40 Commits

Author SHA1 Message Date
LinkLeong
438b8a1dd2 Solve the problem of local application import failure 2022-11-04 07:41:09 +00:00
LinkLeong
ca967ec59c update release 2022-10-26 08:45:32 +01:00
LinkLeong
2beb1c0d82 update changelog 2022-10-19 09:08:11 +01:00
LinkLeong
772c3e0bc0 Merge branch 'v0.3.7' of https://github.com/IceWhaleTech/CasaOS into v0.3.7 2022-10-19 09:00:57 +01:00
LinkLeong
bcda992322 add change log 2022-10-19 09:00:45 +01:00
Tiger Wang
87de9cec0a wip 2022-10-18 18:58:26 -04:00
Tiger Wang
6d47d4ff18 wip 2022-10-18 17:30:00 -04:00
LinkLeong
4bb81e4669 Merge branch 'v0.3.7' of https://github.com/IceWhaleTech/CasaOS into v0.3.7 2022-10-17 06:54:34 +01:00
LinkLeong
c05d837350 add update url 2022-10-17 06:53:23 +01:00
Tiger Wang
8908c39969 wip 2022-10-13 19:33:18 -04:00
Tiger Wang
df0f015944 wip 2022-10-13 16:09:19 -04:00
LinkLeong
46a37f0510 fix upload file 2022-10-13 11:32:30 +01:00
LinkLeong
6ea3cdb364 Utilization interface to supplement disk information 2022-10-13 04:45:17 +01:00
LinkLeong
be80d0cd95 Merge branch 'v0.3.7' of https://github.com/IceWhaleTech/CasaOS into v0.3.7 2022-10-13 04:32:13 +01:00
a624669980@163.com
296e88d099 Merge branch 'v0.3.7' of ssh://github.com/IceWhaleTech/CasaOS into v0.3.7 2022-10-13 11:16:52 +08:00
Tiger Wang
b61a3db611 wip 2022-10-12 16:12:14 -04:00
Tiger Wang
0f3d3e82f5 wip 2022-10-11 23:33:58 -04:00
Tiger Wang
dd66f73157 wip 2022-10-11 23:33:58 -04:00
Tiger Wang
cbbb907d6a wip 2022-10-11 23:33:58 -04:00
Tiger Wang
ff6cdb6fda wip 2022-10-11 23:33:58 -04:00
Tiger Wang
2eac040875 update CasaOS-Common to fix runtime error 2022-10-11 23:33:54 -04:00
Tiger Wang
b41d855f73 change service type to notify for systemd so its status is OK only when service is initialized successfully 2022-10-11 23:31:42 -04:00
Tiger Wang
182bc25343 wip 2022-10-11 23:31:42 -04:00
Tiger Wang
12d5e5db03 update goreleaser configuration 2022-10-11 23:31:42 -04:00
Tiger Wang
455d226dcd remove /DATA directory initialization - moved to local-storage (#578) 2022-10-11 23:31:42 -04:00
LinkLeong
f0448cd1b9 remove temp path 2022-10-11 23:31:42 -04:00
LinkLeong
aff18fa091 add share function to common 2022-10-11 23:31:42 -04:00
LinkLeong
80c347ac01 update http status 2022-10-11 23:31:42 -04:00
LinkLeong
8113f51cf7 remove disk and test common package 2022-10-11 23:31:42 -04:00
LinkLeong
4f491fa22f add system notiry 2022-10-11 23:31:42 -04:00
LinkLeong
3935489d8b add shell script 2022-10-11 23:31:37 -04:00
LinkLeong
d14381e6a2 add send notify function 2022-10-11 23:28:25 -04:00
Tiger Wang
42ebd5f325 wip 2022-10-11 00:19:02 -04:00
Tiger Wang
a51bf70b79 update CasaOS-Common to fix runtime error 2022-09-29 00:05:12 -04:00
Tiger Wang
3787c7bf99 change service type to notify for systemd so its status is OK only when service is initialized successfully 2022-09-28 18:19:31 -04:00
Tiger Wang
ec7f6573ad wip 2022-09-28 17:56:28 -04:00
LinkLeong
466350dd21 update CasaOS-Common 2022-09-13 07:02:21 +01:00
LinkLeong
fb39529e8f update common package 2022-09-10 01:00:01 +01:00
LinkLeong
4434ba522b update upgrade script address 2022-09-09 07:36:49 +01:00
LinkLeong
aac8fe85ba update the way environment variables are displayed 2022-09-09 06:46:51 +01:00
36 changed files with 905 additions and 609 deletions

View File

@@ -28,6 +28,10 @@ jobs:
-
name: Fetch all tags
run: git fetch --force --tags
- name: Get version
id: get_version
run: echo ::set-output name=VERSION::${GITHUB_REF/refs\/tags\//}
-
name: Set up Go
uses: actions/setup-go@v2
@@ -45,3 +49,18 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Your GoReleaser Pro key, if you are using the 'goreleaser-pro' distribution
# GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }}
- name: Upload to oss
id: upload_to_oss
uses: tvrcgo/upload-to-oss@master
with:
key-id: ${{ secrets.OSS_KEY_ID }}
key-secret: ${{ secrets.OSS_KEY_SECRET }}
region: oss-cn-shanghai
bucket: casaos
assets: |
dist/checksums.txt:/IceWhaleTech/CasaOS/releases/download/${{ steps.get_version.outputs.VERSION }}/checksums.txt
dist/linux-arm-7-casaos-${{ steps.get_version.outputs.VERSION }}.tar.gz:/IceWhaleTech/CasaOS/releases/download/${{ steps.get_version.outputs.VERSION }}/linux-arm-7-casaos-${{ steps.get_version.outputs.VERSION }}.tar.gz
dist/linux-arm64-casaos-${{ steps.get_version.outputs.VERSION }}.tar.gz:/IceWhaleTech/CasaOS/releases/download/${{ steps.get_version.outputs.VERSION }}/linux-arm64-casaos-${{ steps.get_version.outputs.VERSION }}.tar.gz
dist/linux-amd64-casaos-${{ steps.get_version.outputs.VERSION }}.tar.gz:/IceWhaleTech/CasaOS/releases/download/${{ steps.get_version.outputs.VERSION }}/linux-amd64-casaos-${{ steps.get_version.outputs.VERSION }}.tar.gz

167
.goreleaser.debug.yaml Normal file
View File

@@ -0,0 +1,167 @@
# This is an example .goreleaser.yml file with some sensible defaults.
# Make sure to check the documentation at https://goreleaser.com
project_name: casaos
before:
hooks:
# You may remove this if you don't use go modules.
- go mod tidy
builds:
- id: casaos-amd64
binary: build/sysroot/usr/bin/casaos
env:
- CGO_ENABLED=1
- CC=x86_64-linux-gnu-gcc
gcflags:
- all=-N -l
ldflags:
- -extldflags "-static"
tags:
- musl
- netgo
goos:
- linux
goarch:
- amd64
hooks:
post:
- find build/sysroot -type f | xargs -L 1 realpath --relative-to=build/sysroot > build/sysroot.manifest
- id: casaos-arm64
binary: build/sysroot/usr/bin/casaos
env:
- CGO_ENABLED=1
- CC=aarch64-linux-gnu-gcc
gcflags:
- all=-N -l
ldflags:
- -extldflags "-static"
tags:
- musl
- netgo
goos:
- linux
goarch:
- arm64
hooks:
post:
- find build/sysroot -type f | xargs -L 1 realpath --relative-to=build/sysroot > build/sysroot.manifest
- id: casaos-arm-7
binary: build/sysroot/usr/bin/casaos
env:
- CGO_ENABLED=1
- CC=arm-linux-gnueabihf-gcc
gcflags:
- all=-N -l
ldflags:
- -extldflags "-static"
tags:
- musl
- netgo
goos:
- linux
goarch:
- arm
goarm:
- "7"
hooks:
post:
- find build/sysroot -type f | xargs -L 1 realpath --relative-to=build/sysroot > build/sysroot.manifest
- id: casaos-migration-tool-amd64
binary: build/sysroot/usr/bin/casaos-migration-tool
main: ./cmd/migration-tool
env:
- CGO_ENABLED=1
- CC=x86_64-linux-gnu-gcc
gcflags:
- all=-N -l
ldflags:
- -extldflags "-static"
tags:
- musl
- netgo
goos:
- linux
goarch:
- amd64
- id: casaos-migration-tool-arm64
binary: build/sysroot/usr/bin/casaos-migration-tool
main: ./cmd/migration-tool
env:
- CGO_ENABLED=1
- CC=aarch64-linux-gnu-gcc
gcflags:
- all=-N -l
ldflags:
- -extldflags "-static"
tags:
- musl
- netgo
goos:
- linux
goarch:
- arm64
- id: casaos-migration-tool-arm-7
binary: build/sysroot/usr/bin/casaos-migration-tool
main: ./cmd/migration-tool
env:
- CGO_ENABLED=1
- CC=arm-linux-gnueabihf-gcc
gcflags:
- all=-N -l
ldflags:
- -extldflags "-static"
tags:
- musl
- netgo
goos:
- linux
goarch:
- arm
goarm:
- "7"
archives:
- name_template: "{{ .Os }}-{{ .Arch }}-{{ .ProjectName }}-v{{ .Version }}"
id: casaos
builds:
- casaos-amd64
- casaos-arm64
- casaos-arm-7
replacements:
arm: arm-7
files:
- build/**/*
- name_template: "{{ .Os }}-{{ .Arch }}-{{ .ProjectName }}-migration-tool-v{{ .Version }}"
id: casaos-migration-tool
builds:
- casaos-migration-tool-amd64
- casaos-migration-tool-arm64
- casaos-migration-tool-arm-7
replacements:
arm: arm-7
files:
- build/sysroot/etc/**/*
checksum:
name_template: "checksums.txt"
snapshot:
name_template: "{{ incpatch .Version }}"
changelog:
sort: asc
filters:
exclude:
- "^docs:"
- "^test:"
# release:
# github:
# owner: IceWhaleTech
# name: CasaOS
# draft: true
# prerelease: auto
# mode: replace
# name_template: "v{{ .Version }}"
release:
github:
owner: IceWhaleTech
name: CasaOS
draft: true
prerelease: auto
mode: replace
name_template: "v{{ .Version }}"

View File

@@ -18,6 +18,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
## [0.3.7.1] 2022-11-04
### Fixed
- Fix memory leak issue ([#658](https://github.com/IceWhaleTech/CasaOS/issues/658)[#646](https://github.com/IceWhaleTech/CasaOS/issues/646))
- Solve the problem of local application import failure ([#490](https://github.com/IceWhaleTech/CasaOS/issues/490))
## [0.3.7] 2022-10-28
### Added
- [Storage] Disk merge (Beta), you can merge multiple disks into a single storage space (currently you need to enable this feature from the command line)
### Changed
- [Files] Changed the cache file storage location, now the file upload size is not limited by the system disk capacity.
- [Scripts] Updated installation and upgrade scripts to support more Debian-based Linux distributions.
- [Engineering] Refactored Local Storage into a standalone service as part of CasaOS modularization.
### Fixed
- [Apps] App list update mechanism improved, now you can see the latest apps in App Store immediately.
- [Storage] Fixed a lot of known issues
## [0.3.6-alpha.1] - 2022-09-06

View File

@@ -60,8 +60,6 @@ BUILD_PATH=$(dirname "${BASH_SOURCE[0]}")/../../..
SOURCE_ROOT=${BUILD_PATH}/sysroot
APP_NAME="casaos"
APP_NAME_FORMAL="CasaOS"
#APP_NAME_FORMAL="casaos-alpha"
# check if migration is needed
SOURCE_BIN_PATH=${SOURCE_ROOT}/usr/bin
@@ -85,45 +83,6 @@ if [ "${NEED_MIGRATION}" = "false" ]; then
exit 0
fi
MIGRATION_SERVICE_DIR=${1}
if [ -z "${MIGRATION_SERVICE_DIR}" ]; then
MIGRATION_SERVICE_DIR=${BUILD_PATH}/scripts/migration/service.d/${APP_NAME}
fi
MIGRATION_LIST_FILE=${MIGRATION_SERVICE_DIR}/migration.list
MIGRATION_PATH=()
CURRENT_VERSION_FOUND="false"
# a VERSION_PAIR looks like "v0.3.5 v0.3.6-alpha2"
#
# - "v0.3.5" is the current version installed on this host
# - "v0.3.6-alpha2" is the version of the migration tool from GitHub
while read -r VERSION_PAIR; do
if [ -z "${VERSION_PAIR}" ]; then
continue
fi
# obtain "v0.3.5" from "v0.3.5 v0.3.6-alpha2"
VER1=$(echo "${VERSION_PAIR}" | cut -d' ' -f1)
# obtain "v0.3.6-alpha2" from "v0.3.5 v0.3.6-alpha2"
VER2=$(echo "${VERSION_PAIR}" | cut -d' ' -f2)
if [ "${CURRENT_VERSION}" = "${VER1// /}" ] || [ "${CURRENT_VERSION}" = "LEGACY_WITHOUT_VERSION" ]; then
CURRENT_VERSION_FOUND="true"
fi
if [ "${CURRENT_VERSION_FOUND}" = "true" ]; then
MIGRATION_PATH+=("${VER2// /}")
fi
done < "${MIGRATION_LIST_FILE}"
if [ ${#MIGRATION_PATH[@]} -eq 0 ]; then
__warning "No migration path found from ${CURRENT_VERSION} to ${SOURCE_VERSION}"
exit 0
fi
ARCH="unknown"
case $(uname -m) in
@@ -141,22 +100,59 @@ case $(uname -m) in
;;
esac
__info "ARCH: ${ARCH}"
MIGRATION_SERVICE_DIR=${1}
if [ -z "${MIGRATION_SERVICE_DIR}" ]; then
MIGRATION_SERVICE_DIR=${BUILD_PATH}/scripts/migration/service.d/${APP_NAME}
fi
MIGRATION_LIST_FILE=${MIGRATION_SERVICE_DIR}/migration.list
MIGRATION_PATH=()
CURRENT_VERSION_FOUND="false"
# a VERSION_PAIR looks like "v0.3.5 <url>"
#
# - "v0.3.5" is the current version installed on this host
# - "<url>" is the url of the migration tool
while read -r VERSION_PAIR; do
if [ -z "${VERSION_PAIR}" ]; then
continue
fi
# obtain "v0.3.5" from "v0.3.5 v0.3.6-alpha2"
VER1=$(echo "${VERSION_PAIR}" | cut -d' ' -f1)
# obtain "<url>" from "v0.3.5 <url>"
URL=$(eval echo "${VERSION_PAIR}" | cut -d' ' -f2)
if [ "${CURRENT_VERSION}" = "${VER1// /}" ] || [ "${CURRENT_VERSION}" = "LEGACY_WITHOUT_VERSION" ]; then
CURRENT_VERSION_FOUND="true"
fi
if [ "${CURRENT_VERSION_FOUND}" = "true" ]; then
MIGRATION_PATH+=("${URL// /}")
fi
done < "${MIGRATION_LIST_FILE}"
if [ ${#MIGRATION_PATH[@]} -eq 0 ]; then
__warning "No migration path found from ${CURRENT_VERSION} to ${SOURCE_VERSION}"
exit 0
fi
pushd "${MIGRATION_SERVICE_DIR}"
{ for VER2 in "${MIGRATION_PATH[@]}"; do
MIGRATION_TOOL_FILE=linux-"${ARCH}"-"${APP_NAME}"-migration-tool-"${VER2}".tar.gz
{ for URL in "${MIGRATION_PATH[@]}"; do
MIGRATION_TOOL_FILE=$(basename "${URL}")
if [ -f "${MIGRATION_TOOL_FILE}" ]; then
__info "Migration tool ${MIGRATION_TOOL_FILE} exists. Skip downloading."
continue
fi
# MIGRATION_TOOL_URL=http://192.168.2.197:8000/v1/package/migration?type=release&name="${APP_NAME_FORMAL}"&version=${VER2}&arch=${ARCH}
MIGRATION_TOOL_URL=https://github.com/IceWhaleTech/"${APP_NAME_FORMAL}"/releases/download/"${VER2}"/linux-"${ARCH}"-"${APP_NAME}"-migration-tool-"${VER2}".tar.gz
echo "Dowloading ${MIGRATION_TOOL_URL}..."
curl -sL -O "${MIGRATION_TOOL_URL}"
__info "Dowloading ${URL}..."
curl -fsSL -o "${MIGRATION_TOOL_FILE}" -O "${URL}"
done
} || {
popd
@@ -164,8 +160,8 @@ pushd "${MIGRATION_SERVICE_DIR}"
}
{
for VER2 in "${MIGRATION_PATH[@]}"; do
MIGRATION_TOOL_FILE=linux-"${ARCH}"-"${APP_NAME}"-migration-tool-"${VER2}".tar.gz
for URL in "${MIGRATION_PATH[@]}"; do
MIGRATION_TOOL_FILE=$(basename "${URL}")
__info "Extracting ${MIGRATION_TOOL_FILE}..."
tar zxvf "${MIGRATION_TOOL_FILE}" || __error "Failed to extract ${MIGRATION_TOOL_FILE}"

View File

@@ -1,4 +1,3 @@
LEGACY_WITHOUT_VERSION v0.3.6
v0.3.5 v0.3.6
v0.3.5.1 v0.3.6
v0.3.6 v0.3.7
LEGACY_WITHOUT_VERSION https://github.com/IceWhaleTech/CasaOS/releases/download/v0.3.6/linux-${ARCH}-casaos-migration-tool-v0.3.6.tar.gz
v0.3.5 https://github.com/IceWhaleTech/CasaOS/releases/download/v0.3.6/linux-${ARCH}-casaos-migration-tool-v0.3.6.tar.gz
v0.3.5.1 https://github.com/IceWhaleTech/CasaOS/releases/download/v0.3.6/linux-${ARCH}-casaos-migration-tool-v0.3.6.tar.gz

View File

@@ -31,15 +31,10 @@ if [ ! -f "${CONF_FILE}" ]; then
cp -v "${CONF_FILE_SAMPLE}" "${CONF_FILE}"
fi
if systemctl is-active "${APP_NAME}.service" &>/dev/null ;then
echo "server started"
else
# enable and start service
systemctl daemon-reload
rm -rf /etc/systemd/system/casaos.service # remove old service file
echo "Enabling service..."
systemctl enable --force --no-ask-password "${APP_NAME}.service"
systemctl daemon-reload
echo "Starting service..."
systemctl start --force --no-ask-password "${APP_NAME}.service"
fi
# enable service (without starting)
echo "Enabling service..."
systemctl enable --force --no-ask-password "${APP_NAME}.service"

View File

@@ -1,12 +1,13 @@
[Unit]
After=casaos-gateway.service
ConditionFileNotEmpty=/etc/casaos/casaos.conf
Description=CasaOS Service
Description=CasaOS Main Service
[Service]
ExecStart=/usr/bin/casaos -c /etc/casaos/casaos.conf
PIDFile=/var/run/casaos/casaos.pid
Restart=always
Type=notify
[Install]
WantedBy=multi-user.target

View File

@@ -0,0 +1,46 @@
#!/bin/bash
set -e
readonly APP_NAME_SHORT=casaos
__get_setup_script_directory_by_os_release() {
pushd "$(dirname "${BASH_SOURCE[0]}")/../service.d/${APP_NAME_SHORT}" &>/dev/null
{
# shellcheck source=/dev/null
{
source /etc/os-release
{
pushd "${ID}"/"${VERSION_CODENAME}" &>/dev/null
} || {
pushd "${ID}" &>/dev/null
} || {
pushd "${ID_LIKE}" &>/dev/null
} || {
echo "Unsupported OS: ${ID} ${VERSION_CODENAME} (${ID_LIKE})"
exit 1
}
pwd
popd &>/dev/null
} || {
echo "Unsupported OS: unknown"
exit 1
}
}
popd &>/dev/null
}
SETUP_SCRIPT_DIRECTORY=$(__get_setup_script_directory_by_os_release)
readonly SETUP_SCRIPT_DIRECTORY
readonly SETUP_SCRIPT_FILENAME="cleanup-${APP_NAME_SHORT}.sh"
readonly SETUP_SCRIPT_FILEPATH="${SETUP_SCRIPT_DIRECTORY}/${SETUP_SCRIPT_FILENAME}"
echo "🟩 Running ${SETUP_SCRIPT_FILENAME}..."
$SHELL "${SETUP_SCRIPT_FILEPATH}" "${BUILD_PATH}"

View File

@@ -0,0 +1 @@
../cleanup-casaos.sh

View File

@@ -0,0 +1,204 @@
#!/bin/bash
set -e
readonly CASA_SERVICES=(
"casaos.service"
"devmon@devmon.service"
)
readonly CASA_EXEC=casaos
readonly CASA_CONF=/etc/casaos/casaos.conf
readonly CASA_URL=/var/run/casaos/casaos.url
readonly CASA_SERVICE_USR=/usr/lib/systemd/system/casaos.service
readonly CASA_SERVICE_LIB=/lib/systemd/system/casaos.service
readonly CASA_SERVICE_ETC=/etc/systemd/system/casaos.service
# Old Casa Files
readonly CASA_PATH=/casaOS
readonly CASA_CONF_PATH_OLD=/etc/casaos.conf
readonly aCOLOUR=(
'\e[38;5;154m' # green | Lines, bullets and separators
'\e[1m' # Bold white | Main descriptions
'\e[90m' # Grey | Credits
'\e[91m' # Red | Update notifications Alert
'\e[33m' # Yellow | Emphasis
)
Show() {
# OK
if (($1 == 0)); then
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[0]} OK $COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
# FAILED
elif (($1 == 1)); then
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[3]}FAILED$COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
# INFO
elif (($1 == 2)); then
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[0]} INFO $COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
# NOTICE
elif (($1 == 3)); then
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[4]}NOTICE$COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
fi
}
Warn() {
echo -e "${aCOLOUR[3]}$1$COLOUR_RESET"
}
trap 'onCtrlC' INT
onCtrlC() {
echo -e "${COLOUR_RESET}"
exit 1
}
Detecting_CasaOS() {
if [[ ! -x "$(command -v ${CASA_EXEC})" ]]; then
Show 2 "CasaOS is not detected, exit the script."
exit 1
else
Show 0 "This script will delete the containers you no longer use, and the CasaOS configuration files."
fi
}
Uninstall_Container() {
if [[ ${UNINSTALL_ALL_CONTAINER} == true && "$(docker ps -aq)" != "" ]]; then
Show 2 "Start deleting containers."
docker stop "$(docker ps -aq)" || Show 1 "Failed to stop all containers."
docker rm "$(docker ps -aq)" || Show 1 "Failed to delete all containers."
fi
}
Remove_Images() {
if [[ ${REMOVE_IMAGES} == "all" && "$(docker images -q)" != "" ]]; then
Show 2 "Start deleting all images."
docker rmi "$(docker images -q)" || Show 1 "Failed to delete all images."
elif [[ ${REMOVE_IMAGES} == "unuse" && "$(docker images -q)" != "" ]]; then
Show 2 "Start deleting unuse images."
docker image prune -af || Show 1 "Failed to delete unuse images."
fi
}
Uninstall_Casaos() {
for SERVICE in "${CASA_SERVICES[@]}"; do
Show 2 "Stopping ${SERVICE}..."
systemctl disable --now "${SERVICE}" || Show 3 "Failed to disable ${SERVICE}"
done
# Remove Service file
if [[ -f ${CASA_SERVICE_USR} ]]; then
rm -rvf ${CASA_SERVICE_USR}
fi
if [[ -f ${CASA_SERVICE_LIB} ]]; then
rm -rvf ${CASA_SERVICE_LIB}
fi
if [[ -f ${CASA_SERVICE_ETC} ]]; then
rm -rvf ${CASA_SERVICE_ETC}
fi
# Old Casa Files
if [[ -d ${CASA_PATH} ]]; then
rm -rvf ${CASA_PATH} || Show 1 "Failed to delete legacy CasaOS files."
fi
if [[ -f ${CASA_CONF_PATH_OLD} ]]; then
rm -rvf ${CASA_CONF_PATH_OLD}
fi
# New Casa Files
if [[ ${REMOVE_APP_DATA} = true ]]; then
rm -rvf /DATA/AppData || Show 1 "Failed to delete AppData."
fi
rm -rvf "$(which ${CASA_EXEC})" || Show 3 "Failed to remove ${CASA_EXEC}"
rm -rvf ${CASA_CONF} || Show 3 "Failed to remove ${CASA_CONF}"
rm -rvf ${CASA_URL} || Show 3 "Failed to remove ${CASA_URL}"
rm -rvf /var/lib/casaos/app_category.json
rm -rvf /var/lib/casaos/app_list.json
rm -rvf /var/lib/casaos/docker_root
}
Detecting_CasaOS
while true; do
echo -n -e " ${aCOLOUR[4]}Do you want delete all containers? Y/n :${COLOUR_RESET}"
read -r input
case $input in
[yY][eE][sS] | [yY])
UNINSTALL_ALL_CONTAINER=true
break
;;
[nN][oO] | [nN])
UNINSTALL_ALL_CONTAINER=false
break
;;
*)
Warn " Invalid input..."
;;
esac
done
if [[ ${UNINSTALL_ALL_CONTAINER} == true ]]; then
while true; do
echo -n -e " ${aCOLOUR[4]}Do you want delete all images? Y/n :${COLOUR_RESET}"
read -r input
case $input in
[yY][eE][sS] | [yY])
REMOVE_IMAGES="all"
break
;;
[nN][oO] | [nN])
REMOVE_IMAGES="none"
break
;;
*)
Warn " Invalid input..."
;;
esac
done
while true; do
echo -n -e " ${aCOLOUR[4]}Do you want delete all AppData of CasaOS? Y/n :${COLOUR_RESET}"
read -r input
case $input in
[yY][eE][sS] | [yY])
REMOVE_APP_DATA=true
break
;;
[nN][oO] | [nN])
REMOVE_APP_DATA=false
break
;;
*)
Warn " Invalid input..."
;;
esac
done
else
while true; do
echo -n -e " ${aCOLOUR[4]}Do you want to delete all images that are not used by the container? Y/n :${COLOUR_RESET}"
read -r input
case $input in
[yY][eE][sS] | [yY])
REMOVE_IMAGES="unuse"
break
;;
[nN][oO] | [nN])
REMOVE_IMAGES="none"
break
;;
*)
Warn " Invalid input..."
;;
esac
done
fi
Uninstall_Container
Remove_Images
Uninstall_Casaos

View File

@@ -0,0 +1 @@
../debian/cleanup-casaos.sh

View File

@@ -0,0 +1 @@
../../debian/bullseye/cleanup-casaos.sh

View File

@@ -9,4 +9,4 @@
###
curl -fsSL https://raw.githubusercontent.com/LinkLeong/casaos-alpha/main/new.update.sh | bash
curl -fsSL https://raw.githubusercontent.com/IceWhaleTech/get/main/update.sh | bash

View File

@@ -83,8 +83,7 @@ func main() {
}
migrationTools := []interfaces.MigrationTool{
NewMigrationToolFor_035(),
NewMigrationToolFor_036(),
// nothing to migrate from last version
}
var selectedMigrationTool interfaces.MigrationTool
@@ -115,8 +114,7 @@ func main() {
panic(err)
}
selectedMigrationTool.PostMigrate()
_logger.Info("casaos migration ok")
// panic(err)
if err := selectedMigrationTool.PostMigrate(); err != nil {
_logger.Error("Migration succeeded, but post-migration failed: %s", err)
}
}

View File

@@ -1,182 +0,0 @@
/*
* @Author: LinkLeong link@icewhale.org
* @Date: 2022-08-24 17:36:00
* @LastEditors: LinkLeong
* @LastEditTime: 2022-09-05 11:24:27
* @FilePath: /CasaOS/cmd/migration-tool/migration-034-035.go
* @Description:
* @Website: https://www.casaos.io
* Copyright (c) 2022 by icewhale, All Rights Reserved.
*/
package main
import (
"io"
"io/ioutil"
"os"
"path"
"strings"
interfaces "github.com/IceWhaleTech/CasaOS-Common"
"github.com/IceWhaleTech/CasaOS-Common/utils/version"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/utils/command"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS/service"
)
type migrationTool036 struct{}
func (u *migrationTool036) IsMigrationNeeded() (bool, error) {
majorVersion, minorVersion, patchVersion, err := version.DetectLegacyVersion()
if err != nil {
if err == version.ErrLegacyVersionNotFound {
return false, nil
}
return false, err
}
if majorVersion > 0 {
return false, nil
}
if minorVersion > 3 {
return false, nil
}
if minorVersion == 3 && patchVersion > 5 {
return false, nil
}
_logger.Info("Migration is needed for a CasaOS version 0.3.5 and older...")
return true, nil
}
func (u *migrationTool036) PreMigrate() error {
return nil
}
func (u *migrationTool036) Migrate() error {
if service.MyService.System().GetSysInfo().KernelArch == "aarch64" && config.ServerInfo.USBAutoMount != "True" && strings.Contains(service.MyService.System().GetDeviceTree(), "Raspberry Pi") {
service.MyService.System().UpdateUSBAutoMount("False")
service.MyService.System().ExecUSBAutoMountShell("False")
}
newAPIUrl := "https://api.casaos.io/casaos-api"
if config.ServerInfo.ServerApi == "https://api.casaos.zimaboard.com" {
config.ServerInfo.ServerApi = newAPIUrl
config.Cfg.Section("server").Key("ServerApi").SetValue(newAPIUrl)
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
}
command.OnlyExec("curl -fsSL https://raw.githubusercontent.com/IceWhaleTech/get/main/assist.sh | bash")
if !file.CheckNotExist("/casaOS") {
command.OnlyExec("source /casaOS/server/shell/update.sh ;")
command.OnlyExec("source " + config.AppInfo.ShellPath + "/delete-old-service.sh ;")
}
service.MyService.App().ImportApplications(true)
src := "/casaOS/server/conf/conf.ini"
if file.Exists(src) {
dst := "/etc/casaos/casaos.conf"
source, err := os.Open(src)
if err != nil {
return err
}
defer source.Close()
destination, err := os.Create(dst)
if err != nil {
return err
}
defer destination.Close()
_, err = io.Copy(destination, source)
if err != nil {
return err
}
}
if file.Exists("/casaOS/server/db") {
var fds []os.FileInfo
var err error
to := "/var/lib/casaos/db"
file.IsNotExistMkDir(to)
from := "/casaOS/server/db"
if fds, err = ioutil.ReadDir(from); err != nil {
return err
}
for _, fd := range fds {
srcfp := path.Join(from, fd.Name())
dstfp := path.Join(to, fd.Name())
source, err := os.Open(srcfp)
if err != nil {
return err
}
defer source.Close()
destination, err := os.Create(dstfp)
if err != nil {
return err
}
defer destination.Close()
_, err = io.Copy(destination, source)
if err != nil {
return err
}
}
}
if file.Exists("/casaOS/server/conf") {
var fds []os.FileInfo
var err error
to := "/var/lib/casaos/conf"
file.IsNotExistMkDir(to)
from := "/casaOS/server/conf"
if fds, err = ioutil.ReadDir(from); err != nil {
return err
}
for _, fd := range fds {
fExt := path.Ext(fd.Name())
if fExt != ".json" {
continue
}
srcfp := path.Join(from, fd.Name())
dstfp := path.Join(to, fd.Name())
source, err := os.Open(srcfp)
if err != nil {
return err
}
defer source.Close()
destination, err := os.Create(dstfp)
if err != nil {
return err
}
defer destination.Close()
_, err = io.Copy(destination, source)
if err != nil {
return err
}
}
}
_logger.Info("update done")
return nil
}
func (u *migrationTool036) PostMigrate() error {
return nil
}
func NewMigrationToolFor_035() interfaces.MigrationTool {
return &migrationTool{}
}

View File

@@ -11,18 +11,13 @@
package main
import (
"strings"
interfaces "github.com/IceWhaleTech/CasaOS-Common"
"github.com/IceWhaleTech/CasaOS-Common/utils/version"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/service"
)
type migrationTool struct{}
func (u *migrationTool) IsMigrationNeeded() (bool, error) {
majorVersion, minorVersion, patchVersion, err := version.DetectLegacyVersion()
if err != nil {
if err == version.ErrLegacyVersionNotFound {
@@ -46,22 +41,13 @@ func (u *migrationTool) IsMigrationNeeded() (bool, error) {
_logger.Info("Migration is needed for a CasaOS version 0.3.5 and older...")
return true, nil
}
func (u *migrationTool) PreMigrate() error {
return nil
}
func (u *migrationTool) Migrate() error {
if service.MyService.System().GetSysInfo().KernelArch == "aarch64" && config.ServerInfo.USBAutoMount != "True" && strings.Contains(service.MyService.System().GetDeviceTree(), "Raspberry Pi") {
service.MyService.System().UpdateUSBAutoMount("False")
service.MyService.System().ExecUSBAutoMountShell("False")
}
_logger.Info("update done")
return nil
}

3
go.mod
View File

@@ -4,13 +4,14 @@ go 1.16
require (
github.com/Curtis-Milo/nat-type-identifier-go v0.0.0-20220215191915-18d42168c63d
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220901034123-ca130f6b5ce9
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220929035515-b1287110d6d8
github.com/IceWhaleTech/CasaOS-Gateway v0.3.6
github.com/Microsoft/go-winio v0.5.0 // indirect
github.com/ambelovsky/go-structs v1.1.0 // indirect
github.com/ambelovsky/gosf v0.0.0-20201109201340-237aea4d6109
github.com/ambelovsky/gosf-socketio v0.0.0-20201109193639-add9d32f8b19 // indirect
github.com/containerd/containerd v1.5.7 // indirect
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e
github.com/disintegration/imaging v1.6.2
github.com/docker/distribution v2.8.0+incompatible // indirect
github.com/docker/docker v20.10.7+incompatible

3
go.sum
View File

@@ -83,8 +83,9 @@ github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym
github.com/Curtis-Milo/nat-type-identifier-go v0.0.0-20220215191915-18d42168c63d h1:62lEBImTxZ83pgzywgDNIrPPuQ+j4ep9QjqrWBn1hrU=
github.com/Curtis-Milo/nat-type-identifier-go v0.0.0-20220215191915-18d42168c63d/go.mod h1:lW9x+yEjqKdPbE3+cf2fGPJXCw/hChX3Omi9QHTLFsQ=
github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220901034123-ca130f6b5ce9 h1:q4I/lSsCooxdd6LxinGy90y0n6V8EcaPBV1JCfpEnV4=
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220901034123-ca130f6b5ce9/go.mod h1:2MiivEMzvh41codhEKUcn46WK3Ffesop/04qa9jsvQk=
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220929035515-b1287110d6d8 h1:r8nhgQ6tnrn6ikXN9aLH/K4H4H64Nc0hZ6jyW2B22x0=
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220929035515-b1287110d6d8/go.mod h1:2MiivEMzvh41codhEKUcn46WK3Ffesop/04qa9jsvQk=
github.com/IceWhaleTech/CasaOS-Gateway v0.3.6 h1:2tQQo85+jzbbjqIsKKn77QlAA73bc7vZsVCFvWnK4mg=
github.com/IceWhaleTech/CasaOS-Gateway v0.3.6/go.mod h1:hnZwGUzcOyiufMpVO7l3gu2gAm6Ws4TY4Nlj3kMshXA=
github.com/Microsoft/go-winio v0.4.11/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA=

24
main.go
View File

@@ -18,6 +18,7 @@ import (
"github.com/IceWhaleTech/CasaOS/route"
"github.com/IceWhaleTech/CasaOS/service"
"github.com/IceWhaleTech/CasaOS/types"
"github.com/coreos/go-systemd/daemon"
"go.uber.org/zap"
"github.com/robfig/cron"
@@ -135,14 +136,6 @@ func main() {
}
}()
// s := &http.Server{
// Addr: listener.Addr().String(), //fmt.Sprintf(":%v", config.ServerInfo.HttpPort),
// Handler: r,
// ReadTimeout: 60 * time.Second,
// WriteTimeout: 60 * time.Second,
// MaxHeaderBytes: 1 << 20,
// }
// s.ListenAndServe()
urlFilePath := filepath.Join(config.CommonInfo.RuntimePath, "casaos.url")
err = file.CreateFileAndWriteContent(urlFilePath, "http://"+listener.Addr().String())
if err != nil {
@@ -152,7 +145,20 @@ func main() {
)
}
err = http.Serve(listener, r)
if supported, err := daemon.SdNotify(false, daemon.SdNotifyReady); err != nil {
loger.Error("Failed to notify systemd that casaos main service is ready", zap.Any("error", err))
} else if supported {
loger.Info("Notified systemd that casaos main service is ready")
} else {
loger.Info("This process is not running as a systemd service.")
}
s := &http.Server{
Handler: r,
ReadHeaderTimeout: 5 * time.Second, // fix G112: Potential slowloris attack (see https://github.com/securego/gosec)
}
err = s.Serve(listener) // not using http.serve() to fix G114: Use of net/http serve function that has no support for setting timeouts (see https://github.com/securego/gosec)
if err != nil {
panic(err)
}

View File

@@ -1,62 +0,0 @@
/*
* @Author: LinkLeong link@icewhale.com
* @Date: 2021-10-08 10:29:08
* @LastEditors: LinkLeong
* @LastEditTime: 2022-07-22 11:06:07
* @FilePath: /CasaOS/middleware/gin.go
* @Description:
* @Website: https://www.casaos.io
* Copyright (c) 2022 by icewhale, All Rights Reserved.
*/
package middleware
import (
"fmt"
"net/http"
"strings"
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
//允许跨域设置可以返回其他子段,可以自定义字段
c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,Language,Content-Type,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Access-Control-Allow-Methods,Connection,Host,Origin,Referer,User-Agent,X-Requested-With")
// 允许浏览器(客户端)可以解析的头部 (重要)
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
//c.Writer.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, Content-Length, X-CSRF-Token, Token, session, Origin, Host, Connection, Accept-Encoding, Accept-Language, X-Requested-With")
//设置缓存时间
c.Header("Access-Control-Max-Age", "172800")
c.Header("Access-Control-Allow-Credentials", "true")
c.Set("Content-Type", "application/json")
//}
//允许类型校验
if method == "OPTIONS" {
c.JSON(http.StatusOK, "ok!")
}
defer func() {
if err := recover(); err != nil {
fmt.Println(err)
}
}()
c.Next()
}
}
func WriteLog() gin.HandlerFunc {
return func(c *gin.Context) {
if !strings.Contains(c.Request.URL.String(), "password") {
loger.Info("request:", zap.Any("path", c.Request.URL.String()), zap.Any("param", c.Params), zap.Any("query", c.Request.URL.Query()), zap.Any("method", c.Request.Method))
c.Next()
}
}
}

View File

@@ -17,6 +17,8 @@ type DockerStatsModel struct {
Previous interface{} `json:"previous"`
}
type DeckerDaemonModel struct {
Graph string `json:"graph"`
// reference - https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-configuration-file
type DockerDaemonConfigurationModel struct {
// e.g. `/var/lib/docker`
Root string `json:"data-root,omitempty"`
}

View File

@@ -26,6 +26,7 @@ type ServerModel struct {
Token string
USBAutoMount string
SocketPort string
UpdateUrl string
}
// 服务配置
@@ -73,3 +74,8 @@ type FileSetting struct {
ShareDir []string `json:"share_dir" delim:"|"`
DownloadDir string `json:"download_dir"`
}
type BaseInfo struct {
Hash string `json:"i"`
Version string `json:"v"`
Channel string `json:"c,omitempty"`
}

View File

@@ -15,7 +15,6 @@ import (
)
func NewSshClient(user, password string, port string) (*ssh.Client, error) {
// connet to ssh
// addr = fmt.Sprintf("%s:%d", host, port)
@@ -23,10 +22,10 @@ func NewSshClient(user, password string, port string) (*ssh.Client, error) {
Timeout: time.Second * 5,
User: user,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
//HostKeyCallback: ,
//HostKeyCallback: hostKeyCallBackFunc(h.Host),
// HostKeyCallback: ,
// HostKeyCallback: hostKeyCallBackFunc(h.Host),
}
//if h.Type == "password" {
// if h.Type == "password" {
config.Auth = []ssh.AuthMethod{ssh.Password(password)}
//} else {
// config.Auth = []ssh.AuthMethod{publicKeyAuthFunc(h.Key)}
@@ -90,11 +89,11 @@ func (w *wsBufferWriter) Write(p []byte) (int, error) {
defer w.mu.Unlock()
return w.buffer.Write(p)
}
func (s *SshConn) Close() {
if s.Session != nil {
s.Session.Close()
}
}
const (
@@ -102,16 +101,15 @@ const (
wsMsgResize = "resize"
)
//ReceiveWsMsg receive websocket msg do some handling then write into ssh.session.stdin
// ReceiveWsMsg receive websocket msg do some handling then write into ssh.session.stdin
func ReceiveWsMsgUser(wsConn *websocket.Conn, logBuff *bytes.Buffer) string {
//tells other go routine quit
// tells other go routine quit
username := ""
for {
//read websocket msg
// read websocket msg
_, wsData, err := wsConn.ReadMessage()
if err != nil {
return ""
}
@@ -125,8 +123,8 @@ func ReceiveWsMsgUser(wsConn *websocket.Conn, logBuff *bytes.Buffer) string {
//}
switch msgObj.Type {
case wsMsgCmd:
//handle xterm.js stdin
//decodeBytes, err := base64.StdEncoding.DecodeString(msgObj.Cmd)
// handle xterm.js stdin
// decodeBytes, err := base64.StdEncoding.DecodeString(msgObj.Cmd)
decodeBytes := []byte(msgObj.Cmd)
if msgObj.Cmd == "\u007f" {
if len(username) == 0 {
@@ -144,7 +142,7 @@ func ReceiveWsMsgUser(wsConn *websocket.Conn, logBuff *bytes.Buffer) string {
if err := wsConn.WriteMessage(websocket.TextMessage, decodeBytes); err != nil {
logrus.WithError(err).Error("ws cmd bytes write to ssh.stdin pipe failed")
}
//write input cmd to log buffer
// write input cmd to log buffer
if _, err := logBuff.Write(decodeBytes); err != nil {
logrus.WithError(err).Error("write received cmd into log buffer failed")
}
@@ -154,11 +152,11 @@ func ReceiveWsMsgUser(wsConn *websocket.Conn, logBuff *bytes.Buffer) string {
}
func ReceiveWsMsgPassword(wsConn *websocket.Conn, logBuff *bytes.Buffer) string {
//tells other go routine quit
// tells other go routine quit
password := ""
for {
//read websocket msg
// read websocket msg
_, wsData, err := wsConn.ReadMessage()
if err != nil {
logrus.WithError(err).Error("reading webSocket message failed")
@@ -175,8 +173,8 @@ func ReceiveWsMsgPassword(wsConn *websocket.Conn, logBuff *bytes.Buffer) string
//}
switch msgObj.Type {
case wsMsgCmd:
//handle xterm.js stdin
//decodeBytes, err := base64.StdEncoding.DecodeString(msgObj.Cmd)
// handle xterm.js stdin
// decodeBytes, err := base64.StdEncoding.DecodeString(msgObj.Cmd)
if msgObj.Cmd == "\r" {
return password
}
@@ -194,16 +192,16 @@ func ReceiveWsMsgPassword(wsConn *websocket.Conn, logBuff *bytes.Buffer) string
}
}
//ReceiveWsMsg receive websocket msg do some handling then write into ssh.session.stdin
// ReceiveWsMsg receive websocket msg do some handling then write into ssh.session.stdin
func (ssConn *SshConn) ReceiveWsMsg(wsConn *websocket.Conn, logBuff *bytes.Buffer, exitCh chan bool) {
//tells other go routine quit
// tells other go routine quit
defer setQuit(exitCh)
for {
select {
case <-exitCh:
return
default:
//read websocket msg
// read websocket msg
_, wsData, err := wsConn.ReadMessage()
if err != nil {
logrus.WithError(err).Error("reading webSocket message failed")
@@ -227,15 +225,15 @@ func (ssConn *SshConn) ReceiveWsMsg(wsConn *websocket.Conn, logBuff *bytes.Buffe
switch msgObj.Type {
case wsMsgResize:
//handle xterm.js size change
// handle xterm.js size change
if msgObj.Cols > 0 && msgObj.Rows > 0 {
if err := ssConn.Session.WindowChange(msgObj.Rows, msgObj.Cols); err != nil {
logrus.WithError(err).Error("ssh pty change windows size failed")
}
}
case wsMsgCmd:
//handle xterm.js stdin
//decodeBytes, err := base64.StdEncoding.DecodeString(msgObj.Cmd)
// handle xterm.js stdin
// decodeBytes, err := base64.StdEncoding.DecodeString(msgObj.Cmd)
decodeBytes := []byte(msgObj.Cmd)
if err != nil {
logrus.WithError(err).Error("websock cmd string base64 decoding failed")
@@ -243,7 +241,7 @@ func (ssConn *SshConn) ReceiveWsMsg(wsConn *websocket.Conn, logBuff *bytes.Buffe
if _, err := ssConn.StdinPipe.Write(decodeBytes); err != nil {
logrus.WithError(err).Error("ws cmd bytes write to ssh.stdin pipe failed")
}
//write input cmd to log buffer
// write input cmd to log buffer
if _, err := logBuff.Write(decodeBytes); err != nil {
logrus.WithError(err).Error("write received cmd into log buffer failed")
}
@@ -253,17 +251,17 @@ func (ssConn *SshConn) ReceiveWsMsg(wsConn *websocket.Conn, logBuff *bytes.Buffe
}
func (ssConn *SshConn) SendComboOutput(wsConn *websocket.Conn, exitCh chan bool) {
//tells other go routine quit
//defer setQuit(exitCh)
// tells other go routine quit
// defer setQuit(exitCh)
//every 120ms write combine output bytes into websocket response
// every 120ms write combine output bytes into websocket response
tick := time.NewTicker(time.Millisecond * time.Duration(120))
//for range time.Tick(120 * time.Millisecond){}
// for range time.Tick(120 * time.Millisecond){}
defer tick.Stop()
for {
select {
case <-tick.C:
//write combine output bytes into websocket response
// write combine output bytes into websocket response
if err := flushComboOutput(ssConn.ComboOutput, wsConn); err != nil {
logrus.WithError(err).Error("ssh sending combo output to webSocket failed")
return
@@ -273,6 +271,7 @@ func (ssConn *SshConn) SendComboOutput(wsConn *websocket.Conn, exitCh chan bool)
}
}
}
func flushComboOutput(w *wsBufferWriter, wsConn *websocket.Conn) error {
if w.buffer.Len() != 0 {
err := wsConn.WriteMessage(websocket.TextMessage, w.buffer.Bytes())
@@ -284,16 +283,16 @@ func flushComboOutput(w *wsBufferWriter, wsConn *websocket.Conn) error {
return nil
}
//ReceiveWsMsg receive websocket msg do some handling then write into ssh.session.stdin
// ReceiveWsMsg receive websocket msg do some handling then write into ssh.session.stdin
func (ssConn *SshConn) Login(wsConn *websocket.Conn, logBuff *bytes.Buffer, exitCh chan bool) {
//tells other go routine quit
// tells other go routine quit
defer setQuit(exitCh)
for {
select {
case <-exitCh:
return
default:
//read websocket msg
// read websocket msg
_, wsData, err := wsConn.ReadMessage()
if err != nil {
logrus.WithError(err).Error("reading webSocket message failed")
@@ -317,15 +316,15 @@ func (ssConn *SshConn) Login(wsConn *websocket.Conn, logBuff *bytes.Buffer, exit
switch msgObj.Type {
case wsMsgResize:
//handle xterm.js size change
// handle xterm.js size change
if msgObj.Cols > 0 && msgObj.Rows > 0 {
if err := ssConn.Session.WindowChange(msgObj.Rows, msgObj.Cols); err != nil {
logrus.WithError(err).Error("ssh pty change windows size failed")
}
}
case wsMsgCmd:
//handle xterm.js stdin
//decodeBytes, err := base64.StdEncoding.DecodeString(msgObj.Cmd)
// handle xterm.js stdin
// decodeBytes, err := base64.StdEncoding.DecodeString(msgObj.Cmd)
decodeBytes := []byte(msgObj.Cmd)
if err != nil {
logrus.WithError(err).Error("websock cmd string base64 decoding failed")
@@ -333,7 +332,7 @@ func (ssConn *SshConn) Login(wsConn *websocket.Conn, logBuff *bytes.Buffer, exit
if _, err := ssConn.StdinPipe.Write(decodeBytes); err != nil {
logrus.WithError(err).Error("ws cmd bytes write to ssh.stdin pipe failed")
}
//write input cmd to log buffer
// write input cmd to log buffer
if _, err := logBuff.Write(decodeBytes); err != nil {
logrus.WithError(err).Error("write received cmd into log buffer failed")
}
@@ -341,6 +340,7 @@ func (ssConn *SshConn) Login(wsConn *websocket.Conn, logBuff *bytes.Buffer, exit
}
}
}
func (ssConn *SshConn) SessionWait(quitChan chan bool) {
if err := ssConn.Session.Wait(); err != nil {
logrus.WithError(err).Error("ssh session wait failed")
@@ -395,7 +395,7 @@ func WsReaderCopy(reader *websocket.Conn, writer io.Writer) {
if err = json2.Unmarshal(p, &msgObj); err != nil {
writer.Write(p)
} else if msgObj.Type == wsMsgResize {
//writer.Write([]byte("stty rows " + strconv.Itoa(msgObj.Rows) + " && stty cols " + strconv.Itoa(msgObj.Cols) + " \r"))
// writer.Write([]byte("stty rows " + strconv.Itoa(msgObj.Rows) + " && stty cols " + strconv.Itoa(msgObj.Cols) + " \r"))
}
}
}

View File

@@ -35,8 +35,8 @@ func ExecResultStrArray(cmdStr string) []string {
fmt.Println(err)
return nil
}
//str, err := ioutil.ReadAll(stdout)
var networklist = []string{}
// str, err := ioutil.ReadAll(stdout)
networklist := []string{}
outputBuf := bufio.NewReader(stdout)
for {
output, _, err := outputBuf.ReadLine()
@@ -54,6 +54,8 @@ func ExecResultStrArray(cmdStr string) []string {
func ExecResultStr(cmdStr string) string {
cmd := exec.Command("/bin/bash", "-c", cmdStr)
println(cmd.String())
stdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Println(err)
@@ -73,7 +75,7 @@ func ExecResultStr(cmdStr string) string {
return string(str)
}
//执行 lsblk 命令
// 执行 lsblk 命令
func ExecLSBLK() []byte {
output, err := exec.Command("lsblk", "-O", "-J", "-b").Output()
if err != nil {
@@ -83,7 +85,7 @@ func ExecLSBLK() []byte {
return output
}
//执行 lsblk 命令
// 执行 lsblk 命令
func ExecLSBLKByPath(path string) []byte {
output, err := exec.Command("lsblk", path, "-O", "-J", "-b").Output()
if err != nil {
@@ -93,7 +95,7 @@ func ExecLSBLKByPath(path string) []byte {
return output
}
//exec smart
// exec smart
func ExecSmartCTLByPath(path string) []byte {
timeout := 3
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
@@ -107,6 +109,5 @@ func ExecSmartCTLByPath(path string) []byte {
}
func ExecEnabledSMART(path string) {
exec.Command("smartctl", "-s on", path).Output()
}

View File

@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"io/ioutil"
"log"
"mime/multipart"
@@ -60,7 +61,7 @@ func MkDir(src string) error {
if err != nil {
return err
}
os.Chmod(src, 0777)
os.Chmod(src, 0o777)
return nil
}
@@ -103,7 +104,7 @@ func MustOpen(fileName, filePath string) (*os.File, error) {
return nil, fmt.Errorf("file.IsNotExistMkDir src: %s, err: %v", src, err)
}
f, err := Open(src+fileName, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644)
f, err := Open(src+fileName, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0o644)
if err != nil {
return nil, fmt.Errorf("Fail to OpenFile :%v", err)
}
@@ -113,7 +114,7 @@ func MustOpen(fileName, filePath string) (*os.File, error) {
// 判断所给路径文件/文件夹是否存在
func Exists(path string) bool {
_, err := os.Stat(path) //os.Stat获取文件信息
_, err := os.Stat(path) // os.Stat获取文件信息
if err != nil {
if os.IsExist(err) {
return true
@@ -147,7 +148,7 @@ func CreateFile(path string) error {
}
func CreateFileAndWriteContent(path string, content string) error {
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666)
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o666)
if err != nil {
return err
}
@@ -163,7 +164,7 @@ func CreateFileAndWriteContent(path string, content string) error {
// IsNotExistMkDir create a directory if it does not exist
func IsNotExistCreateFile(src string) error {
if notExist := CheckNotExist(src); notExist == true {
if notExist := CheckNotExist(src); notExist {
if err := CreateFile(src); err != nil {
return err
}
@@ -267,7 +268,7 @@ func CopySingleFile(src, dst, style string) error {
return os.Chmod(dst, srcinfo.Mode())
}
//Check for duplicate file names
// Check for duplicate file names
func GetNoDuplicateFileName(fullPath string) string {
path, fileName := filepath.Split(fullPath)
fileSuffix := path2.Ext(fileName)
@@ -293,7 +294,7 @@ func CopyDir(src string, dst string, style string) error {
}
return nil
}
//dstPath := dst
// dstPath := dst
lastPath := src[strings.LastIndex(src, "/")+1:]
dst += "/" + lastPath
// for i := 0; Exists(dst); i++ {
@@ -314,7 +315,7 @@ func CopyDir(src string, dst string, style string) error {
}
for _, fd := range fds {
srcfp := path.Join(src, fd.Name())
dstfp := dst //path.Join(dst, fd.Name())
dstfp := dst // path.Join(dst, fd.Name())
if fd.IsDir() {
if err = CopyDir(srcfp, dstfp, style); err != nil {
@@ -336,10 +337,17 @@ func WriteToPath(data []byte, path, name string) error {
} else {
fullPath += "/" + name
}
IsNotExistCreateFile(fullPath)
return WriteToFullPath(data, fullPath, 0o666)
}
func WriteToFullPath(data []byte, fullPath string, perm fs.FileMode) error {
if err := IsNotExistCreateFile(fullPath); err != nil {
return err
}
file, err := os.OpenFile(fullPath,
os.O_WRONLY|os.O_TRUNC|os.O_CREATE,
0666,
perm,
)
if err != nil {
return err
@@ -350,26 +358,31 @@ func WriteToPath(data []byte, path, name string) error {
return err
}
//最终拼接
// 最终拼接
func SpliceFiles(dir, path string, length int, startPoint int) error {
fullPath := path
IsNotExistCreateFile(fullPath)
if err := IsNotExistCreateFile(fullPath); err != nil {
return err
}
file, _ := os.OpenFile(fullPath,
os.O_WRONLY|os.O_TRUNC|os.O_CREATE,
0666,
0o666,
)
defer file.Close()
bufferedWriter := bufio.NewWriter(file)
for i := 0; i < length+startPoint; i++ {
// todo: here should have a goroutine to remove each partial file after it is read, to save disk space
for i := 0; i < length+startPoint-1; i++ {
data, err := ioutil.ReadFile(dir + "/" + strconv.Itoa(i+startPoint))
if err != nil {
return err
}
_, err = bufferedWriter.Write(data)
if err != nil {
if _, err := bufferedWriter.Write(data); err != nil { // recommend to use https://github.com/iceber/iouring-go for faster write
return err
}
}
@@ -380,7 +393,6 @@ func SpliceFiles(dir, path string, length int, startPoint int) error {
}
func GetCompressionAlgorithm(t string) (string, archiver.Writer, error) {
switch t {
case "zip", "":
return ".zip", archiver.NewZip(), nil
@@ -400,8 +412,8 @@ func GetCompressionAlgorithm(t string) (string, archiver.Writer, error) {
return "", nil, errors.New("format not implemented")
}
}
func AddFile(ar archiver.Writer, path, commonPath string) error {
func AddFile(ar archiver.Writer, path, commonPath string) error {
info, err := os.Stat(path)
if err != nil {
return err
@@ -447,6 +459,7 @@ func AddFile(ar archiver.Writer, path, commonPath string) error {
return nil
}
func CommonPrefix(sep byte, paths ...string) string {
// Handle special cases.
switch len(paths) {
@@ -513,7 +526,7 @@ func GetFileOrDirSize(path string) (int64, error) {
return fileInfo.Size(), nil
}
//getFileSize get file size by path(B)
// getFileSize get file size by path(B)
func DirSizeB(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {

View File

@@ -1,21 +1,55 @@
package route
import (
"encoding/json"
"fmt"
"os"
"strings"
"time"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/samba"
"github.com/IceWhaleTech/CasaOS/pkg/utils/encryption"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
"github.com/IceWhaleTech/CasaOS/service"
"github.com/IceWhaleTech/CasaOS/types"
"go.uber.org/zap"
)
func InitFunction() {
go InitNetworkMount()
go InitInfo()
}
func InitInfo() {
mb := model.BaseInfo{}
if file.Exists(config.AppInfo.DBPath + "/baseinfo.conf") {
err := json.Unmarshal(file.ReadFullFile(config.AppInfo.DBPath+"/baseinfo.conf"), &mb)
if err != nil {
loger.Error("baseinfo.conf", zap.String("error", err.Error()))
}
}
if file.Exists("/etc/CHANNEL") {
channel := file.ReadFullFile("/etc/CHANNEL")
mb.Channel = string(channel)
}
mac, err := service.MyService.System().GetMacAddress()
if err != nil {
loger.Error("GetMacAddress", zap.String("error", err.Error()))
}
mb.Hash = encryption.GetMD5ByStr(mac)
mb.Version = types.CURRENTVERSION
os.Remove(config.AppInfo.DBPath + "/baseinfo.conf")
by, err := json.Marshal(mb)
if err != nil {
loger.Error("init info err", zap.Any("err", err))
return
}
file.WriteToFullPath(by, config.AppInfo.DBPath+"/baseinfo.conf", 0o666)
}
func InitNetworkMount() {
time.Sleep(time.Second * 10)
connections := service.MyService.Connections().GetConnectionsList()

View File

@@ -1,8 +1,10 @@
package route
import (
"os"
"github.com/IceWhaleTech/CasaOS-Common/middleware"
"github.com/IceWhaleTech/CasaOS-Common/utils/jwt"
"github.com/IceWhaleTech/CasaOS/middleware"
"github.com/IceWhaleTech/CasaOS/pkg/config"
v1 "github.com/IceWhaleTech/CasaOS/route/v1"
@@ -11,13 +13,22 @@ import (
)
func InitRouter() *gin.Engine {
ginMode := gin.ReleaseMode
if config.ServerInfo.RunMode != "" {
ginMode = config.ServerInfo.RunMode
}
if os.Getenv(gin.EnvGinMode) != "" {
ginMode = os.Getenv(gin.EnvGinMode)
}
gin.SetMode(ginMode)
r := gin.Default()
r := gin.New()
r.Use(gin.Recovery())
r.Use(middleware.Cors())
r.Use(middleware.WriteLog())
r.Use(gzip.Gzip(gzip.DefaultCompression))
gin.SetMode(config.ServerInfo.RunMode)
if ginMode != gin.ReleaseMode {
r.Use(middleware.WriteLog())
}
// r.StaticFS("/ui", http.FS(web.Static))
// r.GET("/", WebUIHome)
@@ -35,7 +46,7 @@ func InitRouter() *gin.Engine {
// r.GET("/v1/users/image", v1.GetUserImage)
// r.GET("/v1/users/status", v1.GetUserStatus) //init/check
//r.GET("/v1/guide/check", v1.GetGuideCheck) // /v1/sys/guide_check
// r.GET("/v1/guide/check", v1.GetGuideCheck) // /v1/sys/guide_check
r.GET("/v1/sys/debug", v1.GetSystemConfigDebug) // //debug
r.GET("/v1/sys/socket-port", v1.GetSystemSocketPort) //sys/socket_port
@@ -73,7 +84,7 @@ func InitRouter() *gin.Engine {
v1AppsGroup := v1Group.Group("/apps")
v1AppsGroup.Use()
{
v1AppsGroup.GET("", v1.AppList) //list
v1AppsGroup.GET("", v1.AppList) // list
v1AppsGroup.GET("/:id", v1.AppInfo)
}
v1ContainerGroup := v1Group.Group("/container")
@@ -84,24 +95,24 @@ func InitRouter() *gin.Engine {
v1ContainerGroup.GET("/usage", v1.AppUsageList)
v1ContainerGroup.GET("/:id", v1.ContainerUpdateInfo) ///update/:id/info
v1ContainerGroup.GET("/:id/logs", v1.ContainerLog) // /app/logs/:id
v1ContainerGroup.GET("/networks", v1.GetDockerNetworks) //app/install/config
v1ContainerGroup.GET("/networks", v1.GetDockerNetworks) // app/install/config
v1ContainerGroup.GET("/:id/state", v1.GetContainerState) //app/state/:id ?state=install_progress
v1ContainerGroup.GET("/:id/state", v1.GetContainerState) // app/state/:id ?state=install_progress
// there are problems, temporarily do not deal with
v1ContainerGroup.GET("/:id/terminal", v1.DockerTerminal) //app/terminal/:id
v1ContainerGroup.POST("", v1.InstallApp) //app/install
//v1ContainerGroup.GET("/:id", v1.ContainerInfo) // /app/info/:id
v1ContainerGroup.GET("/:id/terminal", v1.DockerTerminal) // app/terminal/:id
v1ContainerGroup.POST("", v1.InstallApp) // app/install
// v1ContainerGroup.GET("/:id", v1.ContainerInfo) // /app/info/:id
v1ContainerGroup.PUT("/:id", v1.UpdateSetting) ///update/:id/setting
v1ContainerGroup.PUT("/:id/state", v1.ChangAppState) // /app/state/:id
v1ContainerGroup.DELETE("/:id", v1.UnInstallApp) //app/uninstall/:id
//Not used
v1ContainerGroup.DELETE("/:id", v1.UnInstallApp) // app/uninstall/:id
// Not used
v1ContainerGroup.PUT("/:id/latest", v1.PutAppUpdate)
//Not used
// Not used
v1ContainerGroup.POST("/share", v1.ShareAppFile)
v1ContainerGroup.GET("/info", v1.GetcontainerInfo)
v1ContainerGroup.PUT("/info", v1.PutcontainerInfo)
v1ContainerGroup.GET("/info", v1.GetDockerDaemonConfiguration)
v1ContainerGroup.PUT("/info", v1.PutDockerDaemonConfiguration)
}
v1AppCategoriesGroup := v1Group.Group("/app-categories")
@@ -113,19 +124,19 @@ func InitRouter() *gin.Engine {
v1SysGroup := v1Group.Group("/sys")
v1SysGroup.Use()
{
v1SysGroup.GET("/version", v1.GetSystemCheckVersion) //version/check
v1SysGroup.GET("/version", v1.GetSystemCheckVersion) // version/check
v1SysGroup.POST("/update", v1.SystemUpdate)
v1SysGroup.GET("/hardware", v1.GetSystemHardwareInfo) //hardware/info
v1SysGroup.GET("/hardware", v1.GetSystemHardwareInfo) // hardware/info
v1SysGroup.GET("/wsssh", v1.WsSsh)
v1SysGroup.POST("/ssh-login", v1.PostSshLogin)
//v1SysGroup.GET("/config", v1.GetSystemConfig) //delete
//v1SysGroup.POST("/config", v1.PostSetSystemConfig)
v1SysGroup.GET("/logs", v1.GetCasaOSErrorLogs) //error/logs
//v1SysGroup.GET("/widget/config", v1.GetWidgetConfig)//delete
//v1SysGroup.POST("/widget/config", v1.PostSetWidgetConfig)//delete
// v1SysGroup.GET("/config", v1.GetSystemConfig) //delete
// v1SysGroup.POST("/config", v1.PostSetSystemConfig)
v1SysGroup.GET("/logs", v1.GetCasaOSErrorLogs) // error/logs
// v1SysGroup.GET("/widget/config", v1.GetWidgetConfig)//delete
// v1SysGroup.POST("/widget/config", v1.PostSetWidgetConfig)//delete
v1SysGroup.POST("/stop", v1.PostKillCasaOS)
@@ -135,37 +146,34 @@ func InitRouter() *gin.Engine {
// v1SysGroup.GET("/disk", v1.GetSystemDiskInfo)
// v1SysGroup.GET("/network", v1.GetSystemNetInfo)
v1SysGroup.PUT("/usb-auto-mount", v1.PutSystemUSBAutoMount) ///sys/usb/:status
v1SysGroup.GET("/usb-auto-mount", v1.GetSystemUSBAutoMount) ///sys/usb/status
v1SysGroup.GET("/server-info", nil)
v1SysGroup.PUT("/server-info", nil)
v1SysGroup.GET("/apps-state", v1.GetSystemAppsStatus)
//v1SysGroup.GET("/port", v1.GetCasaOSPort)
//v1SysGroup.PUT("/port", v1.PutCasaOSPort)
// v1SysGroup.GET("/port", v1.GetCasaOSPort)
// v1SysGroup.PUT("/port", v1.PutCasaOSPort)
v1SysGroup.GET("/proxy", v1.GetSystemProxy)
}
v1PortGroup := v1Group.Group("/port")
v1PortGroup.Use()
{
v1PortGroup.GET("/", v1.GetPort) //app/port
v1PortGroup.GET("/state/:port", v1.PortCheck) //app/check/:port
v1PortGroup.GET("/", v1.GetPort) // app/port
v1PortGroup.GET("/state/:port", v1.PortCheck) // app/check/:port
}
v1FileGroup := v1Group.Group("/file")
v1FileGroup.Use()
{
v1FileGroup.GET("", v1.GetDownloadSingleFile) //download/:path
v1FileGroup.GET("", v1.GetDownloadSingleFile) // download/:path
v1FileGroup.POST("", v1.PostCreateFile)
v1FileGroup.PUT("", v1.PutFileContent)
v1FileGroup.PUT("/name", v1.RenamePath)
//file/rename
v1FileGroup.GET("/content", v1.GetFilerContent) //file/read
// file/rename
v1FileGroup.GET("/content", v1.GetFilerContent) // file/read
//File uploads need to be handled separately, and will not be modified here
// File uploads need to be handled separately, and will not be modified here
v1FileGroup.POST("/upload", v1.PostFileUpload)
v1FileGroup.GET("/upload", v1.GetFileUpload)
//v1FileGroup.GET("/download", v1.UserFileDownloadCommonService)
// v1FileGroup.GET("/download", v1.UserFileDownloadCommonService)
}
v1FolderGroup := v1Group.Group("/folder")
v1FolderGroup.Use()
@@ -178,9 +186,9 @@ func InitRouter() *gin.Engine {
v1BatchGroup.Use()
{
v1BatchGroup.DELETE("", v1.DeleteFile) //file/delete
v1BatchGroup.DELETE("", v1.DeleteFile) // file/delete
v1BatchGroup.DELETE("/:id/task", v1.DeleteOperateFileOrDir)
v1BatchGroup.POST("/task", v1.PostOperateFileOrDir) //file/operate
v1BatchGroup.POST("/task", v1.PostOperateFileOrDir) // file/operate
v1BatchGroup.GET("", v1.GetDownloadFile)
}
v1ImageGroup := v1Group.Group("/image")
@@ -211,7 +219,7 @@ func InitRouter() *gin.Engine {
v1NotifyGroup.Use()
{
v1NotifyGroup.POST("/:path", v1.PostNotifyMessage)
//merge to system
// merge to system
v1NotifyGroup.POST("/system_status", v1.PostSystemStatusNotify)
}
}

View File

@@ -2,8 +2,9 @@ package v1
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"path/filepath"
"strconv"
"github.com/IceWhaleTech/CasaOS/model"
@@ -16,6 +17,11 @@ import (
"github.com/gin-gonic/gin"
)
const (
dockerRootDirFilePath = "/var/lib/casaos/docker_root"
dockerDaemonConfigurationFilePath = "/etc/docker/daemon.json"
)
// @Summary 获取远程列表
// @Produce application/json
// @Accept application/json
@@ -29,8 +35,7 @@ import (
// @Success 200 {string} string "ok"
// @Router /app/list [get]
func AppList(c *gin.Context) {
//service.MyService.Docker().DockerContainerCommit("test2")
// service.MyService.Docker().DockerContainerCommit("test2")
index := c.DefaultQuery("index", "1")
size := c.DefaultQuery("size", "10000")
@@ -139,7 +144,7 @@ func MyAppList(c *gin.Context) {
func AppUsageList(c *gin.Context) {
list := service.MyService.App().GetHardwareUsage()
c.JSON(common_err.SUCCESS, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list})
//c.JSON(common_err.SUCCESS, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: nil})
// c.JSON(common_err.SUCCESS, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: nil})
}
// @Summary 应用详情
@@ -151,7 +156,6 @@ func AppUsageList(c *gin.Context) {
// @Success 200 {string} string "ok"
// @Router /app/appinfo/{id} [get]
func AppInfo(c *gin.Context) {
id := c.Param("id")
language := c.GetHeader("Language")
info, err := service.MyService.Casa().GetServerAppInfo(id, "", language)
@@ -213,7 +217,7 @@ func AppInfo(c *gin.Context) {
// return c1.Type < c2.Type
// }
//sort
// sort
// if info.NetworkModel != "host" {
// sort.PortsSort(portOrder).Sort(info.Configures.TcpPorts)
// sort.PortsSort(portOrder).Sort(info.Configures.UdpPorts)
@@ -265,53 +269,87 @@ func ShareAppFile(c *gin.Context) {
c.JSON(common_err.SUCCESS, json.RawMessage(content))
}
func GetcontainerInfo(c *gin.Context) {
func GetDockerDaemonConfiguration(c *gin.Context) {
// info, err := service.MyService.Docker().GetDockerInfo()
// if err != nil {
// c.JSON(common_err.SERVICE_ERROR, &model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()})
// return
// }
daemon := model.DeckerDaemonModel{}
data := make(map[string]interface{}, 1)
data["docker_root_dir"] = ""
if file.Exists("/etc/docker/daemon.json") {
byteResult := file.ReadFullFile("/etc/docker/daemon.json")
err := json.Unmarshal(byteResult, &daemon)
data := make(map[string]interface{})
if file.Exists(dockerRootDirFilePath) {
buf := file.ReadFullFile(dockerRootDirFilePath)
err := json.Unmarshal(buf, &data)
if err != nil {
c.JSON(common_err.CLIENT_ERROR, &model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.INVALID_PARAMS), Data: err.Error()})
c.JSON(common_err.CLIENT_ERROR, &model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.INVALID_PARAMS), Data: err})
return
}
data["docker_root_dir"] = daemon.Graph
}
c.JSON(common_err.SUCCESS, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
}
func PutcontainerInfo(c *gin.Context) {
js := make(map[string]interface{})
err := c.BindJSON(&js)
if err != nil {
c.JSON(common_err.CLIENT_ERROR, &model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.INVALID_PARAMS), Data: err.Error()})
func PutDockerDaemonConfiguration(c *gin.Context) {
request := make(map[string]interface{})
if err := c.BindJSON(&request); err != nil {
c.JSON(http.StatusBadRequest, &model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.INVALID_PARAMS), Data: err})
return
}
dockerRootDir := js["docker_root_dir"].(string)
daemon := model.DeckerDaemonModel{}
if file.Exists("/etc/docker/daemon.json") {
byteResult := file.ReadFullFile("/etc/docker/daemon.json")
err := json.Unmarshal(byteResult, &daemon)
value, ok := request["docker_root_dir"]
if !ok {
c.JSON(http.StatusBadRequest, &model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.INVALID_PARAMS), Data: "`docker_root_dir` should not empty"})
return
}
dockerConfig := model.DockerDaemonConfigurationModel{}
if file.Exists(dockerDaemonConfigurationFilePath) {
byteResult := file.ReadFullFile(dockerDaemonConfigurationFilePath)
err := json.Unmarshal(byteResult, &dockerConfig)
if err != nil {
c.JSON(common_err.CLIENT_ERROR, &model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.INVALID_PARAMS), Data: err.Error()})
c.JSON(http.StatusInternalServerError, &model.Result{Success: common_err.SERVICE_ERROR, Message: "error when trying to deserialize " + dockerDaemonConfigurationFilePath, Data: err})
return
}
}
dockerRootDir := value.(string)
if dockerRootDir == "/" {
dockerConfig.Root = "" // omitempty - empty string will not be serialized
} else {
if !file.Exists(dockerRootDir) {
c.JSON(common_err.CLIENT_ERROR, &model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.DIR_NOT_EXISTS), Data: common_err.GetMsg(common_err.DIR_NOT_EXISTS)})
c.JSON(http.StatusBadRequest, &model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.DIR_NOT_EXISTS), Data: common_err.GetMsg(common_err.DIR_NOT_EXISTS)})
return
}
daemon.Graph = dockerRootDir
byteMode, _ := json.Marshal(daemon)
file.WriteToPath(byteMode, "/etc/docker", "daemon.json")
fmt.Println(command.ExecResultStr("systemctl daemon-reload"))
fmt.Println(command.ExecResultStr("systemctl restart docker"))
dockerConfig.Root = filepath.Join(dockerRootDir, "docker")
c.JSON(common_err.SUCCESS, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: js})
if err := file.IsNotExistMkDir(dockerConfig.Root); err != nil {
c.JSON(http.StatusInternalServerError, &model.Result{Success: common_err.SERVICE_ERROR, Message: "error when trying to create " + dockerConfig.Root, Data: err})
return
}
}
if buf, err := json.Marshal(request); err != nil {
c.JSON(http.StatusBadRequest, &model.Result{Success: common_err.CLIENT_ERROR, Message: "error when trying to serialize docker root json", Data: err})
return
} else {
if err := file.WriteToFullPath(buf, dockerRootDirFilePath, 0o644); err != nil {
c.JSON(http.StatusInternalServerError, &model.Result{Success: common_err.SERVICE_ERROR, Message: "error when trying to write " + dockerRootDirFilePath, Data: err})
return
}
}
if buf, err := json.Marshal(dockerConfig); err != nil {
c.JSON(http.StatusBadRequest, &model.Result{Success: common_err.CLIENT_ERROR, Message: "error when trying to serialize docker config", Data: dockerConfig})
return
} else {
if err := file.WriteToFullPath(buf, dockerDaemonConfigurationFilePath, 0o644); err != nil {
c.JSON(http.StatusInternalServerError, &model.Result{Success: common_err.SERVICE_ERROR, Message: "error when trying to write to " + dockerDaemonConfigurationFilePath, Data: err})
return
}
}
println(command.ExecResultStr("systemctl daemon-reload"))
println(command.ExecResultStr("systemctl restart docker"))
c.JSON(http.StatusOK, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: request})
}

View File

@@ -1126,7 +1126,7 @@ func ContainerUpdateInfo(c *gin.Context) {
}
}
for _, v := range info.Config.Env {
if len(showENVList) > 0 {
if len(showENVList) > 0 && info.Config.Labels["origin"] != "local" {
if _, ok := showENVMap[strings.Split(v, "=")[0]]; ok {
temp := model.Env{
Name: strings.Split(v, "=")[0],

View File

@@ -18,9 +18,11 @@ import (
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
"github.com/IceWhaleTech/CasaOS/service"
"github.com/gin-gonic/gin"
uuid "github.com/satori/go.uuid"
"go.uber.org/zap"
)
// @Summary 读取文件
@@ -47,7 +49,7 @@ func GetFilerContent(c *gin.Context) {
})
return
}
//文件读取任务是将文件内容读取到内存中。
// 文件读取任务是将文件内容读取到内存中。
info, err := ioutil.ReadFile(filePath)
if err != nil {
c.JSON(common_err.SERVICE_ERROR, model.Result{
@@ -83,7 +85,6 @@ func GetLocalFile(c *gin.Context) {
return
}
c.File(path)
return
}
// @Summary download
@@ -96,7 +97,6 @@ func GetLocalFile(c *gin.Context) {
// @Success 200 {string} string "ok"
// @Router /file/download [get]
func GetDownloadFile(c *gin.Context) {
t := c.Query("format")
files := c.Query("files")
@@ -135,11 +135,11 @@ func GetDownloadFile(c *gin.Context) {
}
if !info.IsDir() {
//打开文件
// 打开文件
fileTmp, _ := os.Open(filePath)
defer fileTmp.Close()
//获取文件的名称
// 获取文件的名称
fileName := path.Base(filePath)
c.Header("Content-Disposition", "attachment; filename*=utf-8''"+url2.PathEscape(fileName))
c.File(filePath)
@@ -179,7 +179,6 @@ func GetDownloadFile(c *gin.Context) {
log.Printf("Failed to archive %s: %v", fname, err)
}
}
}
func GetDownloadSingleFile(c *gin.Context) {
@@ -202,7 +201,7 @@ func GetDownloadSingleFile(c *gin.Context) {
defer fileTmp.Close()
fileName := path.Base(filePath)
//c.Header("Content-Disposition", "inline")
// c.Header("Content-Disposition", "inline")
c.Header("Content-Disposition", "attachment; filename*=utf-8''"+url2.PathEscape(fileName))
c.File(filePath)
}
@@ -248,7 +247,7 @@ func DirPath(c *gin.Context) {
info[i].Extensions = ex
}
}
//Hide the files or folders in operation
// Hide the files or folders in operation
fileQueue := make(map[string]string)
if len(service.OpStrArr) > 0 {
for _, v := range service.OpStrArr {
@@ -361,7 +360,6 @@ func PostCreateFile(c *gin.Context) {
// @Success 200 {string} string "ok"
// @Router /file/upload [get]
func GetFileUpload(c *gin.Context) {
relative := c.Query("relativePath")
fileName := c.Query("filename")
chunkNumber := c.Query("chunkNumber")
@@ -405,7 +403,8 @@ func PostFileUpload(c *gin.Context) {
hash := file.GetHashByContent([]byte(fileName))
if len(path) == 0 {
c.JSON(common_err.INVALID_PARAMS, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
loger.Error("path should not be empty")
c.JSON(http.StatusBadRequest, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
return
}
tempDir := filepath.Join(path, ".temp", hash+strconv.Itoa(totalChunks)) + "/"
@@ -413,47 +412,82 @@ func PostFileUpload(c *gin.Context) {
if fileName != relative {
dirPath = strings.TrimSuffix(relative, fileName)
tempDir += dirPath
file.MkDir(path + "/" + dirPath)
if err := file.MkDir(path + "/" + dirPath); err != nil {
loger.Error("error when trying to create `"+path+"/"+dirPath+"`", zap.Error(err))
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
}
path += "/" + relative
if !file.CheckNotExist(tempDir + chunkNumber) {
file.RMDir(tempDir + chunkNumber)
if err := file.RMDir(tempDir + chunkNumber); err != nil {
loger.Error("error when trying to remove existing `"+tempDir+chunkNumber+"`", zap.Error(err))
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
}
if totalChunks > 1 {
file.IsNotExistMkDir(tempDir)
if err := file.IsNotExistMkDir(tempDir); err != nil {
loger.Error("error when trying to create `"+tempDir+"`", zap.Error(err))
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
out, _ := os.OpenFile(tempDir+chunkNumber, os.O_WRONLY|os.O_CREATE, 0644)
defer out.Close()
_, err := io.Copy(out, f)
out, err := os.OpenFile(tempDir+chunkNumber, os.O_WRONLY|os.O_CREATE, 0o644)
if err != nil {
c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()})
loger.Error("error when trying to open `"+tempDir+chunkNumber+"` for creation", zap.Error(err))
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
} else {
out, _ := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0644)
defer out.Close()
_, err := io.Copy(out, f)
if err != nil {
c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()})
return
}
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
if _, err := io.Copy(out, f); err != nil { // recommend to use https://github.com/iceber/iouring-go for faster copy
loger.Error("error when trying to write to `"+tempDir+chunkNumber+"`", zap.Error(err))
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
fileNum, err := ioutil.ReadDir(tempDir)
if err != nil {
c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()})
loger.Error("error when trying to read number of files under `"+tempDir+"`", zap.Error(err))
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
if totalChunks == len(fileNum) {
file.SpliceFiles(tempDir, path, totalChunks, 1)
file.RMDir(tempDir)
if err := file.SpliceFiles(tempDir, path, totalChunks, 1); err != nil {
loger.Error("error when trying to splice files under `"+tempDir+"`", zap.Error(err))
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
if err := file.RMDir(tempDir); err != nil {
loger.Error("error when trying to remove `"+tempDir+"`", zap.Error(err))
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
}
} else {
out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o644)
if err != nil {
loger.Error("error when trying to open `"+path+"` for creation", zap.Error(err))
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
defer out.Close()
if _, err := io.Copy(out, f); err != nil { // recommend to use https://github.com/iceber/iouring-go for faster copy
loger.Error("error when trying to write to `"+path+"`", zap.Error(err))
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()})
return
}
}
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
}
// @Summary copy or move file
@@ -465,7 +499,6 @@ func PostFileUpload(c *gin.Context) {
// @Success 200 {string} string "ok"
// @Router /file/operate [post]
func PostOperateFileOrDir(c *gin.Context) {
list := model.FileOperate{}
c.ShouldBind(&list)
@@ -515,7 +548,6 @@ func PostOperateFileOrDir(c *gin.Context) {
// @Success 200 {string} string "ok"
// @Router /file/delete [delete]
func DeleteFile(c *gin.Context) {
paths := []string{}
c.ShouldBind(&paths)
if len(paths) == 0 {
@@ -547,7 +579,6 @@ func DeleteFile(c *gin.Context) {
// @Success 200 {string} string "ok"
// @Router /file/update [put]
func PutFileContent(c *gin.Context) {
fi := model.FileUpdate{}
c.ShouldBind(&fi)
@@ -557,7 +588,7 @@ func PutFileContent(c *gin.Context) {
c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.FILE_ALREADY_EXISTS, Message: common_err.GetMsg(common_err.FILE_ALREADY_EXISTS)})
return
}
//err := os.Remove(path)
// err := os.Remove(path)
err := os.RemoveAll(fi.FilePath)
if err != nil {
c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.FILE_DELETE_ERROR, Message: common_err.GetMsg(common_err.FILE_DELETE_ERROR), Data: err})

View File

@@ -164,51 +164,6 @@ func PostKillCasaOS(c *gin.Context) {
os.Exit(0)
}
// @Summary Turn off usb auto-mount
// @Produce application/json
// @Accept application/json
// @Tags sys
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /sys/usb/off [put]
func PutSystemUSBAutoMount(c *gin.Context) {
js := make(map[string]string)
c.ShouldBind(&js)
status := js["state"]
if status == "on" {
service.MyService.System().UpdateUSBAutoMount("True")
service.MyService.System().ExecUSBAutoMountShell("True")
} else {
service.MyService.System().UpdateUSBAutoMount("False")
service.MyService.System().ExecUSBAutoMountShell("False")
}
c.JSON(common_err.SUCCESS,
model.Result{
Success: common_err.SUCCESS,
Message: common_err.GetMsg(common_err.SUCCESS),
})
}
// @Summary Turn off usb auto-mount
// @Produce application/json
// @Accept application/json
// @Tags sys
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /sys/usb [get]
func GetSystemUSBAutoMount(c *gin.Context) {
state := "True"
if config.ServerInfo.USBAutoMount == "False" {
state = "False"
}
c.JSON(common_err.SUCCESS,
model.Result{
Success: common_err.SUCCESS,
Message: common_err.GetMsg(common_err.SUCCESS),
Data: state,
})
}
func GetSystemAppsStatus(c *gin.Context) {
systemAppList := service.MyService.App().GetSystemAppList()
appList := []model2.MyAppList{}
@@ -225,12 +180,12 @@ func GetSystemAppsStatus(c *gin.Context) {
Id: v.ID,
Port: v.Labels["web"],
Index: v.Labels["index"],
//Order: m.Labels["order"],
// Order: m.Labels["order"],
Image: v.Image,
Latest: false,
//Type: m.Labels["origin"],
//Slogan: m.Slogan,
//Rely: m.Rely,
// Type: m.Labels["origin"],
// Slogan: m.Slogan,
// Rely: m.Rely,
Host: v.Labels["host"],
Protocol: v.Labels["protocol"],
})
@@ -251,7 +206,6 @@ func GetSystemAppsStatus(c *gin.Context) {
// @Success 200 {string} string "ok"
// @Router /sys/hardware/info [get]
func GetSystemHardwareInfo(c *gin.Context) {
data := make(map[string]string, 1)
data["drive_model"] = service.MyService.System().GetDeviceTree()
c.JSON(common_err.SUCCESS,
@@ -270,7 +224,7 @@ func GetSystemHardwareInfo(c *gin.Context) {
// @Success 200 {string} string "ok"
// @Router /sys/utilization [get]
func GetSystemUtilization(c *gin.Context) {
var data = make(map[string]interface{}, 6)
data := make(map[string]interface{})
cpu := service.MyService.System().GetCpuPercent()
num := service.MyService.System().GetCpuCoreNum()
cpuData := make(map[string]interface{})
@@ -282,7 +236,7 @@ func GetSystemUtilization(c *gin.Context) {
data["cpu"] = cpuData
data["mem"] = service.MyService.System().GetMemInfo()
//拼装网络信息
// 拼装网络信息
netList := service.MyService.System().GetNetInfo()
newNet := []model.IOCountersStat{}
nets := service.MyService.System().GetNet(true)
@@ -299,7 +253,9 @@ func GetSystemUtilization(c *gin.Context) {
}
data["net"] = newNet
for k, v := range service.MyService.Notify().GetSystemTempMap() {
data[k] = v
}
c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
}
@@ -311,7 +267,6 @@ func GetSystemUtilization(c *gin.Context) {
// @Success 200 {string} string "ok"
// @Router /sys/socket/port [get]
func GetSystemSocketPort(c *gin.Context) {
c.JSON(common_err.SUCCESS,
model.Result{
Success: common_err.SUCCESS,
@@ -334,7 +289,6 @@ func GetSystemCupInfo(c *gin.Context) {
data["percent"] = cpu
data["num"] = num
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
}
// @Summary get mem info
@@ -347,7 +301,6 @@ func GetSystemCupInfo(c *gin.Context) {
func GetSystemMemInfo(c *gin.Context) {
mem := service.MyService.System().GetMemInfo()
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: mem})
}
// @Summary get disk info

View File

@@ -560,6 +560,7 @@ func (ds *dockerService) DockerContainerCreate(m model.CustomizationPostData, id
//container, err := cli.ContainerCreate(context.Background(), info.Config, info.HostConfig, &network.NetworkingConfig{info.NetworkSettings.Networks}, nil, info.Name)
hostConfig.Mounts = volumes
hostConfig.Binds = []string{}
hostConfig.Privileged = m.Privileged
hostConfig.CapAdd = m.CapAdd
hostConfig.NetworkMode = container.NetworkMode(m.NetworkModel)

View File

@@ -37,6 +37,7 @@ type NotifyServer interface {
SendStorageBySocket(message notify.StorageMessage)
SendNotify(path string, message map[string]interface{})
SettingSystemTempData(message map[string]interface{})
GetSystemTempMap() map[string]interface{}
}
type notifyServer struct {
@@ -442,7 +443,11 @@ func SendMeg() {
// }
// }
func (i *notifyServer) GetSystemTempMap() map[string]interface{} {
return i.SystemTempMap
}
func NewNotifyService(db *gorm.DB) NotifyServer {
return &notifyServer{db: db, SystemTempMap: make(map[string]interface{})}
}

View File

@@ -30,8 +30,6 @@ type SystemService interface {
UpdateAssist()
UpSystemPort(port string)
GetTimeZone() string
UpdateUSBAutoMount(state string)
ExecUSBAutoMountShell(state string)
UpAppOrderFile(str, id string)
GetAppOrderFile(id string) []byte
GetNet(physics bool) []string
@@ -52,16 +50,18 @@ type SystemService interface {
IsServiceRunning(name string) bool
GetCPUTemperature() int
GetCPUPower() map[string]string
GetMacAddress() (string, error)
}
type systemService struct {
}
type systemService struct{}
func (s *systemService) UpdateUSBAutoMount(state string) {
config.ServerInfo.USBAutoMount = state
config.Cfg.Section("server").Key("USBAutoMount").SetValue(state)
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
func (c *systemService) GetMacAddress() (string, error) {
interfaces, err := net.Interfaces()
if err != nil {
return "", err
}
inter := interfaces[0]
return inter.HardwareAddr, nil
}
func (c *systemService) MkdirAll(path string) (int, error) {
_, err := os.Stat(path)
if err == nil {
@@ -76,8 +76,8 @@ func (c *systemService) MkdirAll(path string) (int, error) {
}
return common_err.SERVICE_ERROR, err
}
func (c *systemService) RenameFile(oldF, newF string) (int, error) {
func (c *systemService) RenameFile(oldF, newF string) (int, error) {
_, err := os.Stat(newF)
if err == nil {
return common_err.DIR_ALREADY_EXISTS, nil
@@ -92,6 +92,7 @@ func (c *systemService) RenameFile(oldF, newF string) (int, error) {
}
return common_err.SERVICE_ERROR, err
}
func (c *systemService) CreateFile(path string) (int, error) {
_, err := os.Stat(path)
if err == nil {
@@ -104,9 +105,11 @@ func (c *systemService) CreateFile(path string) (int, error) {
}
return common_err.SERVICE_ERROR, err
}
func (c *systemService) GetDeviceTree() string {
return command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;GetDeviceTree")
}
func (c *systemService) GetSysInfo() host.InfoStat {
info, _ := host.Info()
return *info
@@ -128,9 +131,7 @@ func (c *systemService) GetNetState(name string) string {
}
func (c *systemService) GetDirPathOne(path string) (m model.Path) {
f, err := os.Stat(path)
if err != nil {
return
}
@@ -175,6 +176,7 @@ func (c *systemService) GetDirPath(path string) []model.Path {
}
return dirs
}
func (c *systemService) GetCpuInfo() []cpu.InfoStat {
info, _ := cpu.Info()
return info
@@ -207,6 +209,7 @@ func (c *systemService) GetNetInfo() []net.IOCountersStat {
parts, _ := net.IOCounters(true)
return parts
}
func (c *systemService) GetNet(physics bool) []string {
t := "1"
if physics {
@@ -221,10 +224,16 @@ func (s *systemService) UpdateSystemVersion(version string) {
}
file.CreateFile(config.AppInfo.LogPath + "/upgrade.log")
//go command2.OnlyExec("curl -fsSL https://raw.githubusercontent.com/LinkLeong/casaos-alpha/main/update.sh | bash")
go command2.OnlyExec("curl -fsSL https://raw.githubusercontent.com/IceWhaleTech/get/main/update.sh | sudo bash")
if len(config.ServerInfo.UpdateUrl) > 0 {
go command2.OnlyExec("curl -fsSL " + config.ServerInfo.UpdateUrl + " | bash")
} else {
go command2.OnlyExec("curl -fsSL https://raw.githubusercontent.com/IceWhaleTech/get/main/update.sh | bash")
}
//s.log.Error(config.AppInfo.ProjectPath + "/shell/tool.sh -r " + version)
//s.log.Error(command2.ExecResultStr(config.AppInfo.ProjectPath + "/shell/tool.sh -r " + version))
}
func (s *systemService) UpdateAssist() {
command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/assist.sh")
}
@@ -233,14 +242,6 @@ func (s *systemService) GetTimeZone() string {
return command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;GetTimeZone")
}
func (s *systemService) ExecUSBAutoMountShell(state string) {
if state == "False" {
command2.OnlyExec("source " + config.AppInfo.ShellPath + "/helper.sh ;USB_Stop_Auto")
} else {
command2.OnlyExec("source " + config.AppInfo.ShellPath + "/helper.sh ;USB_Start_Auto")
}
}
func (s *systemService) GetSystemConfigDebug() []string {
return command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;GetSysInfo")
}
@@ -248,9 +249,11 @@ func (s *systemService) GetSystemConfigDebug() []string {
func (s *systemService) UpAppOrderFile(str, id string) {
file.WriteToPath([]byte(str), config.AppInfo.DBPath+"/"+id, "app_order.json")
}
func (s *systemService) GetAppOrderFile(id string) []byte {
return file.ReadFullFile(config.AppInfo.UserDataPath + "/" + id + "/app_order.json")
}
func (s *systemService) UpSystemPort(port string) {
if len(port) > 0 && port != config.ServerInfo.HttpPort {
config.Cfg.Section("server").Key("HttpPort").SetValue(port)
@@ -258,6 +261,7 @@ func (s *systemService) UpSystemPort(port string) {
}
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
}
func (s *systemService) GetCasaOSLogs(lineNumber int) string {
file, err := os.Open(filepath.Join(config.AppInfo.LogPath, fmt.Sprintf("%s.%s",
config.AppInfo.LogSaveName,
@@ -294,8 +298,8 @@ func GetDeviceAllIP() []string {
func (s *systemService) IsServiceRunning(name string) bool {
status := command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;CheckServiceStatus smbd")
return strings.TrimSpace(status) == "running"
}
func (s *systemService) GetCPUTemperature() int {
outPut := ""
if file.Exists("/sys/class/thermal/thermal_zone0/temp") {
@@ -313,6 +317,7 @@ func (s *systemService) GetCPUTemperature() int {
}
return celsius
}
func (s *systemService) GetCPUPower() map[string]string {
data := make(map[string]string, 2)
data["timestamp"] = strconv.FormatInt(time.Now().Unix(), 10)
@@ -323,6 +328,7 @@ func (s *systemService) GetCPUPower() map[string]string {
}
return data
}
func NewSystemService() SystemService {
return &systemService{}
}

View File

@@ -1,15 +1,14 @@
/*
* @Author: LinkLeong link@icewhale.com
* @Date: 2022-02-17 18:53:22
* @LastEditors: LinkLeong
* @LastEditTime: 2022-09-06 14:27:42
* @FilePath: /CasaOS/types/system.go
* @Description:
* @Website: https://www.casaos.io
* Copyright (c) 2022 by icewhale, All Rights Reserved.
/*@Author: LinkLeong link@icewhale.com
*@Date: 2022-02-17 18:53:22
*@LastEditors: LinkLeong
*@LastEditTime: 2022-09-06 14:27:42
*@FilePath: /CasaOS/types/system.go
*@Description:
*@Website: https://www.casaos.io
*Copyright (c) 2022 by icewhale, All Rights Reserved.
*/
package types
const CURRENTVERSION = "0.3.6"
const CURRENTVERSION = "0.3.7.1"
const BODY = " "