Compare commits

..
376 Commits
Author SHA1 Message Date
ssongliu 2c92226f88 chore: Modify cache cleanup internationalization (#11551) 2026-01-04 18:32:46 +08:00
CityFun cd9cb9b9c9 feat: Update website name validation rules (#11550) 2026-01-04 10:29:43 +00:00
CityFun b2777055bc fix: Fix website log cleanup selection state (#11549) 2026-01-04 10:27:40 +00:00
ssongliu c8673b60bb fix: Fix the issue of abnormal cache cleanup display (#11547) 2026-01-04 09:31:43 +00:00
ssongliu 21975dff2d chore: Rollback S3 backup account SDK version (#11546)
Refs #11486

aws v2 存在部分兼容性问题 https://github.com/aws/aws-sdk-go-v2/issues/3007
2026-01-04 08:51:40 +00:00
CityFun 6ab14185e0 perf: Optimize supervisor log reading (#11545)
Refs https://github.com/1Panel-dev/1Panel/issues/11515
2026-01-04 08:49:40 +00:00
CityFun 1f70646952 feat: Add enable UDP option for TCP/UDP website configuration (#11543) 2026-01-04 15:23:56 +08:00
ssongliu c90ed9e873 feat: Cache database default connections (#11540)
Refs  #10819
2026-01-04 06:39:40 +00:00
CityFun e4ee07d36b feat: Support batch installation of applications (#11539) 2026-01-04 05:43:40 +00:00
ssongliu 8fb3e78554 chore: Fix some internationalization content (#11528)
Refs #11517
2025-12-31 14:35:38 +00:00
CityFun 01ab004876 fix: update MdEditor component to prevent potential XSS attacks (#11527) 2025-12-31 14:33:38 +00:00
ssongliu 6205eac51c feat: Support enabling proxy when adding nodes (#11525) 2025-12-31 22:31:43 +08:00
王贺 d9a5418029 chore: update copyright (#11524) 2025-12-31 09:03:56 +08:00
CityFun 74a8e61f3e feat: change website http to https logic (#11522)
Refs https://github.com/1Panel-dev/1Panel/issues/11521
2025-12-30 06:33:36 +00:00
CityFun e18472f1a3 feat: optimize disk mount logic (#11519) 2025-12-30 06:31:35 +00:00
蘭 e3dea80cb7 fix: Fix the issue of garbled Chinese characters in recipient names and email titles in email alerts (#11516)
#11264
2025-12-29 09:37:35 +00:00
ssongliu 50947f4ddc feat: ICMP ping disable compatibility with Debian 13 (#11514)
Refs  #11472
2025-12-29 09:35:36 +00:00
KOMATA d302bc07b3 feat: Add support for Mux SSL mode and update related settings (#11509)
* feat: Add support for Mux SSL mode and update related settings

- Introduced a new SSL mode "Mux" in the settings, allowing for HTTP to HTTPS redirection.
- Updated the `SSL` field in the `SettingUpdate` struct to include "Mux" as a valid option.
- Modified the server logic to handle Mux connections, including certificate management and HTTP redirection.
- Updated frontend components to reflect the new SSL options and improved user guidance in multiple languages.

* fix: Update HTTPS related messages for improved clarity and security guidance in multiple languages
2025-12-29 15:41:15 +08:00
CityFun c6df20e565 feat: support sync 404 html page to websites (#11513)
Refs https://github.com/1Panel-dev/1Panel/issues/11489
2025-12-29 07:17:34 +00:00
CityFun 6f9a1321d1 feat: support custom DNS server for manual DNS mode when applying certificates (#11512) 2025-12-29 07:13:35 +00:00
ssongliu eb4eb31578 feat: Multi-machine management supports viewing node logs (#11510) 2025-12-29 07:11:34 +00:00
CityFun f8f5fcfca2 fix: Fixed Website configuration file automatically keeps adding HTTPS redirects (#11506)
#11490
2025-12-29 07:09:35 +00:00
l061x 4e7b654090 fix: Fix command argument formatting in terminal initlinux (#11484) 2025-12-26 22:03:24 +08:00
ssongliu e8059d3676 fix: Fix refresh issue during compose creation (#11482)
Refs #11463
2025-12-26 13:55:03 +00:00
ssongliu ffadc6721b fix: Fix issue where compose cannot be created when empty (#11481) 2025-12-26 09:13:04 +00:00
CityFun e2e774d215 feat: add website log clean option for clean cache (#11480) 2025-12-26 09:11:03 +00:00
ssongliu f23d3678fb fix: Fix backup account echo abnormality issue (#11479)
Refs #11478
2025-12-26 09:09:03 +00:00
ssongliu dfade50bd8 fix: Fix snapshot backup application image failure issue (#11477) 2025-12-26 16:49:03 +08:00
ssongliu d25b5f4f2a feat: Add quick operation features to node overview page (#11476) 2025-12-26 08:35:03 +00:00
CityFun 9a17bc74b0 feat: add 'nofail' option for disk mounting (#11475)
Refs https://github.com/1Panel-dev/1Panel/issues/11468
2025-12-26 08:33:03 +00:00
CityFun 015605526d fix: add missing intermediate certificates for IP certificate requests (#11470)
Refs https://github.com/1Panel-dev/1Panel/issues/11462
2025-12-26 08:31:03 +00:00
CityFun 099896dc96 feat: add app temporary download file cleanup option to cache cleaning (#11460) 2025-12-25 10:33:03 +00:00
CityFun aa1bc6fa8e feat: add website log cleanup option to cache cleaning (#11457) 2025-12-25 07:43:02 +00:00
ssongliu f27a429fc5 feat: Cache cleanup supports cleaning up unassociated backups (#11452) 2025-12-25 13:49:47 +08:00
ssongliu f4587d0ae5 fix: Fix panic issue caused by 1pctl command (#11453)
Refs  #11449
2025-12-25 04:17:02 +00:00
CityFun 41bae1e636 perf: improve display of IP certificate editing interface (#11451)
Refs https://github.com/1Panel-dev/1Panel/issues/11449
2025-12-25 03:17:02 +00:00
CityFun 5295fd08d4 feat: update Let's Encrypt to official endpoint (#11444) 2025-12-24 11:24:17 +08:00
CityFun 36fdf05d2b feat: support apply ip Certificate (#11437) 2025-12-23 13:35:38 +08:00
ssongliu 5794dbc0a6 Merge pull request #11435 from 1Panel-dev/pr@dev-v2@fix_compose_log
fix: Fix compose log download failure issue
2025-12-23 13:35:14 +08:00
ssongliu c10474db69 fix: Fix typo (#11436) 2025-12-23 05:35:06 +00:00
wanghe d68309fd44 Merge pull request #11432 from HynoR/fix/firewall
feat: Add UDP port 443 accept rule to Pre-firewall config
2025-12-22 19:14:21 +08:00
CityFun 1c634756a0 fix: resolve issue with quick navigation failure in applications (#11434) 2025-12-22 18:50:22 +08:00
CityFun ae536550c3 style: adjust node card display (#11431) 2025-12-22 18:49:58 +08:00
ssongliu 63d5d70314 feat: Retain historical settings when toggling watermark (#11429)
Refs #11392
2025-12-22 10:23:39 +00:00
KOMATA 0be73600e5 feat: Implement Punycode utility functions and integrate into domain dispay (#11433)
* feat: Implement Punycode utility functions and integrate into domain display

* chore: Add punycode package and update import path in utility functions
2025-12-22 18:22:29 +08:00
ssongliu c9cc064f51 fix: Fix container orchestration creation failure issue (#11430) 2025-12-22 18:21:51 +08:00
HynoR dc47eb5ae4 feat: Add UDP port 443 acceptance rule to firewall and iptables configuration 2025-12-22 15:55:47 +08:00
ssongliu 955d9db699 style: Modify terminal connection style issues (#11425)
Refs  #11413
2025-12-22 06:33:29 +00:00
CityFun 3c1549e288 fix: resolve limitation of fetching only 100 redirects for websites (#11424) 2025-12-22 14:31:40 +08:00
CityFun 9fd030b6c3 feat: improve scrolling effect of left-side on website configuration page (#11423)
Refs https://github.com/1Panel-dev/1Panel/issues/11412
2025-12-22 06:01:30 +00:00
CityFun 63a10691b3 feat: limit website name length in configuration (#11422) 2025-12-22 05:59:30 +00:00
ssongliu 5674673c5d feat: Support display and operations for multi-YAML compose startup (#11421)
Refs #11405
2025-12-22 05:57:30 +00:00
ssongliu 74f29e3dc3 chore: Adjust image dependency warning messages (#11407) 2025-12-19 10:08:32 +00:00
ssongliu 1dac8593ae feat: Add database transaction monitoring logs (#11406) 2025-12-19 10:06:32 +00:00
ssongliu 71fd123be1 fix: Fix snapshot application checkbox abnormality issue (#11404) 2025-12-19 10:04:33 +00:00
CityFun d4d66cad2e feat: improve prompt messages when synchronizing WAF IP groups (#11402) 2025-12-19 07:41:02 +00:00
CityFun c78a6ec047 style: change table tooltip style (#11399) 2025-12-19 15:33:57 +08:00
CityFun 1ae3198b10 fix: clear stream configuration when closing website creation page (#11400) 2025-12-19 07:27:03 +00:00
CityFun a6c172b1ab feat: remove Cache-Control: no-cache for create proxy website (#11398) 2025-12-19 07:25:03 +00:00
CityFun 9e9d68f841 style: adjust status column styling in websites list page (#11397) 2025-12-19 07:23:02 +00:00
CityFun 123e6b90a3 feat: update MySQL parameter input validation rules (#11396) 2025-12-19 05:42:11 +00:00
CityFun 00b4a6caf5 feat: update MySQL parameter input validation rules (#11395)
https://github.com/1Panel-dev/1Panel/issues/11394
2025-12-19 03:41:27 +00:00
ssongliu 8642e20d19 perf: Optimize container task log output (#11393) 2025-12-19 03:39:40 +00:00
ssongliu 2b81f7ef7a feat: Output last incomplete line in shell cronjob (#11391) 2025-12-18 21:58:24 +08:00
ssongliu c08e83e5d4 fix: Fix firewalld range port forwarding failure issue (#11390) 2025-12-18 09:21:13 +00:00
CityFun 863ee5c172 feat: Adjust tooltip positions on some pages (#11389) 2025-12-18 09:01:14 +00:00
ssongliu a91f372fbd chore: Revert container command input style (#11387)
revert for #10724

https://bbs.fit2cloud.com/t/topic/16496
2025-12-18 08:59:14 +00:00
ssongliu 825acd5b46 feat: Optimize snapshot backup items (#11385) 2025-12-18 07:43:13 +00:00
CityFun 70e64e648f feat: Adjust prompt for creating stream website (#11384) 2025-12-18 07:41:13 +00:00
ssongliu 7855e89ca9 chore: Modify orchestration environment variable style (#11381) 2025-12-17 14:20:12 +00:00
CityFun 75273abda7 fix: Resolve issue where website names are not displayed in logs for stream-type websites (#11379) 2025-12-17 08:50:11 +00:00
ssongliu 02b278ecff feat: Add version printing after rollback (#11378)
Refs #11265
2025-12-17 08:48:10 +00:00
CityFun e43d7b7a59 fix: Fix issue where backing up stream websites fails (#11377) 2025-12-17 16:46:51 +08:00
CityFun 61f321a04d fix: Fix issue where disabling logs for stream websites fails (#11376) 2025-12-17 16:46:41 +08:00
CityFun 7885b00213 feat: Optimize display issues after creating TCP/UDP proxies (#11375) 2025-12-17 08:46:11 +00:00
CityFun 2ad882b7c2 fix: Fixed issue where deleting symbolic link files fails (#11373)
Refs https://github.com/1Panel-dev/1Panel/issues/11324
2025-12-17 08:44:10 +00:00
ssongliu 2546809013 chore: Adjust task log output format (#11372) 2025-12-17 06:24:09 +00:00
CityFun 4fcf3e11cd fix: Resolve issue where bulk certificate setup creates duplicate server certificates (#11371) 2025-12-17 05:52:10 +00:00
CityFun 1f6cd6f4e9 feat: increase timeout duration for some API interfaces (#11370)
Refs https://github.com/1Panel-dev/1Panel/issues/11348
2025-12-17 05:50:09 +00:00
ssongliu 5c1ce232db chore: Modify i18n initialization method (#11368) 2025-12-17 13:46:32 +08:00
CityFun 172e9e212b feat: Adjust the display position of PHP runtime environment prompts (#11366) 2025-12-17 05:46:09 +00:00
CityFun 279a16c256 feat: Optimize HTTP to HTTPS redirection rules for non-443 port websites (#11364)
Refs https://github.com/1Panel-dev/1Panel/issues/11360
2025-12-17 05:44:09 +00:00
ssongliu e772cdff3c fix: Fix task log printing garbled characters issue (#11363) 2025-12-17 13:42:23 +08:00
CityFun 8881827f9d feat: Optimize the structure of installed apps in the App Store (#11361) 2025-12-17 13:42:13 +08:00
ssongliu d9579901fe fix: Fix incomplete log printing for compose save errors (#11357) 2025-12-16 08:41:58 +00:00
蘭 682d78698f ref: Optimize the button layout on the file upload page (#11354) 2025-12-16 08:39:58 +00:00
CityFun 2cc8567c2f feat: relocate PHP extension installation prompts (#11352)
https://github.com/1Panel-dev/1Panel/issues/11293
2025-12-16 08:38:00 +00:00
ssongliu 184a214bff feat: Add hint messages for compose environment variables (#11351) 2025-12-16 08:35:59 +00:00
CityFun c6376541ed feat: add OpenResty version restriction for TCP/UDP proxy (#11350) 2025-12-16 08:33:59 +00:00
ssongliu 6aca579854 fix: Fix ufw IPv6 rule configuration issue (#11349)
Refs #11211
2025-12-16 08:31:59 +00:00
CityFun 15bc6cf884 feat: add prompt for TCP/UDP proxy (#11343) 2025-12-15 18:56:07 +08:00
ssongliu 895dde74dd fix: Fix local application backup failure in snapshots (#11341) 2025-12-15 18:42:05 +08:00
CityFun c477d20a05 feat: support batch SSL configuration for websites (#11339)
Refs https://github.com/1Panel-dev/1Panel/issues/8250
2025-12-15 10:41:38 +00:00
ssongliu 2fdb1700e5 feat: Database restore supports timeout settings (#11338) 2025-12-15 18:40:37 +08:00
KOMATA 11764e1ba5 feat: improve website create function and interface (#11331)
* feat: improve website create function and interface

* feat: update website create tag

* feat: update i18n files

* feat: update valid domain regex

* feat: reorder website types to improve structure

* feat: update domain labels for consistency in the domain creation form

* feat: update i18n
2025-12-15 16:01:21 +08:00
ssongliu 3212e23f43 feat: Terminal connection supports reset (#11336) 2025-12-15 07:19:21 +00:00
CityFun 84a58f2bb1 fix: resolve issue where crossVersionUpdate setting not taking effect (#11333)
Refs https://github.com/1Panel-dev/1Panel/issues/11328
2025-12-15 07:17:21 +00:00
KOMATA 191396c78a fix: Validate StreamPorts in StreamConfig to prevent empty values (#11332) 2025-12-15 10:11:09 +08:00
CityFun 956a64c692 feat: Support managing application upgrades for all nodes on a single page (#11325) 2025-12-12 10:49:10 +00:00
ssongliu 6f9a8d5afe fix: Fix version upgrade failure in some scenarios 2025-12-12 18:22:49 +08:00
ssongliu 9424d061fa fix: Fix version upgrade failure in some scenarios (#11322) 2025-12-12 18:13:35 +08:00
CityFun 3db8e47679 feat: optimize prompt for syncing WAF IP groups (#11317) 2025-12-12 08:11:11 +00:00
CityFun 5602741550 feat: improve container deletion prompt (#11316) 2025-12-12 08:09:11 +00:00
CityFun 1ef3f540c2 feat: Task center supports switching nodes (#11315) 2025-12-12 08:07:12 +00:00
ssongliu 51846895d5 fix: Fix lock issue during monitoring input insertion (#11312) 2025-12-12 08:05:11 +00:00
ssongliu 551542c99c perf: Optimize GPU monitoring style (#11303) 2025-12-11 14:11:05 +00:00
CityFun ab13ddec48 feat: The website supports TCP/UDP proxying. (#11302)
Refs https://github.com/1Panel-dev/1Panel/issues/5135
Refs https://github.com/1Panel-dev/1Panel/issues/6976
2025-12-11 10:33:03 +00:00
CityFun 2d1792c6de fix: Fix the issue where the website app deployment fails (#11301) 2025-12-11 09:03:03 +00:00
KOMATA 3aedb7e82d chore: Add trusted dependencies for vue-office packages to support bun toolkit (#11291) 2025-12-11 17:00:34 +08:00
ssongliu a9c9f0272a fix: Fix cronjob manual stop not working (#11300) 2025-12-11 17:00:22 +08:00
Kadxy 8606427e8c feat(frontend): add autocomplete attributes for MFA input (#11297) 2025-12-11 16:59:58 +08:00
ssongliu 3d3d22dc06 fix: Fix local PostgreSQL database backup failure (#11295) 2025-12-10 19:02:24 +08:00
ssongliu 23a3a5cf74 Fix typo (#11287) 2025-12-10 14:31:19 +08:00
ssongliu 0f5410d225 fix: Fix focus loss issue in file selection component (#11281)
Refs #11272
2025-12-09 10:38:56 +00:00
ssongliu 1b7be836ef fix: Fix container orchestration format validation issues (#11280)
Refs #11227
2025-12-09 10:36:57 +00:00
CityFun 66e7223db9 feat: Support quick installation of PHP lz4 extension (#11279) 2025-12-09 09:42:56 +00:00
ssongliu d801b811d4 style: Optimize container-associated resource styles (#11278)
Refs #11268
2025-12-09 09:40:57 +00:00
ssongliu 307029272e fix: Fix port forwarding initialization status judgment issue (#11276)
Refs #11267
2025-12-09 09:38:57 +00:00
ssongliu 9aa3caab16 feat: Container compose supports .env file operations (#11274) 2025-12-09 09:36:58 +00:00
KOMATA b47a4525dc feat: Enhance browser cache management and localization support (#11277)
* feat: Enhance browser cache management and localization support

- Updated browser cache handling in WebsiteService to include a 'noModify' option.
- Introduced new method AddBroswerNoCache in Location to manage no-cache directives.
- Added localization for 'noModify' in multiple languages.
- Updated frontend to support the new browser cache options in the proxy configuration.

* fix: Update cache display logic in proxy configuration

- Adjusted the rendering of cache tags in the proxy configuration to conditionally display based on cache time values.
- Improved user interface by adding margin classes for better spacing between cache tags.
2025-12-09 17:32:23 +08:00
KOMATA 38ab0d9ca0 feat: Implement process management and network data handling (#11270)
- Introduced ProcessStore for managing process and network data via WebSocket.
- Enhanced TableSearch component to synchronize search parameters with props.
- Updated network and process views to utilize ProcessStore for data fetching and state management.
- Improved data filtering and sorting in network and process views.
- Added WebSocket connection management with polling for real-time updates.
2025-12-09 17:31:23 +08:00
KOMATA 38985671c6 perf: improve getNetConnections function and Websocket handling (#11269)
* feat: Enhance WebSocket client functionality and improve data processing

- Reduced message queue size in WebSocket client from 100 to 32.
- Introduced atomic boolean to track client closure state.
- Added SendPayload method to handle message sending with queue management.
- Updated ProcessData function to utilize SendPayload for sending responses.
- Expanded netTypes to include both IPv4 and IPv6 protocols in network connection retrieval.
- Improved net connection processing by using a map for process names, enhancing efficiency.

* feat: Enhance WebSocket client and process data handling

- Added synchronization with sync.Once for safe closure of WebSocket client.
- Updated message queue size to a constant for better maintainability.
- Implemented context timeouts for process data retrieval to prevent blocking.
- Improved network connection handling by utilizing a more efficient method for retrieving connections.
- Introduced a new function to determine connection types based on protocol family.

* feat: Enhance network connection retrieval and process name mapping

- Updated getNetConnections function to improve efficiency by using maps for process names and connections.
- Introduced a new helper function to retrieve process names from the filesystem or process context.
- Enhanced filtering logic for network connections based on process ID, name, and port.
- Increased initial capacity for connection results to optimize performance.

* refactor: Rename SendPayload method to Send in WebSocket client

- Updated the SendPayload method to be more succinctly named Send for clarity.
- Ensured the method continues to handle message sending while maintaining existing functionality.

* refactor: Update ProcessData and getNetConnections for improved clarity and efficiency

- Replaced SendPayload method calls with Send for consistency in WebSocket message handling.
- Enhanced getNetConnections function by refining process name retrieval and filtering logic.
- Improved error handling in getProcessNameWithContext for better robustness.

* refactor: Simplify WebSocket client closure and reading logic

- Removed unnecessary synchronization for closing the WebSocket client.
- Updated the Read method to handle message reading directly without a separate Close method.
- Ensured the Socket is closed properly after reading messages to prevent resource leaks.
2025-12-09 17:30:12 +08:00
ssongliu d1c2a69820 pref: Optimize backup account code structure (#11261) 2025-12-08 18:22:59 +08:00
KOMATA 3a1b9fedd1 perf: Simplify process data handling and improve performance (#11236)
* refactor: Simplify process data handling and improve performance

- Replaced goroutine-based processing with a direct loop for handling process data.
- Introduced context support for process and connection retrieval.
- Enhanced error handling and data structuring for process information.
- Improved SSH session retrieval by mapping users by host for better efficiency.

* chore: go fmt
2025-12-08 17:34:52 +08:00
蘭 8119ba75fc ref: Adjust Swagger format (#11207)
* ref: Adjust Swagger format

* ref: Adjust Swagger format
2025-12-08 17:34:24 +08:00
ssongliu be4c22012e fix: Fix HTTP/HTTPS docker proxy issues (#11258)
Refs #11254
2025-12-08 09:20:38 +00:00
ssongliu 60fef48cf0 chore: Remove system upgrade temporary files (#11255)
Refs #11241
2025-12-08 09:18:37 +00:00
KOMATA bb72ea0fc0 fix: Improve SSH session retrieval by grouping users by host in process_data.go (#11210) 2025-12-08 16:39:08 +08:00
KOMATA af48fed3c2 feat: Add file preview functionality and interface (#11200)
* feat: Add file content preview functionality

- Implemented a new API endpoint for previewing file content.
- Added PreviewContent method in BaseApi to handle requests.
- Introduced GetPreviewContent method in FileService to retrieve file previews.
- Updated frontend to include a TextPreview component for displaying file previews.
- Added localization support for preview-related messages in multiple languages.
- Enhanced file management view to support previewing large files.

* feat: Update file preview functionality and interface

- Added PreviewContentReq interface to define request parameters for file preview.
- Updated getPreviewContent function to use the new PreviewContentReq type.
- Modified text-preview component to align with updated API, removing unnecessary parameters.
2025-12-08 16:37:50 +08:00
endymx ce3fa94708 feat(iptables): range forward (#11188) 2025-12-08 16:35:01 +08:00
ssongliu 7f9f4ae740 fix: Fix PostgreSQL backup failure with $ character (#11252) 2025-12-08 15:24:08 +08:00
CityFun 8bec6f2b28 fix: Fixed network search returning empty results with no page update (#11251) 2025-12-08 07:10:37 +00:00
CityFun b397363c9d fix: Fixed process search returning empty results with no page update (#11246) 2025-12-08 05:54:36 +00:00
KOMATA acb800b505 fix: Update compose operation handling to ensure correct path usage and detail loading after operations (#11245) 2025-12-08 13:41:55 +08:00
CityFun ec37af2f18 fix: Fixed missing redirect after installing runtime environment (#11243) 2025-12-08 04:44:36 +00:00
CityFun d2b030e698 feat: Added support for auto-filling remote MySQL root password in App Store (#11240) 2025-12-08 11:39:08 +08:00
ssongliu c6f496f2a5 fix: Fix the issue of container compose log cleanup failure (#11238) 2025-12-08 11:38:05 +08:00
CityFun 722e1929f1 fix: Fixed file comparison highlighting loss issue (#11237) 2025-12-08 03:28:35 +00:00
王贺 f9a20ec443 Fix typo (#11229) 2025-12-07 11:36:20 +08:00
ssongliu f5568d4874 fix: Fix style issues caused by element upgrade (#11224) 2025-12-06 14:16:34 +00:00
ssongliu 87bbe4ee12 fix: Fix the issue of abnormal compose directory redirection (#11223) 2025-12-06 14:14:28 +00:00
ssongliu a034b03c1d fix: Task framework adds timeout exit parameter (#11206) 2025-12-05 18:42:23 +08:00
CityFun 470f4e4db7 style: Updated layout page save button styling (#11198) 2025-12-05 03:24:23 +00:00
CityFun 9428efd8c0 fix: Fixed CAPTCHA loading issue in certain scenarios (#11186) 2025-12-04 10:12:22 +00:00
CityFun bf4d91b68b fix: Fixed login CAPTCHA bypass vulnerability (#11185) 2025-12-04 10:10:23 +00:00
KOMATA 781155b029 perf: remove useless stat checking logic (#11178)
* feat: Enhance proxy initialization and error handling

* Add a timeout to the dialer for Unix socket connections
* Improve error response by including the error message in the "Bad Gateway" response

* refactor: Change sockPath variable to constant in proxy initialization

* Update sockPath to a constant SockPath for improved clarity and consistency
* Ensure the new constant is used in the dialer function for Unix socket connections
2025-12-04 18:07:47 +08:00
KOMATA 3caf0ac529 fix: Ensure proper client closure in volume and device clean operations (#11177) 2025-12-04 18:07:16 +08:00
CityFun 7d25228e55 perf: Optimized tensorrtLLM display performanceperf (#11184) 2025-12-04 17:57:19 +08:00
ssongliu 4fb099912e fix: Fix the issue of remote database connection failure (#11181)
Refs #11173
2025-12-04 09:56:23 +00:00
ssongliu b3350b54b3 fix: Add iptables execution timeout (#11176) 2025-12-04 11:22:25 +08:00
CityFun cd4e0374d0 refactor: Refactored agent core.db loading logic (#11175) 2025-12-04 11:15:40 +08:00
KOMATA 5d2084fda4 feat: improve linux distribution information get logic (#11171)
* feat: Add PrettyDistro field to dashboard information and update related services and frontend components

* fix: Trim whitespace and parentheses from detected Linux distribution name in GetDistro method

* fix: Correctly trim parentheses from detected Linux distribution name in GetDistro method

* refactor: Simplify Linux distribution detection by removing unnecessary checks and consolidating logic
2025-12-03 14:14:35 +08:00
ssongliu 8c32fa3e6c fix: Fix the issue of abnormal clam scan status judgment (#11172) 2025-12-03 14:13:22 +08:00
KOMATA fef13211a0 feat: Enhance CPU metrics by adding CPU detailed information (#11169)
* fix: Update CPU usage retrieval to include detailed percentage information

* feat: Enhance CPU metrics by adding CPU frequency and detailed usage percentages

* feat: Add CPU frequency metric to dashboard base information
2025-12-03 13:37:57 +08:00
CityFun 5ff5b0a5ad feat: revised some of the translations (#11168) 2025-12-03 03:58:14 +00:00
CityFun 8ac9d022b6 fix: fix missing version issue during mssql installation (#11167) 2025-12-03 03:56:15 +00:00
CityFun 2c02dc07e9 fix: resolve i18n file loading failure issue (#11164) 2025-12-03 10:08:20 +08:00
ssongliu ba999c516a chore: Modify the default runtime value on the overview page (#11159) 2025-12-02 10:21:42 +00:00
AirboZH 28303ffa82 feat: Add support for AWS Route 53 DNS provider (#11158) 2025-12-02 18:20:35 +08:00
ssongliu 1f9a3aa51a feat: Add refresh after resource release in container overview (#11157) 2025-12-02 09:29:41 +00:00
ssongliu 656dda234c perf: Optimize GPU monitoring display (#11156) 2025-12-02 09:21:41 +00:00
KOMATA 63b62f4074 fix: Enhance error handling in file saving process (#11152)
* fix: Enhance error handling in file saving process

* f

* f
2025-12-02 17:19:22 +08:00
KOMATA 158180a052 fix: Enhance error handling for additional HTTP status codes in RequestHttp class (#11151) 2025-12-02 17:11:55 +08:00
ssongliu dbe479e920 fix: Fix agent packaging failure issue (#11150) 2025-12-02 02:57:40 +00:00
蘭 7aefa34871 fix: Fix the issue of software link creation errors (#11149) 2025-12-02 02:53:41 +00:00
ssongliu 7d92436b92 perf: Change container overview page disk usage to asynchronous requests (#11148) 2025-12-02 02:29:39 +00:00
AirboZH 66a070c239 feat: Add support for AliESA DNS provider (#11147) 2025-12-02 10:11:46 +08:00
ssongliu bb9d9042f0 chore: Modify iptables initialization logic (#11145) 2025-12-01 22:20:17 +08:00
ssongliu a5d86d4c00 fix: Fix the issue where container details cannot be fully selected and copied (#11144) 2025-12-01 22:06:59 +08:00
KOMATA e867deb547 feat: Add copy function for raw JSON in container and network detail views (#11141)
* feat: Add copy button for raw JSON in container and network detail views

* refactor: Change CodemirrorPro component from disabled to readonly in container and network detail views

* feat: Add readonly prop to CodemirrorPro component for enhanced editing control
2025-12-01 18:13:52 +08:00
ssongliu af15659d99 fix: Fix display issues caused by default table height (#11143) 2025-12-01 10:05:37 +00:00
ssongliu f63658db9e fix: Fix the issue of extremely slow container list retrieval (#11142)
Refs #11129
2025-12-01 10:03:37 +00:00
ssongliu d4edf2f874 fix: Fix the issue of abnormal time filtering in GPU monitoring (#11139) 2025-12-01 08:43:38 +00:00
ssongliu 94f7d78cc9 fix: Fix iptables state persistence issue (#11137)
Refs #11126
2025-12-01 06:33:38 +00:00
ssongliu 5cede39e5c fix: Fix log display issue when backup account is unavailable during … (#11135)
Refs #11123
2025-12-01 02:15:37 +00:00
KOMATA 508ac2ae84 fix: Improve error handling in file download API (#11127) 2025-12-01 09:40:48 +08:00
KOMATA 997b820a42 perf: use gzipped data for improved load speed in large response (#11128)
* perf: use gzipped data for improved load speed in big files

* perf: switch to gzipped response for GetFileTree to enhance performance

* perf: switch to gzipped response for SearchApp to improve performance

* perf: update file size conditions for gzipped response to enhance performance
2025-12-01 09:40:32 +08:00
KOMATA 5de83985e3 feat: Add path protection mechanism to prevent deletion of system dir (#11130)
* feat: Add path protection mechanism to prevent deletion of critical system directories

* feat: Enhance recycle bin service with path protection for deletion requests
2025-12-01 09:40:00 +08:00
ssongliu c0220dbed0 fix: Disable caching for recommended apps on the overview page (#11117) 2025-11-28 10:19:27 +00:00
ssongliu 2e9305b9b1 fix: Fix some overview page caching issues (#11114) 2025-11-28 09:05:29 +00:00
王贺 b18bdea1c9 chore: limit gitee sync workflow to main repo (#11112) 2025-11-28 16:47:37 +08:00
ssongliu 25fb431163 fix: Fix the upgrade service file location issue (#11109) 2025-11-28 11:07:49 +08:00
CityFun ac43f00273 perf: optimize login API logic (#11104) 2025-11-28 03:05:27 +00:00
ssongliu 8ccf1fcbf3 fix: Fix the issue of abnormal runtime refresh on the overview page (#11106) 2025-11-27 10:37:24 +00:00
ssongliu b2803f574b chore: Remove some unused code (#11105) 2025-11-27 17:59:48 +08:00
ssongliu bbc14bb723 feat: Add GPU monitoring settings redirection (#11103) 2025-11-27 09:57:25 +00:00
KOMATA e89311d5d4 feat: Implement dashboard caching and refresh functionality (#11100)
* feat: Implement dashboard caching and refresh functionality

* feat: Enhance dashboard and launcher with hover refresh functionality and improve caching strategy

* feat: Introduce dashboard caching utility functions for improved data management
2025-11-27 17:54:54 +08:00
CityFun b5e56c6b65 feat: optimize IP whitelist validation logic (#11102) 2025-11-27 16:29:31 +08:00
ssongliu 3d2023858c feat: Compatible with XPU monitoring (#11099) 2025-11-27 05:57:24 +00:00
KOMATA 74b48a18be fix: Improve app list loading by switching to JSON decoder from file stream (#11095) 2025-11-27 13:47:03 +08:00
CityFun 42f61f60fb fix: Fixed issue with edit runtime port failed (#11096)
Refs https://github.com/1Panel-dev/1Panel/issues/11091
2025-11-27 03:51:24 +00:00
KOMATA e32a11910e fix: adjust WebSocket buffer sizes in terminal and host API (#11094) 2025-11-27 11:22:33 +08:00
CityFun dc9fdf897b feat: add more fields to process detail view (#11093) 2025-11-27 11:21:44 +08:00
CityFun 35c946a064 feat: support creating databases with custom charset and collation during app installation (#11092) 2025-11-27 03:21:23 +00:00
KOMATAand王贺 747a0c45ee feat: async load data of top CPU and memory processes data (#11081)
* feat: async load data of top CPU and memory processes data

* refactor: Update CPU and memory top toggle functionality and state management

---------

Co-authored-by: 王贺 <wanghe@fit2cloud.com>
2025-11-26 23:02:09 +08:00
ssongliu 8e03b24b0c feat: Compatible with XPU monitoring (#11088) 2025-11-26 22:30:15 +08:00
ssongliu 18c65c3096 fix: Fix the issue of snapshots not automatically restarting after restoration (#11087) 2025-11-26 22:29:59 +08:00
ssongliu 3b306f990a chore: Optimize iptables initial state loading speed (#11085) 2025-11-26 22:29:48 +08:00
CityFun 92fa6552b1 style: change file management terminal style (#11084) 2025-11-26 10:35:21 +00:00
ssongliu a39dc33770 fix: Handle empty character set in MariaDB compatibility (#11082) 2025-11-26 09:21:21 +00:00
KOMATA 0a42d4942c perf: replace gopsutil sampling with cached metrics and optimize system info retrieval (#11079)
* refactor: change psutil method
2025-11-26 16:33:47 +08:00
ssongliu 8086d5cecb fix: Fix uppercase exclusion in container compose (#11080) 2025-11-26 07:53:24 +00:00
ssongliu a6875614f6 style: Optimize container compose page style (#11076) 2025-11-26 04:39:20 +00:00
CityFun 6b061fa327 perf: change db connect params (#11075) 2025-11-26 11:11:11 +08:00
KOMATA b416e6b6f1 refactor: Optimize log file reading logic (#11064)
* refactor: Optimize log file reading with buffered reader pool and improve pagination logic

* refactor: Enhance file reading logic with improved buffer management and constant usage

* refactor: Adjust maximum read file size and enhance line reading functionality
2025-11-25 22:42:29 +08:00
ssongliu ac1f49f8dd fix: Fix the issue of abnormal image list retrieval in snapshots (#11074)
Refs #11030
2025-11-25 14:25:18 +00:00
ssongliu 6ddee2649d feat: Add default values for curl scheduled tasks (#11073) 2025-11-25 14:17:18 +00:00
ssongliu fd14f53cb9 style: Adjust container network details style (#11072) 2025-11-25 10:51:18 +00:00
CityFun 029e2210f5 perf: change db connect params (#11071) 2025-11-25 18:48:47 +08:00
ssongliu 69769e6203 fix: Fix the issue of database connections not being released (#11070) 2025-11-25 10:07:19 +00:00
ssongliu 2a21f194d3 feat: Optimize orchestration creation logs (#11069)
Refs  #11068
2025-11-25 09:21:18 +00:00
ssongliu e46d8c5812 feat: Support MySQL data synchronization collation (#11067) 2025-11-25 15:02:37 +08:00
CityFun 938605a169 fix: Resolve application list display error caused by docker-compose.yml modifications (#11065) 2025-11-25 06:27:18 +00:00
ssongliu c3cc26a136 fix: Fix the issue of abnormal iptables persistence loading (#11066) 2025-11-25 14:21:24 +08:00
KOMATA dda83b6307 feat: Implement Gzip compression for successful log API responses (#11063)
* feat: Implement Gzip compression for successful API responses

* refactor: Optimize Gzip compression handling in API responses using sync.Pool
2025-11-25 13:39:08 +08:00
CityFun 48e2e01a57 feat: Add MySQL character set and collation configuration during application installation (#11062) 2025-11-25 03:51:17 +00:00
ssongliu d6b00967ca fix: Fix the issue of database backup failure (#11060) 2025-11-25 03:19:18 +00:00
ssongliu 6d4c1f8e79 fix: Fix the issue of abnormal container list sorting (#11059) 2025-11-25 11:17:34 +08:00
ssongliu e88fe0ac2f fix: Fix the issue of database creation failure (#11057) 2025-11-24 14:35:16 +00:00
ssongliu 496c0b50b4 fix: Fix the issue of abnormal iptables rule persistence (#11056)
Refs #11027
2025-11-24 14:33:15 +00:00
wanghe-fit2cloud 9d73d74c63 chore: remove UPX compression 2025-11-24 18:27:54 +08:00
CityFun 7e4e12107a perf: change db connect params (#11055) 2025-11-24 10:03:15 +00:00
CityFun 5b15de91e6 fix: Fixed issue with build failed (#11054) 2025-11-24 16:29:48 +08:00
KOMATA 98b3dc9d7d refactor: update Swagger serving and processing method (#11052)
* feat: Add Swagger UI support and update Go module dependencies
2025-11-24 16:14:06 +08:00
ssongliu c05e610b13 feat: Support more MySQL character sets and collations (#11053) 2025-11-24 08:07:14 +00:00
ssongliu 63f9368e26 feat: GPU monitoring data supports persistence (#11051)
Refs #9496
2025-11-24 07:59:15 +00:00
ssongliu 3f47a6e701 feat: Support multiple URL access for cronjob (#11050)
Refs #10279
2025-11-24 07:57:18 +00:00
ssongliu d7c9b3b192 feat: Support favorite operations for containers and images (#11049)
Refs #10035 #3372
2025-11-24 07:55:14 +00:00
CityFun 063ed23acb perf: Optimize disk management formatting process (#11047)
https://github.com/1Panel-dev/1Panel/issues/11031
2025-11-24 07:51:15 +00:00
ssongliu 7c33dd9026 feat: PG remote databases version 18.x support backup and restore (#11048)
Refs #10917
2025-11-24 07:47:14 +00:00
CityFun a853d8c869 perf: change base64Captcha (#11046) 2025-11-24 14:47:58 +08:00
KOMATA 4ddeb81972 refactor: Update database connection settings to limit concurrency and idle connections (#11045) 2025-11-24 14:04:54 +08:00
CityFun 4dd9f00637 perf: Increase supervisor API timeout duration (#11043)
Refs https://github.com/1Panel-dev/1Panel/issues/11041
2025-11-24 03:59:14 +00:00
ssongliu 49f3779fd2 fix: Fix the issue of abnormal WebDAV connection (#11038) 2025-11-24 11:36:58 +08:00
KOMATAandssongliu 7389aad122 feat: Add ComposeDetail view for enhanced container management (#10981)
* feat: Add ComposeDetail view for enhanced container management

* feat: Update container log management with new table layout and improved stats display

* feat: Update log search mode to 'all' for comprehensive log retrieval

* cleanup

* feat: Enhance log container and compose management with new UI components and improved functionality

* refactor: Remove unused ComposeDetail route and enhance UI components in container management

* refactor: Improve UI styling and interaction for compose list items in container management

* refactor: Update styling and hover effects for compose list items in container management

* refactor: Enhance container compose header with additional context and improve port handling in inspect view

* refactor: Update .env label to use translation for improved localization in container compose view

* refactor: Adjust height and placeholder text for YAML editor in container compose view

* refactor: Adjust docker compose layout

---------

Co-authored-by: ssongliu <songlius11@163.com>
2025-11-21 18:20:19 +08:00
KOMATA bf095c677c feat: Migrate AWS SDK to v2 (#10983)
* refactor: Migrate S3 client to AWS SDK v2

* refactor: Migrate S3 client to AWS SDK v2 and update dependencies

* refactor: Simplify endpoint handling in S3 client initialization

* refactor: Update S3 client method receivers to pointer types for consistency
2025-11-21 16:18:38 +08:00
ssongliu fb929687d8 fix: Fix the issue of abnormal sshd service auto-start status (#11022)
Refs #11017
2025-11-21 08:13:06 +00:00
CityFun bddcf76fc3 fix: Fixed issue with uninstall extension failed (#11021) 2025-11-21 07:59:08 +00:00
KOMATA 9370bdb5ac fix: Update Cache-Control headers for static resources in router (#11020)
* fix: Update Cache-Control headers for static resources in router

* chore: Remove Cache-Control header from static resource response in router
2025-11-21 15:47:48 +08:00
KOMATA ef6d8bb17b fix: improve logic and fix bug in i18n module (#11019)
* feat: Implement language caching and improve language handling in i18n module

* refactor: Optimize i18n initialization with sync.Once for thread safety

* fix: Replace logging with fmt.Println for language file loading errors in i18n module

* fix: Correct format string in error logging for language file loading in i18n module

* fix: Update language files and improve error handling in i18n module

* fix: Update Malay language file extension from .yml to .yaml and add new translations in i18n module

* fix: Improve error messages for language file loading in i18n module

* fix: Ensure cached database language is set correctly during i18n initialization

* fix: Enhance language detection in i18n module by using Accept-Language header
2025-11-21 15:37:01 +08:00
CityFun 99c2eb04c9 feat: Add memory requirement field display for local applications (#11018)
Refs https://github.com/1Panel-dev/1Panel/issues/11015
2025-11-21 04:05:05 +00:00
CityFun d83b673c90 perf: significantly improve app store homepage loading speed (#11013) 2025-11-20 18:57:49 +08:00
ssongliu 7498f3f66b feat: Container networks support multi-NIC operations (#11011)
Refs #11007
2025-11-20 08:35:03 +00:00
ssongliu 147eda529c fix: Fix the issue with PostgreSQL configuration file abnormalities (#11010)
Refs #11004
2025-11-20 08:33:02 +00:00
CityFun c1f0da4248 refactor: remove debug cmd for agent and core (#11009) 2025-11-20 08:31:03 +00:00
KOMATA 8656dada06 fix: correct suitable log queue size to improve performance (#11008)
* fix: Update log queue size to improve performance and ensure proper handling of log entries

* fix: Adjust log queue size to maintain consistency with queue size limit
2025-11-20 16:28:03 +08:00
ssongliu 217d780ed1 fix: Fix the issue of abnormal time display on the monitoring page (#11001) 2025-11-20 02:11:01 +00:00
蘭 fe62dc18fa fix: Fix the issue of creating file/folder hierarchy errors (#10999) 2025-11-19 08:42:59 +00:00
KOMATA d0e95903c9 chore: disable CSS code splitting in Vite config (#10996) 2025-11-19 14:03:23 +08:00
CityFun 1ec7f519c6 fix: resolve certificate push losing other domain data (#10998)
Refs https://github.com/1Panel-dev/1Panel/issues/10988
2025-11-19 06:02:59 +00:00
CityFun 450e8b18cf refactor: remove unused code (#10995) 2025-11-19 03:50:59 +00:00
ssongliu bb882286aa fix: Fix the monitoring settings menu title display issue (#10994) 2025-11-19 03:48:58 +00:00
蘭 d9bbde9e50 feat: code editor supports creating files and folders (#10989)
#10424
2025-11-18 14:34:58 +00:00
CityFun 29746d1b32 refactor: remove unused code (#10987) 2025-11-18 19:12:37 +08:00
ssongliu 5f211961ae fix: Fix the issue of abnormal disk display on the overview page (#10986)
Refs #10982
2025-11-18 09:26:57 +00:00
CityFun 91d364b18b feat: improve LVM partition recognition in disk management (#10985) 2025-11-18 06:22:56 +00:00
CityFun f1677f5a67 fix: resolve network connection count always showing 0 in process list (#10979) 2025-11-18 14:04:23 +08:00
KOMATA fd270263f4 fix: Update Enter key event handling in terminal input to prevent default behavior (#10984) 2025-11-18 14:04:00 +08:00
ssongliu 81c1e90e54 chore: Clean up some unused code (#10977) 2025-11-17 08:32:54 +00:00
ssongliu 3b737184ea fix: Fix the issue of postgres database not being synchronized (#10976)
Refs #10966
2025-11-17 08:30:55 +00:00
ssongliu 4779bffceb fix: Fix the system proxy validation issue (#10975)
Refs #10974
2025-11-17 08:28:55 +00:00
KOMATA 4209ee4486 feat: enhance S3 region selection with dropdown and custom input option (#10967)
* feat: enhance S3 region selection with dropdown and custom input option

* refactor: streamline S3 region selection and endpoint handling in backup account settings
2025-11-17 13:39:33 +08:00
ssongliu 6ca352bf85 fix: Fix the issue where pressing Enter to submit in description edit… (#10972)
…ing does not take effect
2025-11-17 04:18:53 +00:00
CityFun a4d77a1cc2 fix: resolve incorrect container filter condition when redirecting applications (#10971) 2025-11-17 11:44:32 +08:00
ssongliu b9367abfb9 feat: Optimize container cleanup task logs (#10970) 2025-11-17 03:40:53 +00:00
ssongliu a6062897d5 fix: Support encrypted backup of databases (#10963) 2025-11-14 22:12:55 +08:00
蘭 1afe84ed02 fix: Fix menu drag and drop issue (#10962)
#10961
2025-11-14 10:24:53 +00:00
ssongliu 388458f759 feat: Image build supports setting build parameters (#10960)
Refs #10898
2025-11-14 10:22:49 +00:00
CityFun 512ff23f19 feat: add tooltips for transfer application (#10959) 2025-11-14 05:44:49 +00:00
ssongliu 45a32ff255 chore: remove debug log in controller (#10958) 2025-11-14 05:42:50 +00:00
蘭 e4e2d76f75 feat: File manager multi-tab start path optimization (#10957)
#10302
2025-11-14 05:40:52 +00:00
KOMATA 282e196534 refactor: Simplify PHP config update logic by replacing regex with a dedicated function for key matching (#10956) 2025-11-14 13:39:39 +08:00
ssongliu e4fbd3cf86 fix: Fix the issue of abnormal ufw status loading (#10949) 2025-11-13 21:36:35 +08:00
ssongliu 402931862f fix: Fix the issue where iptables description does not take effect (#10947) 2025-11-13 08:36:47 +00:00
CityFun a70e2635ab fix(ssl): prevent domain loss when editing certificate remark (#10946) 2025-11-13 15:43:25 +08:00
ssongliu 8c9ae38017 fix: Modify the binding position of the 1PANEL_OUTPUT chain (#10945) 2025-11-13 15:43:10 +08:00
CityFun 3920076bd9 feat(website): support 128 characters for site alias (#10943)
Refs https://github.com/1Panel-dev/1Panel/issues/10787
2025-11-13 07:42:46 +00:00
ssongliu 55cbf572e0 fix: Fix the issue where deleting rules in iptables advanced settings… (#10942)
… fails
2025-11-13 06:38:47 +00:00
CityFun c4bd4734a5 feat(log): optimize log display (#10941) 2025-11-13 14:37:39 +08:00
ssongliu e7810febd6 fix: Fix the issue of abnormal context in the cmd method (#10939) 2025-11-13 14:37:28 +08:00
ssongliu 0bc9e85734 fix: Fix the issue of abnormal iptables range port addition (#10938) 2025-11-12 22:26:59 +08:00
蘭 4d85ae5fa6 fix: Fix the issue of initializing SMS sending quantity as a string (#10936) 2025-11-12 14:24:45 +00:00
蘭 a7342d6ef2 fix: More button operations rename using drawer processing parameters (#10933)
#10591
2025-11-12 10:30:46 +00:00
ssongliu 5b0fccd19a fix: Fix the issue of license status refresh after import (#10934) 2025-11-12 18:29:10 +08:00
ssongliu ebbfed711c fix: Modify the service backup directory (#10930) 2025-11-12 10:28:44 +00:00
ssongliu d631888d09 fix: Modify the unbound status of iptables firewall (#10928) 2025-11-12 06:46:44 +00:00
KOMATA afd62e8539 fix: Fix bug in iptables firewall module (#10927) 2025-11-12 11:49:24 +08:00
ssongliu 4aca66c417 fix: Add existence check when restarting Docker (#10926)
Refs  #10890
2025-11-12 02:24:42 +00:00
ssongliu 944463e9a8 fix: Fix the issue of excessively long container detail ports (#10924) 2025-11-11 22:52:57 +08:00
ssongliu cf4274afdc feat: support paginated viewing of imported data (#10923) 2025-11-11 22:41:28 +08:00
ssongliu 102f7c316d fix: display iptables default allowed ports (#10922) 2025-11-11 14:22:42 +00:00
KOMATA ffc81ea85a fix: enhance ping status and update logic in firewall service (#10920)
* fix: Update ping status check method

* fix: Enhance ping status update logic and support for alternative sysctl configuration path
2025-11-11 22:20:09 +08:00
KOMATA 02d22ba63f feat: refactor regex usage across multiple files and centralize patterns in a new utility (#10896) 2025-11-11 16:14:09 +08:00
CityFun 51e98623c9 feat: add MODEL_PATH environment for tensorrt llm (#10921) 2025-11-11 15:41:29 +08:00
ssongliu 8e94170fed fix: modify some API documentation (#10919)
Refs #10893
2025-11-11 06:26:41 +00:00
ssongliu 42cee513e0 style: modify license binding display information (#10918)
Refs #10895
2025-11-11 06:24:40 +00:00
CityFun 2c18382f46 feat: optimize website log display (#10914) 2025-11-11 06:22:40 +00:00
CityFun 3773412139 feat: order env for tensorrt_llm (#10916) 2025-11-11 14:09:25 +08:00
ssongliu e17bbdd6a7 fix: Fix the issue of abnormal option switching on the monitoring page (#10913) 2025-11-11 11:26:24 +08:00
巴山夜语 82a0f3a770 feat: Add utility to retrieve service configuration paths (#10891) 2025-11-11 11:12:34 +08:00
ssongliu 11e16abe64 fix: modify cronjob name validation (#10911) 2025-11-10 22:37:42 +08:00
ssongliu 6db79f4b7b feat: support iptables firewall control (#10903) 2025-11-10 21:17:53 +08:00
ssongliu 977a4be3c1 fix: Fix the issue of abnormal application port forwarding (#10910) 2025-11-10 10:52:40 +00:00
CityFun 51ae668154 fix: Fixed issue with update runtime ExtraHosts failed (#10909) 2025-11-10 10:38:39 +00:00
CityFun c6fe487e46 fix: Fixed the issue of database transfer failure to child nodes (#10906) 2025-11-10 18:09:39 +08:00
KOMATA ec4533e7de feat: enhance terminal connection UI with improved popover design and search functionality (#10902) 2025-11-10 17:27:47 +08:00
CityFun 3b73de32ad feat: support tensorrt LLM speedup (#10905) 2025-11-10 08:40:37 +00:00
CityFun da5668ac27 fix: Fix incorrect upgrade notification issue (#10901) 2025-11-10 04:02:38 +00:00
刘瑞斌 c1039fb7f2 feat: Add ResizeObserver to dynamically adjust terminal size on container resize (#10894) 2025-11-10 09:39:02 +08:00
CityFun c82d6838c5 feat: Optimize system disk detection logic (#10889)
Refs https://github.com/1Panel-dev/1Panel/issues/10888
2025-11-07 10:06:31 +00:00
CityFun c40c7b57cb feat: Change the order of backup buttons (#10886) 2025-11-07 08:36:31 +00:00
CityFun 009237a35a feat: change gin start mode (#10885) 2025-11-07 08:34:30 +00:00
KOMATA f4f6f65b4c feat: add lighter fill color and table row hover background for dark theme (#10883) 2025-11-07 14:51:27 +08:00
CityFun 313a8a3380 chore(deps): bump dependencies in go.mod (#10884) 2025-11-07 06:50:30 +00:00
CityFun f686e7cbc4 fix: Fixed issue where applications failed to load when creating deployment websites (#10882) 2025-11-07 06:48:30 +00:00
CityFun 7fa39687b5 fix: Fixed issue where original Compose file content was cleared during comparison (#10880) 2025-11-07 06:46:30 +00:00
CityFun 9d84120181 feat: Add log cleanup support for scheduled tasks (#10871)
Refs https://github.com/1Panel-dev/1Panel/issues/5639
2025-11-05 10:08:25 +00:00
CityFun 3be0dab8a3 fix: Fix the issue where PHP extensions fail to install. (#10869) 2025-11-05 15:34:02 +08:00
CityFun 3a9275d5fa feat: Optimize the check for deleting associated databases when removing app (#10868) 2025-11-05 07:32:27 +00:00
ssongliu 6296aa04c6 feat: Cronjob reports add an unexecuted status (#10866)
Refs #10861
2025-11-05 07:30:25 +00:00
KOMATA cfe9e94e16 feat: add sensitive info mask (#10865) 2025-11-05 09:38:42 +08:00
ssongliu 902d329e78 feat: Container overview page supports displaying disk usage information (#10864) 2025-11-04 22:53:54 +08:00
CityFun 62f59eb1c3 feat: Add a check during upgrade to detect whether the Compose file has been modified. (#10863) 2025-11-04 22:53:33 +08:00
CityFun a7d4c4ebec feat: Optimize environment port mappings (#10856) 2025-11-04 15:55:16 +08:00
CityFun 0ca96621d4 feat: Edit the application Compose content to add a comparison. (#10855) 2025-11-04 15:36:34 +08:00
ssongliu 7ea179c2da fix: SSH client execution compatible with controller (#10854) 2025-11-04 15:36:18 +08:00
CityFun 6982396572 style: Optimize batch delete website (#10853)
Refs https://github.com/1Panel-dev/1Panel/issues/10851
2025-11-04 06:14:24 +00:00
KOMATA 36c4fbfeee fix: disable ip input when choosing unsupported network type (#10849) 2025-11-04 09:51:35 +08:00
CityFun 868c6f47a0 style: Optimize application installation style (#10847)
Refs https://github.com/1Panel-dev/1Panel/issues/10845
2025-11-03 10:46:23 +00:00
KOMATA 74695ab276 fix: add copy button for image name (#10837) 2025-11-03 16:47:04 +08:00
KOMATA cb74d8d51b feat: Add network details drawer component (#10836) 2025-11-03 16:46:39 +08:00
ssongliu eaa620b081 feat: Add real-time process display on the overview page (#10833) 2025-10-31 10:36:19 +00:00
CityFun 18ab07ec4f feat: Support application migration to other nodes. (#10832)
Refs https://github.com/1Panel-dev/1Panel/issues/10509
2025-10-31 10:34:20 +00:00
ssongliu e86bc9a8db feat: Container operations support task logs (#10824)
Refs #10817
2025-10-30 09:42:18 +00:00
ssongliu 75837c87b4 fix: Update swagger API documentation (#10822)
Refs #10816
2025-10-30 08:50:18 +00:00
ssongliu 9a73095a8f feat: System monitoring supports process viewing (#10821)
Refs #3437
2025-10-30 08:48:18 +00:00
wanghe-fit2cloud 9242bf6482 feat: service handling on more platforms 2025-10-30 14:50:33 +08:00
CityFun f552a0ac36 feat: update docker sdk (#10814) 2025-10-29 05:42:17 +00:00
ssongliu 141e2f61eb fix: Optimize the compose env file prompt message (#10813)
Refs #7604
2025-10-29 05:40:19 +00:00
蘭 b6d7b319f2 fix: Fix the issue of failure caused by incorrect email service parameters (#10811)
#10803
2025-10-29 05:38:18 +00:00
ssongliu 4cdc6c80ec feat: Compose templates support import and export (#10809) 2025-10-29 13:36:24 +08:00
Jimes cee9d7ffb0 chore: Correct typo in redirect text 2025-10-29 09:05:24 +08:00
Jimes 3f48bdb216 chore: replace '登陆' with '登录' 2025-10-29 09:03:58 +08:00
CityFun 2cef8dcea4 feat: change tensorrt button logic (#10805) 2025-10-28 18:56:45 +08:00
CityFun c327936db1 core: update github.com/docker/compose/v2 version (#10804) 2025-10-28 10:20:16 +00:00
CityFun 1b53cd4ca8 feat: add sync waf ip group cron job (#10802)
Refs https://github.com/1Panel-dev/1Panel/issues/8915
2025-10-28 10:18:18 +00:00
ssongliu 08f9f6f8e5 feat: Support using proxies for inter-node requests (#10799)
Refs #9903
2025-10-28 10:16:18 +00:00
CityFun fb6b2729c6 feat: Website Load balancer config support fail_timeout (#10796)
Refs https://github.com/1Panel-dev/1Panel/issues/10565
2025-10-28 08:28:16 +00:00
CityFun aa55a18ed8 feat: Fix highlighting issues in the ssh config editor. (#10794)
Refs https://github.com/1Panel-dev/1Panel/issues/6496
2025-10-28 08:26:18 +00:00
ssongliu 6c74c64b29 style: Optimize the container details page style (#10791) 2025-10-28 08:24:17 +00:00
maolei fddbf34684 feat: Add automatic SSL certificate selection when creating a website with HTTPS enabled (#10789)
Optimize the default selection logic after the SSL list is loaded.
Add a flagging mechanism for manual SSL certificate selection, which disables automatic selection once triggered.
Add listeners for changes to the primary and more domains to trigger this automatic selection logic.
2025-10-28 13:49:34 +08:00
KOMATA ea878bba73 feat: add Docker Inspect dialog with tabbed container info view and enhanced visual formatting (#10783)
* feat: Expand Docker inspect detail drawer

* chore: i18n

* fix: switch order in mount detail card.
2025-10-27 18:11:50 +08:00
CityFun db002ec915 feat: Add settings to prevent certificate leakage. (#10785)
Refs https://github.com/1Panel-dev/1Panel/issues/10755
2025-10-27 10:06:17 +00:00
ssongliu 606d3c1717 fix: Improve system monitoring settings (#10784)
Refs #5121 #8390
2025-10-27 10:04:17 +00:00
CityFun b0fbb39cd3 style: Optimize app name display for large screens (#10782)
Refs https://github.com/1Panel-dev/1Panel/issues/10764
2025-10-27 10:02:18 +00:00
ssongliu 2478d26c59 fix: Add validation rules for scheduled task names (#10780)
Refs #10741
2025-10-27 10:00:18 +00:00
ssongliu e072620f9b style: Optimize the style of firewall import and export (#10778) 2025-10-27 17:59:06 +08:00
CityFun dd3419bf52 feat: support architecture detail display for local app (#10777)
Refs https://github.com/1Panel-dev/1Panel/issues/10770
2025-10-27 09:58:16 +00:00
ssongliu f12e70ef5d feat: Support importing licenses when adding nodes (#10776)
Refs #9793
2025-10-27 09:56:16 +00:00
ssongliu 2836207850 fix: Fix the issue of abnormal redirection after deleting a tab (#10774)
Refs #10767
2025-10-27 09:54:16 +00:00
ssongliu 4253b48bba fix: Fix the issue of abnormal menu tab switching (#10773)
Refs #10765
2025-10-27 09:52:18 +00:00
KOMATA ff36b65af4 feat: Optimize i18n by dynamically loading module (#10759)
* feat: Optimize internationalization support, dynamically load language packs and update language settings

* feat: Refactor i18n initialization to load initial messages dynamically
2025-10-27 17:49:52 +08:00
KOMATA 1ef4803954 feat: Enhance cache display and setting in proxy configuration (#10751)
* feat: Enhance caching options for proxy configuration

* fix: typo

* feat: Update caching and directive handling in proxy configuration

* feat: Update default cache time and unit to improve caching configuration

* feat: Implement RemoveCorsOption method to streamline CORS directive removal

* feat: Enhance cache display and initialization in proxy configuration

* refactor: Clean up AddBrowserCache and RemoveCache methods by removing commented-out code
2025-10-24 18:17:51 +08:00
CityFun 08ebbee328 feat: support bach set website group (#10754) 2025-10-24 10:00:14 +00:00
ssongliu d8e4144d46 feat: Child nodes support upgrading together with the master node (#10753)
Refs #9647
2025-10-24 09:14:15 +00:00
CityFun 0b1819576d feat: runtime support config extra_hosts (#10750)
Refs https://github.com/1Panel-dev/1Panel/issues/10250
2025-10-24 08:56:15 +00:00
BugKing 6ce33754a8 chore: Add id attribute to welcome dialog (#10746) 2025-10-24 15:45:11 +08:00
KOMATA 21e0808a86 fix: Replace RemoveDirective with RemoveDirectiveByFullParams for better parameter matching (#10748) 2025-10-24 15:19:32 +08:00
KOMATA 3480182473 feat: Refactor quick command function, turn cascader into palette (#10732) 2025-10-23 17:20:16 +08:00
CityFun e516158294 feat: Reduce Echarts bundle size (#10731) 2025-10-23 17:17:42 +08:00
ssongliu c8ee0af152 fix: Fix the packaging failure issue (#10734) 2025-10-23 16:40:45 +08:00
ssongliu 3b82d2a1ee feat: Add xplay welcome page (#10733) 2025-10-23 16:27:11 +08:00
CityFun 274fd526b7 feat: optimization waf map load (#10730) 2025-10-23 16:00:23 +08:00
ssongliu 86b0e01d9d fix: Optimize the container command input method (#10724) 2025-10-22 18:33:10 +08:00
ssongliu c06ba18023 feat: compatible with openrc and sysvinit (#10723) 2025-10-22 18:32:42 +08:00
KOMATA f462591e9c feat: add firewall rule import/export with JSON validation and alerts (#10706) 2025-10-22 18:31:26 +08:00
574 changed files with 33492 additions and 14872 deletions
+1
View File
@@ -6,6 +6,7 @@ permissions:
jobs:
generic_handler:
name: Add Labels to PR
if: github.repository == '1Panel-dev/1Panel'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: '1.23'
go-version: '1.24'
- name: Build Release
uses: goreleaser/goreleaser-action@v6
with:
+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: '1.23'
go-version: '1.24'
- name: Build Release
uses: goreleaser/goreleaser-action@v6
with:
+1
View File
@@ -8,6 +8,7 @@ on:
jobs:
sonarcloud:
name: SonarCloud
if: github.repository == '1Panel-dev/1Panel'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
+1
View File
@@ -2,6 +2,7 @@ name: Synchronize to Gitee
on: [push]
jobs:
repo-sync:
if: github.repository == '1Panel-dev/1Panel'
runs-on: ubuntu-latest
steps:
- name: Mirror the Github organization repos to Gitee.
+3 -8
View File
@@ -33,9 +33,6 @@ builds:
- ppc64le
- s390x
- riscv64
hooks:
post:
- ./ci/script.sh compress_binary {{ .Path }} {{ .Arch }}
- id: core
dir: core
@@ -59,9 +56,6 @@ builds:
- ppc64le
- s390x
- riscv64
hooks:
post:
- ./ci/script.sh compress_binary {{ .Path }} {{ .Arch }}
archives:
- formats: [ 'tar.gz' ]
@@ -70,11 +64,12 @@ archives:
wrap_in_directory: true
files:
- 1pctl
- install.sh
- 1panel-core.service
- 1panel-agent.service
- install.sh
- GeoIP.mmdb
- initscript/*
- lang/*
- GeoIP.mmdb
checksum:
name_template: 'checksums.txt'
+5 -5
View File
@@ -30,20 +30,20 @@ build_frontend:
build_core_on_linux:
cd $(CORE_PATH) \
&& GOOS=$(GOOS) GOARCH=$(GOARCH) $(GOBUILD) -trimpath -ldflags '-s -w' -o $(BUILD_PATH)/$(CORE_NAME) $(CORE_MAIN)
&& CGO_ENABLED=0 GOOS=$(GOOS) GOARCH=$(GOARCH) $(GOBUILD) -trimpath -ldflags '-s -w' -o $(BUILD_PATH)/$(CORE_NAME) $(CORE_MAIN)
build_agent_on_linux:
cd $(AGENT_PATH) \
&& GOOS=$(GOOS) GOARCH=$(GOARCH) $(GOBUILD) -trimpath -ldflags '-s -w' -o $(BUILD_PATH)/$(AGENT_NAME) $(AGENT_MAIN)
&& CGO_ENABLED=0 GOOS=$(GOOS) GOARCH=$(GOARCH) $(GOBUILD) -trimpath -ldflags '-s -w' -o $(BUILD_PATH)/$(AGENT_NAME) $(AGENT_MAIN)
build_core_on_darwin:
cd $(CORE_PATH) \
&& GOOS=linux GOARCH=amd64 $(GOBUILD) -trimpath -ldflags '-s -w' -o $(BUILD_PATH)/$(CORE_NAME) $(CORE_MAIN)
&& CGO_ENABLED=0 GOOS=linux GOARCH=amd64 $(GOBUILD) -trimpath -ldflags '-s -w' -o $(BUILD_PATH)/$(CORE_NAME) $(CORE_MAIN)
build_agent_on_darwin:
cd $(AGENT_PATH) \
&& GOOS=linux GOARCH=amd64 $(GOBUILD) -trimpath -ldflags '-s -w' -o $(BUILD_PATH)/$(AGENT_NAME) $(AGENT_MAIN)
&& CGO_ENABLED=0 GOOS=linux GOARCH=amd64 $(GOBUILD) -trimpath -ldflags '-s -w' -o $(BUILD_PATH)/$(AGENT_NAME) $(AGENT_MAIN)
build_all: build_frontend build_core_on_linux build_agent_on_linux
build_on_local: clean_assets build_frontend build_core_on_darwin build_agent_on_darwin upx_bin
build_on_local: clean_assets build_frontend build_core_on_darwin build_agent_on_darwin
+49 -1
View File
@@ -1,6 +1,9 @@
package v2
import (
"net/http"
"time"
"github.com/1Panel-dev/1Panel/agent/app/api/v2/helper"
"github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/dto/request"
@@ -26,7 +29,7 @@ func (b *BaseApi) SearchApp(c *gin.Context) {
helper.InternalServer(c, err)
return
}
helper.SuccessWithData(c, list)
helper.SuccessWithDataGzipped(c, list)
}
// @Tags App
@@ -192,3 +195,48 @@ func (b *BaseApi) GetAppListUpdate(c *gin.Context) {
}
helper.SuccessWithData(c, res)
}
// @Tags App
// @Summary Get app icon by app_id
// @Accept json
// @Param appId path integer true "app id"
// @Success 200 {file} file "app icon"
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /apps/icon/:appId [get]
func (b *BaseApi) GetAppIcon(c *gin.Context) {
appID, err := helper.GetIntParamByKey(c, "appID")
if err != nil {
helper.BadRequest(c, err)
return
}
iconBytes, err := appService.GetAppIcon(appID)
if err != nil {
helper.InternalServer(c, err)
return
}
c.Header("Content-Type", "image/png")
c.Header("Cache-Control", "public, max-age=31536000, immutable")
c.Header("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
c.Data(http.StatusOK, "image/png", iconBytes)
}
// @Tags App
// @Summary Search app detail by appkey and version
// @Accept json
// @Param appId path integer true "app key"
// @Param version path string true "app version"
// @Success 200 {object} response.AppDetailSimpleDTO
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /apps/detail/node/:appKey/:version [get]
func (b *BaseApi) GetAppDetailForNode(c *gin.Context) {
appKey := c.Param("appKey")
version := c.Param("version")
appDetailDTO, err := appService.GetAppDetailByKey(appKey, version)
if err != nil {
helper.InternalServer(c, err)
return
}
helper.SuccessWithData(c, appDetailDTO)
}
+17
View File
@@ -25,6 +25,23 @@ func (b *BaseApi) CheckBackupUsed(c *gin.Context) {
helper.Success(c)
}
// @Tags Backup Account
// @Summary Check backup account
// @Accept json
// @Param request body dto.BackupOperate true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /backups/check [post]
func (b *BaseApi) CheckBackup(c *gin.Context) {
var req dto.BackupOperate
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
helper.SuccessWithData(c, backupService.CheckConn(req))
}
// @Tags Backup Account
// @Summary Create backup account
// @Accept json
+22
View File
@@ -28,6 +28,28 @@ func (b *BaseApi) CreateComposeTemplate(c *gin.Context) {
helper.Success(c)
}
// @Tags Container Compose-template
// @Summary Bacth compose template
// @Accept json
// @Param request body dto.ComposeTemplateBatch true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /containers/template/batch [post]
// @x-panel-log {"bodyKeys":[],"paramKeys":[],"BeforeFunctions":[],"formatZH":"批量导入编排模版","formatEN":"batch import compose templates"}
func (b *BaseApi) BatchComposeTemplate(c *gin.Context) {
var req dto.ComposeTemplateBatch
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
if err := composeTemplateService.Batch(req); err != nil {
helper.InternalServer(c, err)
return
}
helper.Success(c)
}
// @Tags Container Compose-template
// @Summary Page compose templates
// @Accept json
+45 -2
View File
@@ -263,6 +263,27 @@ func (b *BaseApi) ContainerListStats(c *gin.Context) {
helper.SuccessWithData(c, data)
}
// @Summary Load container stats size
// @Accept json
// @Param request body dto.OperationWithName true "request"
// @Success 200 {object} dto.ContainerItemStats
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /containers/item/stats [post]
func (b *BaseApi) ContainerItemStats(c *gin.Context) {
var req dto.OperationWithName
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
data, err := containerService.ContainerItemStats(req)
if err != nil {
helper.InternalServer(c, err)
return
}
helper.SuccessWithData(c, data)
}
// @Tags Container
// @Summary Create container
// @Accept json
@@ -314,7 +335,7 @@ func (b *BaseApi) ContainerCreateByCommand(c *gin.Context) {
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /containers/upgrade [post]
// @x-panel-log {"bodyKeys":["name","image"],"paramKeys":[],"BeforeFunctions":[],"formatZH":"更新容器镜像 [name][image]","formatEN":"upgrade container image [name][image]"}
// @x-panel-log {"bodyKeys":["names","image"],"paramKeys":[],"BeforeFunctions":[],"formatZH":"更新容器镜像 [names][image]","formatEN":"upgrade container image [names][image]"}
func (b *BaseApi) ContainerUpgrade(c *gin.Context) {
var req dto.ContainerUpgrade
if err := helper.CheckBindAndValidate(&req, c); err != nil {
@@ -372,6 +393,28 @@ func (b *BaseApi) CleanContainerLog(c *gin.Context) {
helper.Success(c)
}
// @Tags Container
// @Summary Clean compose log
// @Accept json
// @Param request body dto.ComposeLogClean true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /containers/compose/clean/log [post]
// @x-panel-log {"bodyKeys":["name"],"paramKeys":[],"BeforeFunctions":[],"formatZH":"清理容器编排 [name] 日志","formatEN":"clean compose [name] logs"}
func (b *BaseApi) CleanComposeLog(c *gin.Context) {
var req dto.ComposeLogClean
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
if err := containerService.ComposeLogClean(req); err != nil {
helper.InternalServer(c, err)
return
}
helper.Success(c)
}
// @Tags Container
// @Summary Rename Container
// @Accept json
@@ -481,7 +524,6 @@ func (b *BaseApi) Inspect(c *gin.Context) {
helper.SuccessWithData(c, result)
}
// @Router /containers/download/log [post]
func (b *BaseApi) DownloadContainerLogs(c *gin.Context) {
var req dto.ContainerLog
if err := helper.CheckBindAndValidate(&req, c); err != nil {
@@ -695,6 +737,7 @@ func (b *BaseApi) ComposeUpdate(c *gin.Context) {
// @Param since query string false "时间筛选"
// @Param follow query string false "是否追踪"
// @Param tail query string false "显示行号"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /containers/search/log [get]
+1 -1
View File
@@ -211,7 +211,7 @@ func (b *BaseApi) LoadRecordLog(c *gin.Context) {
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /cronjobs/records/clean [post]
// @x-panel-log {"bodyKeys":["id"],"paramKeys":[],"BeforeFunctions":[{"input_column":"id","input_value":"id","isList":false,"db":"cronjobs","output_column":"name","output_value":"name"}],"formatZH":"清空计划任务记录 [name]","formatEN":"clean cronjob [name] records"}
// @x-panel-log {"bodyKeys":["cronjobID"],"paramKeys":[],"BeforeFunctions":[{"input_column":"id","input_value":"cronjobID","isList":false,"db":"cronjobs","output_column":"name","output_value":"name"}],"formatZH":"清空计划任务记录 [name]","formatEN":"clean cronjob [name] records"}
func (b *BaseApi) CleanRecord(c *gin.Context) {
var req dto.CronjobClean
if err := helper.CheckBindAndValidate(&req, c); err != nil {
+26 -4
View File
@@ -27,7 +27,7 @@ func (b *BaseApi) LoadDashboardOsInfo(c *gin.Context) {
// @Tags Dashboard
// @Summary Load app launcher
// @Accept json
// @Success 200 {Array} dto.AppLauncher
// @Success 200 {array} dto.AppLauncher
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /dashboard/app/launcher [get]
@@ -37,14 +37,14 @@ func (b *BaseApi) LoadAppLauncher(c *gin.Context) {
helper.InternalServer(c, err)
return
}
helper.SuccessWithData(c, data)
helper.SuccessWithDataGzipped(c, data)
}
// @Tags Dashboard
// @Summary Load app launcher options
// @Accept json
// @Param request body dto.SearchByFilter true "request"
// @Success 200 {Array} dto.LauncherOption
// @Success 200 {array} dto.LauncherOption
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /dashboard/app/launcher/option [post]
@@ -85,7 +85,7 @@ func (b *BaseApi) UpdateAppLauncher(c *gin.Context) {
// @Tags Dashboard
// @Summary Load quick jump options
// @Success 200 {Array} dto.QuickJump
// @Success 200 {array} dto.QuickJump
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /dashboard/quick/option [get]
@@ -179,6 +179,28 @@ func (b *BaseApi) LoadDashboardCurrentInfo(c *gin.Context) {
helper.SuccessWithData(c, data)
}
// @Tags Dashboard
// @Summary Load top cpu processes
// @Success 200 {array} dto.Process
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /dashboard/current/top/cpu [get]
func (b *BaseApi) LoadDashboardTopCPU(c *gin.Context) {
data := dashboardService.LoadTopCPU()
helper.SuccessWithData(c, data)
}
// @Tags Dashboard
// @Summary Load top memory processes
// @Success 200 {array} dto.Process
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /dashboard/current/top/mem [get]
func (b *BaseApi) LoadDashboardTopMem(c *gin.Context) {
data := dashboardService.LoadTopMem()
helper.SuccessWithData(c, data)
}
// @Tags Dashboard
// @Summary System restart
// @Accept json
+9 -10
View File
@@ -195,27 +195,26 @@ func (b *BaseApi) SearchMysql(c *gin.Context) {
}
// @Tags Database Mysql
// @Summary List mysql database names
// @Summary List mysql database format collation options
// @Accept json
// @Param request body dto.PageInfo true "request"
// @Success 200 {array} dto.MysqlOption
// @Param request body dto.OperationWithName true "request"
// @Success 200 {array} dto.MysqlFormatCollationOption
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /databases/options [get]
func (b *BaseApi) ListDBName(c *gin.Context) {
list, err := mysqlService.ListDBOption()
if err != nil {
helper.InternalServer(c, err)
// @Router /databases/format/options [post]
func (b *BaseApi) ListDBFormatCollationOptions(c *gin.Context) {
var req dto.OperationWithName
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
helper.SuccessWithData(c, list)
helper.SuccessWithData(c, mysqlService.LoadFormatOption(req))
}
// @Tags Database Mysql
// @Summary Load mysql database from remote
// @Accept json
// @Param request body dto.MysqlLoadDB true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /databases/load [post]
+1
View File
@@ -167,6 +167,7 @@ func (b *BaseApi) SearchPostgresql(c *gin.Context) {
// @Summary Load postgresql database from remote
// @Accept json
// @Param request body dto.PostgresqlLoadDB true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /databases/pg/:database/load [post]
+1 -1
View File
@@ -27,7 +27,7 @@ func (b *BaseApi) LoadDeviceBaseInfo(c *gin.Context) {
// @Tags Device
// @Summary list time zone options
// @Accept json
// @Success 200 {Array} string
// @Success 200 {array} string
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /toolbox/device/zone/options [get]
+1
View File
@@ -38,6 +38,7 @@ var (
fileService = service.NewIFileService()
sshService = service.NewISSHService()
firewallService = service.NewIFirewallService()
iptablesService = service.NewIIptablesService()
monitorService = service.NewIMonitorService()
systemService = service.NewISystemService()
+4 -2
View File
@@ -28,7 +28,7 @@ func (b *BaseApi) LoadFail2BanBaseInfo(c *gin.Context) {
// @Summary Page fail2ban ip list
// @Accept json
// @Param request body dto.Fail2BanSearch true "request"
// @Success 200 {Array} string
// @Success 200 {array} string
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /toolbox/fail2ban/search [post]
@@ -51,6 +51,7 @@ func (b *BaseApi) SearchFail2Ban(c *gin.Context) {
// @Summary Operate fail2ban
// @Accept json
// @Param request body dto.Operate true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /toolbox/fail2ban/operate [post]
@@ -72,7 +73,8 @@ func (b *BaseApi) OperateFail2Ban(c *gin.Context) {
// @Tags Fail2ban
// @Summary Operate sshd of fail2ban
// @Accept json
// @Param request body dto.Operate true "request"
// @Param request body dto.Fail2BanSet true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /toolbox/fail2ban/operate/sshd [post]
+39 -3
View File
@@ -90,7 +90,7 @@ func (b *BaseApi) GetFileTree(c *gin.Context) {
helper.InternalServer(c, err)
return
}
helper.SuccessWithData(c, tree)
helper.SuccessWithDataGzipped(c, tree)
}
// @Tags File
@@ -265,6 +265,33 @@ func (b *BaseApi) GetContent(c *gin.Context) {
helper.InternalServer(c, err)
return
}
if info.Size > 2*1024 && info.Size < 5*1024*1024 {
helper.SuccessWithDataGzipped(c, info)
} else {
helper.SuccessWithData(c, info)
}
}
// @Tags File
// @Summary Preview file content
// @Accept json
// @Param request body request.FileContentReq true "request"
// @Success 200 {object} response.FileInfo
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /files/preview [post]
// @x-panel-log {"bodyKeys":["path"],"paramKeys":[],"BeforeFunctions":[],"formatZH":"预览文件内容 [path]","formatEN":"Preview file content [path]"}
func (b *BaseApi) PreviewContent(c *gin.Context) {
var req request.FileContentReq
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
info, err := fileService.GetPreviewContent(req)
if err != nil {
helper.InternalServer(c, err)
return
}
helper.SuccessWithData(c, info)
}
@@ -521,9 +548,14 @@ func (b *BaseApi) Download(c *gin.Context) {
file, err := os.Open(filePath)
if err != nil {
helper.InternalServer(c, err)
return
}
defer file.Close()
info, _ := file.Stat()
info, err := file.Stat()
if err != nil {
helper.InternalServer(c, err)
return
}
c.Header("Content-Length", strconv.FormatInt(info.Size(), 10))
c.Header("Content-Disposition", "attachment; filename*=utf-8''"+url.PathEscape(info.Name()))
http.ServeContent(c.Writer, c.Request, info.Name(), info.ModTime(), file)
@@ -841,7 +873,11 @@ func (b *BaseApi) ReadFileByLine(c *gin.Context) {
helper.InternalServer(c, err)
return
}
helper.SuccessWithData(c, res)
if res.TotalLines > 100 {
helper.SuccessWithDataGzipped(c, res)
} else {
helper.SuccessWithData(c, res)
}
}
// @Tags File
+124 -8
View File
@@ -8,12 +8,19 @@ import (
// @Tags Firewall
// @Summary Load firewall base info
// @Accept json
// @Param request body dto.OperationWithName true "request"
// @Success 200 {object} dto.FirewallBaseInfo
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /hosts/firewall/base [get]
// @Router /hosts/firewall/base [post]
func (b *BaseApi) LoadFirewallBaseInfo(c *gin.Context) {
data, err := firewallService.LoadBaseInfo()
var req dto.OperationWithName
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
data, err := firewallService.LoadBaseInfo(req.Name)
if err != nil {
helper.InternalServer(c, err)
return
@@ -95,14 +102,14 @@ func (b *BaseApi) OperatePortRule(c *gin.Context) {
// OperateForwardRule
// @Tags Firewall
// @Summary Create group
// @Summary Operate forward rule
// @Accept json
// @Param request body dto.ForwardRuleOperate true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /hosts/firewall/forward [post]
// @x-panel-log {"bodyKeys":["source_port"],"paramKeys":[],"BeforeFunctions":[],"formatZH":"更新端口转发规则 [source_port]","formatEN":"update port forward rules [source_port]"}
// @x-panel-log {"bodyKeys":[],"paramKeys":[],"BeforeFunctions":[],"formatZH":"更新端口转发规则","formatEN":"update port forward rules"}
func (b *BaseApi) OperateForwardRule(c *gin.Context) {
var req dto.ForwardRuleOperate
if err := helper.CheckBindAndValidate(&req, c); err != nil {
@@ -117,7 +124,7 @@ func (b *BaseApi) OperateForwardRule(c *gin.Context) {
}
// @Tags Firewall
// @Summary Create group
// @Summary Operate Ip rule
// @Accept json
// @Param request body dto.AddrRuleOperate true "request"
// @Success 200
@@ -139,7 +146,7 @@ func (b *BaseApi) OperateIPRule(c *gin.Context) {
}
// @Tags Firewall
// @Summary Create group
// @Summary Batch operate rule
// @Accept json
// @Param request body dto.BatchRuleOperate true "request"
// @Success 200
@@ -181,7 +188,7 @@ func (b *BaseApi) UpdateFirewallDescription(c *gin.Context) {
}
// @Tags Firewall
// @Summary Create group
// @Summary Update port rule
// @Accept json
// @Param request body dto.PortRuleUpdate true "request"
// @Success 200
@@ -202,7 +209,7 @@ func (b *BaseApi) UpdatePortRule(c *gin.Context) {
}
// @Tags Firewall
// @Summary Create group
// @Summary Update Ip rule
// @Accept json
// @Param request body dto.AddrRuleUpdate true "request"
// @Success 200
@@ -221,3 +228,112 @@ func (b *BaseApi) UpdateAddrRule(c *gin.Context) {
}
helper.Success(c)
}
// @Tags Firewall
// @Summary search iptables filter rules
// @Accept json
// @Param request body dto.SearchPageWithType true "request"
// @Success 200 {object} dto.PageResult
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /hosts/firewall/filter/search [post]
func (b *BaseApi) SearchFilterRules(c *gin.Context) {
var req dto.SearchPageWithType
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
total, list, err := iptablesService.Search(req)
if err != nil {
helper.InternalServer(c, err)
return
}
helper.SuccessWithData(c, dto.PageResult{
Items: list,
Total: total,
})
}
// @Tags Firewall
// @Summary Operate iptables filter rule
// @Accept json
// @Param request body dto.IptablesRuleOp true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /hosts/firewall/filter/rule/operate [post]
// @x-panel-log {"bodyKeys":["operation","chain"],"paramKeys":[],"BeforeFunctions":[],"formatZH":"[operation] filter规则到 [chain]","formatEN":"[operation] filter rule to [chain]"}
func (b *BaseApi) OperateFilterRule(c *gin.Context) {
var req dto.IptablesRuleOp
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
if err := iptablesService.OperateRule(req, true); err != nil {
helper.InternalServer(c, err)
return
}
helper.Success(c)
}
// @Tags Firewall
// @Summary Batch operate iptables filter rules
// @Accept json
// @Param request body dto.IptablesBatchOperate true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /hosts/firewall/filter/rule/batch [post]
func (b *BaseApi) BatchOperateFilterRule(c *gin.Context) {
var req dto.IptablesBatchOperate
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
if err := iptablesService.BatchOperate(req); err != nil {
helper.InternalServer(c, err)
return
}
helper.Success(c)
}
// @Tags Firewall
// @Summary Apply/Unload/Init iptables filter
// @Accept json
// @Param request body dto.IptablesOp true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /hosts/firewall/filter/operate [post]
// @x-panel-log {"bodyKeys":["operate"],"paramKeys":[],"BeforeFunctions":[],"formatZH":"[operate] iptables filter 防火墙","formatEN":"[operate] iptables filter firewall"}
func (b *BaseApi) OperateFilterChain(c *gin.Context) {
var req dto.IptablesOp
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
if err := iptablesService.Operate(req); err != nil {
helper.InternalServer(c, err)
return
}
helper.Success(c)
}
// @Tags Firewall
// @Summary load chain status with name
// @Accept json
// @Param request body dto.OperationWithName true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /hosts/firewall/filter/chain/status [post]
func (b *BaseApi) LoadChainStatus(c *gin.Context) {
var req dto.OperationWithName
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
helper.SuccessWithData(c, iptablesService.LoadChainStatus(req))
}
+1
View File
@@ -54,6 +54,7 @@ func (b *BaseApi) LoadFtpLogInfo(c *gin.Context) {
// @Summary Operate FTP
// @Accept json
// @Param request body dto.Operate true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /toolbox/ftp/operate [post]
+40
View File
@@ -1,10 +1,14 @@
package helper
import (
"compress/gzip"
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"sync"
"github.com/1Panel-dev/1Panel/agent/global"
"gorm.io/gorm"
@@ -46,6 +50,42 @@ func SuccessWithData(ctx *gin.Context, data interface{}) {
ctx.Abort()
}
var gzipWriterPool = sync.Pool{
New: func() interface{} {
return gzip.NewWriter(nil)
},
}
func SuccessWithDataGzipped(ctx *gin.Context, data interface{}) {
if !strings.Contains(ctx.GetHeader("Accept-Encoding"), "gzip") {
SuccessWithData(ctx, data)
return
}
if data == nil {
data = gin.H{}
}
res := dto.Response{
Code: http.StatusOK,
Data: data,
}
jsonBytes, err := json.Marshal(res)
if err != nil {
ErrorWithDetail(ctx, http.StatusInternalServerError, "ErrInternalServer", err)
return
}
ctx.Header("Content-Encoding", "gzip")
ctx.Header("Content-Type", "application/json; charset=utf-8")
ctx.Status(http.StatusOK)
gz := gzipWriterPool.Get().(*gzip.Writer)
gz.Reset(ctx.Writer)
_, _ = gz.Write(jsonBytes)
_ = gz.Close()
gzipWriterPool.Put(gz)
ctx.Abort()
}
func Success(ctx *gin.Context) {
res := dto.Response{
Code: http.StatusOK,
+25
View File
@@ -28,6 +28,27 @@ func (b *BaseApi) LoadMonitor(c *gin.Context) {
helper.InternalServer(c, err)
return
}
helper.SuccessWithDataGzipped(c, data)
}
// @Tags Monitor
// @Summary Load monitor data
// @Param request body dto.MonitorGPUSearch true "request"
// @Success 200 {object} dto.MonitorGPUData
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /hosts/monitor/gpu/search [post]
func (b *BaseApi) LoadGPUMonitor(c *gin.Context) {
var req dto.MonitorGPUSearch
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
data, err := monitorService.LoadGPUMonitorData(req)
if err != nil {
helper.InternalServer(c, err)
return
}
helper.SuccessWithData(c, data)
}
@@ -105,3 +126,7 @@ func (b *BaseApi) GetIOOptions(c *gin.Context) {
sort.Strings(options)
helper.SuccessWithData(c, options)
}
func (b *BaseApi) GetCPUOptions(c *gin.Context) {
helper.SuccessWithData(c, monitorService.LoadGPUOptions())
}
+2 -2
View File
@@ -161,13 +161,13 @@ func (b *BaseApi) GetNginxModules(c *gin.Context) {
// @Tags OpenResty
// @Summary Operate default HTTPs
// @Accept json
// @Param request body request.NginxOperateReq true "request"
// @Param request body request.NginxDefaultHTTPSUpdate true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /openresty/https [post]
func (b *BaseApi) OperateDefaultHTTPs(c *gin.Context) {
var req request.NginxOperateReq
var req request.NginxDefaultHTTPSUpdate
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
+1 -1
View File
@@ -40,7 +40,7 @@ func (b *BaseApi) StopProcess(c *gin.Context) {
// @Tags Process
// @Summary Get Process Info By PID
// @Param pid path int true "PID"
// @Success 200 {object} websocket.PsProcessData
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /process/{pid} [get]
+44 -1
View File
@@ -84,9 +84,31 @@ func (b *BaseApi) CheckLocalConn(c *gin.Context) {
helper.SuccessWithData(c, err == nil)
}
// @Tags System Setting
// @Summary Update local is conn
// @Accept json
// @Param request body dto.SSHDefaultConn true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /settings/ssh/conn/default [post]
// @x-panel-log {"bodyKeys":["defaultConn"],"paramKeys":[],"BeforeFunctions":[],"formatZH":"本地终端默认连接 [defaultConn]","formatEN":"update system default conn [defaultConn]"}
func (b *BaseApi) SetDefaultIsConn(c *gin.Context) {
var req dto.SSHDefaultConn
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
if err := settingService.SetDefaultIsConn(req); err != nil {
helper.InternalServer(c, err)
return
}
helper.Success(c)
}
// @Tags System Setting
// @Summary Check local conn info
// @Success 200 {bool} isOk
// @Success 200 {boolean} isOk
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /settings/ssh/check/info [post]
@@ -155,3 +177,24 @@ func (b *BaseApi) GetSettingByKey(c *gin.Context) {
value := settingService.GetSettingByKey(key)
helper.SuccessWithData(c, value)
}
// @Tags System Setting
// @Summary Save common description
// @Accept json
// @Param request body dto.CommonDescription true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /settings/description/save [post]
func (b *BaseApi) SaveDescription(c *gin.Context) {
var req dto.CommonDescription
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
if err := settingService.SaveDescription(req); err != nil {
helper.InternalServer(c, err)
return
}
helper.Success(c)
}
+1 -1
View File
@@ -53,7 +53,7 @@ func (b *BaseApi) OperateSSH(c *gin.Context) {
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /hosts/ssh/update [post]
// @x-panel-log {"bodyKeys":["key","value"],"paramKeys":[],"BeforeFunctions":[],"formatZH":"修改 SSH 配置 [key] => [value]","formatEN":"update SSH setting [key] => [value]"}
// @x-panel-log {"bodyKeys":["key","newValue"],"paramKeys":[],"BeforeFunctions":[],"formatZH":"修改 SSH 配置 [key] => [newValue]","formatEN":"update SSH setting [key] => [newValue]"}
func (b *BaseApi) UpdateSSH(c *gin.Context) {
var req dto.SSHUpdate
if err := helper.CheckBindAndValidate(&req, c); err != nil {
+1 -1
View File
@@ -9,7 +9,7 @@ import (
// @Tags Host
// @Summary Check if a system component exists
// @Accept json
// @Param name query string true "Component name to check (e.g., rsync, docker)"
// @Param name path string true "Component name to check (e.g., rsync, docker)"
// @Success 200 {object} response.ComponentInfo
// @Security ApiKeyAuth
// @Security Timestamp
+2 -2
View File
@@ -228,8 +228,8 @@ func wshandleError(ws *websocket.Conn, err error) bool {
}
var upGrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024 * 1024 * 10,
ReadBufferSize: 4096,
WriteBufferSize: 16384,
CheckOrigin: func(r *http.Request) bool {
return true
},
+63 -3
View File
@@ -73,7 +73,7 @@ func (b *BaseApi) GetWebsiteOptions(c *gin.Context) {
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /websites [post]
// @x-panel-log {"bodyKeys":["primaryDomain"],"paramKeys":[],"BeforeFunctions":[],"formatZH":"创建网站 [primaryDomain]","formatEN":"Create website [primaryDomain]"}
// @x-panel-log {"bodyKeys":["alias"],"paramKeys":[],"BeforeFunctions":[],"formatZH":"创建网站 [alias]","formatEN":"Create website [alias]"}
func (b *BaseApi) CreateWebsite(c *gin.Context) {
var req request.WebsiteCreate
if err := helper.CheckBindAndValidate(&req, c); err != nil {
@@ -672,7 +672,7 @@ func (b *BaseApi) UpdateAntiLeech(c *gin.Context) {
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /websites/redirect/update [post]
// @x-panel-log {"bodyKeys":["websiteID"],"paramKeys":[],"BeforeFunctions":[{"input_column":"id","input_value":"websiteID","isList":false,"db":"websites","output_column":"primary_domain","output_value":"domain"}],"formatZH":"修改网站 [domain] 重定向理配置 ","formatEN":"Update domain [domain] redirect config"}
// @x-panel-log {"bodyKeys":["websiteID"],"paramKeys":[],"BeforeFunctions":[{"input_column":"id","input_value":"websiteID","isList":false,"db":"websites","output_column":"primary_domain","output_value":"domain"}],"formatZH":"修改网站 [domain] 重定向配置 ","formatEN":"Update domain [domain] redirect config"}
func (b *BaseApi) UpdateRedirectConfig(c *gin.Context) {
var req request.NginxRedirectReq
if err := helper.CheckBindAndValidate(&req, c); err != nil {
@@ -1145,7 +1145,7 @@ func (b *BaseApi) ExecComposer(c *gin.Context) {
// @Tags Website
// @Summary Batch operate websites
// @Accept json
// @Param request body request.BatchOpWebsite true "request"
// @Param request body request.BatchWebsiteOp true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
@@ -1162,6 +1162,26 @@ func (b *BaseApi) BatchOpWebsites(c *gin.Context) {
helper.Success(c)
}
// @Tags Website
// @Summary Batch set website group
// @Accept json
// @Param request body request.BatchWebsiteGroup true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /websites/batch/group [post]
func (b *BaseApi) BatchSetWebsiteGroup(c *gin.Context) {
var req request.BatchWebsiteGroup
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
if err := websiteService.BatchSetGroup(req); err != nil {
helper.InternalServer(c, err)
return
}
helper.Success(c)
}
// @Tags Website
// @Summary Get CORS Config
// @Accept json
@@ -1203,3 +1223,43 @@ func (b *BaseApi) UpdateCORSConfig(c *gin.Context) {
}
helper.Success(c)
}
// @Tags Website
// @Summary Update Stream Config
// @Accept json
// @Param request body request.StreamUpdate true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /websites/stream/update [post]
func (b *BaseApi) UpdateStreamConfig(c *gin.Context) {
var req request.StreamUpdate
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
if err := websiteService.UpdateStream(req); err != nil {
helper.InternalServer(c, err)
return
}
helper.Success(c)
}
// @Tags Website
// @Summary Batch set HTTPS for websites
// @Accept json
// @Param request body request.BatchWebsiteHttps true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /websites/batch/https [post]
func (b *BaseApi) BatchSetHttps(c *gin.Context) {
var req request.BatchWebsiteHttps
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
if err := websiteService.BatchSetHttps(c, req); err != nil {
helper.InternalServer(c, err)
return
}
helper.Success(c)
}
+5 -5
View File
@@ -1,7 +1,6 @@
package v2
import (
"github.com/1Panel-dev/1Panel/agent/app/model"
"io"
"mime/multipart"
"net/http"
@@ -9,6 +8,8 @@ import (
"reflect"
"strconv"
"github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/app/api/v2/helper"
"github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/dto/request"
@@ -34,7 +35,7 @@ func (b *BaseApi) PageWebsiteSSL(c *gin.Context) {
helper.InternalServer(c, err)
return
}
helper.SuccessWithData(c, dto.PageResult{
helper.SuccessWithDataGzipped(c, dto.PageResult{
Total: total,
Items: accounts,
})
@@ -44,7 +45,7 @@ func (b *BaseApi) PageWebsiteSSL(c *gin.Context) {
helper.InternalServer(c, err)
return
}
helper.SuccessWithData(c, list)
helper.SuccessWithDataGzipped(c, list)
}
}
@@ -235,7 +236,6 @@ func (b *BaseApi) UploadWebsiteSSL(c *gin.Context) {
func (b *BaseApi) UploadSSLFile(c *gin.Context) {
var req request.WebsiteSSLFileUpload
req.Type = c.PostForm("type")
req.Description = c.PostForm("description")
sslID := c.PostForm("sslID")
if sslID != "" {
@@ -279,7 +279,7 @@ func (b *BaseApi) UploadSSLFile(c *gin.Context) {
return
}
helper.SuccessWithData(c, nil)
helper.Success(c)
}
func readUploadedFile(fileHeader *multipart.FileHeader) ([]byte, error) {
+1 -1
View File
@@ -317,7 +317,7 @@ type AlertCommonConfig struct {
type AlertSmsConfig struct {
Phone string `json:"phone"`
AlertDailyNum uint `json:"alertDailyNum"`
AlertDailyNum string `json:"alertDailyNum"`
}
type AlertEmailConfig struct {
+22 -19
View File
@@ -12,6 +12,8 @@ type AppDatabase struct {
DbUser string `json:"PANEL_DB_USER"`
Password string `json:"PANEL_DB_USER_PASSWORD"`
DatabaseName string `json:"DATABASE_NAME"`
Format string `json:"format"`
Collation string `json:"collation"`
}
type AuthParam struct {
@@ -82,25 +84,26 @@ type ExtraProperties struct {
}
type AppProperty struct {
Name string `json:"name"`
Type string `json:"type"`
Tags []string `json:"tags"`
ShortDescZh string `json:"shortDescZh" yaml:"shortDescZh"`
ShortDescEn string `json:"shortDescEn" yaml:"shortDescEn"`
Description Locale `json:"description"`
Key string `json:"key"`
Required []string `json:"Required"`
CrossVersionUpdate bool `json:"crossVersionUpdate"`
Limit int `json:"limit"`
Recommend int `json:"recommend"`
Website string `json:"website"`
Github string `json:"github"`
Document string `json:"document"`
Architectures []string `json:"architectures"`
MemoryRequired int `json:"memoryRequired"`
GpuSupport bool `json:"gpuSupport"`
Version float64 `json:"version"`
Deprecated float64 `json:"deprecated"`
Name string `json:"name"`
Type string `json:"type"`
Tags []string `json:"tags"`
ShortDescZh string `json:"shortDescZh" yaml:"shortDescZh"`
ShortDescEn string `json:"shortDescEn" yaml:"shortDescEn"`
Description Locale `json:"description"`
Key string `json:"key"`
Required []string `json:"Required"`
CrossVersionUpdate bool `json:"crossVersionUpdate" yaml:"crossVersionUpdate"`
Limit int `json:"limit" yaml:"limit"`
Recommend int `json:"recommend" yaml:"recommend"`
Website string `json:"website"`
Github string `json:"github"`
Document string `json:"document"`
Architectures []string `json:"architectures"`
MemoryRequired int `json:"memoryRequired" yaml:"memoryRequired"`
GpuSupport bool `json:"gpuSupport" yaml:"gpuSupport"`
Version float64 `json:"version"`
Deprecated float64 `json:"deprecated"`
BatchInstallSupport bool `json:"batchInstallSupport"`
}
type AppConfigVersion struct {
+7
View File
@@ -33,6 +33,12 @@ type BackupInfo struct {
RememberAuth bool `json:"rememberAuth"`
}
type BackupCheckRes struct {
IsOk bool `json:"isOk"`
Msg string `json:"msg"`
Token string `json:"token"`
}
type ForBuckets struct {
Type string `json:"type" validate:"required"`
AccessKey string `json:"accessKey"`
@@ -77,6 +83,7 @@ type CommonRecover struct {
Secret string `json:"secret"`
TaskID string `json:"taskID"`
BackupRecordID uint `json:"backupRecordID"`
Timeout int `json:"timeout"`
}
type RecordSearch struct {
+4
View File
@@ -8,6 +8,10 @@ type ComposeTemplateCreate struct {
Content string `json:"content"`
}
type ComposeTemplateBatch struct {
Templates []ComposeTemplateCreate `json:"templates" validate:"required"`
}
type ComposeTemplateUpdate struct {
ID uint `json:"id"`
Description string `json:"description"`
+67 -40
View File
@@ -15,8 +15,9 @@ type PageContainer struct {
}
type InspectReq struct {
ID string `json:"id" validate:"required"`
Type string `json:"type" validate:"required"`
ID string `json:"id" validate:"required"`
Type string `json:"type" validate:"required"`
Detail string `json:"detail"`
}
type ContainerInfo struct {
@@ -37,6 +38,9 @@ type ContainerInfo struct {
AppName string `json:"appName"`
AppInstallName string `json:"appInstallName"`
Websites []string `json:"websites"`
IsPinned bool `json:"isPinned"`
Description string `json:"description"`
}
type ContainerOptions struct {
@@ -45,14 +49,13 @@ type ContainerOptions struct {
}
type ContainerStatus struct {
All uint `json:"all"`
Created uint `json:"created"`
Running uint `json:"running"`
Paused uint `json:"paused"`
Restarting uint `json:"restarting"`
Removing uint `json:"removing"`
Exited uint `json:"exited"`
Dead uint `json:"dead"`
Created int `json:"created"`
Running int `json:"running"`
Paused int `json:"paused"`
Restarting int `json:"restarting"`
Removing int `json:"removing"`
Exited int `json:"exited"`
Dead int `json:"dead"`
ContainerCount int `json:"containerCount"`
ComposeCount int `json:"composeCount"`
@@ -61,8 +64,6 @@ type ContainerStatus struct {
NetworkCount int `json:"networkCount"`
VolumeCount int `json:"volumeCount"`
RepoCount int `json:"repoCount"`
ImageSize uint64 `json:"imageSize"`
}
type ResourceLimit struct {
CPU int `json:"cpu"`
@@ -70,17 +71,16 @@ type ResourceLimit struct {
}
type ContainerOperate struct {
TaskID string `json:"taskID"`
ForcePull bool `json:"forcePull"`
Name string `json:"name" validate:"required"`
Image string `json:"image" validate:"required"`
Network string `json:"network"`
Hostname string `json:"hostname"`
DomainName string `json:"domainName"`
MacAddr string `json:"macAddr"`
DNS []string `json:"dns"`
Ipv4 string `json:"ipv4"`
Ipv6 string `json:"ipv6"`
TaskID string `json:"taskID"`
ForcePull bool `json:"forcePull"`
Name string `json:"name" validate:"required"`
Image string `json:"image" validate:"required"`
Hostname string `json:"hostname"`
DomainName string `json:"domainName"`
DNS []string `json:"dns"`
Networks []ContainerNetwork `json:"networks"`
PublishAllPorts bool `json:"publishAllPorts"`
ExposedPorts []PortHelper `json:"exposedPorts"`
Tty bool `json:"tty"`
@@ -99,6 +99,12 @@ type ContainerOperate struct {
Env []string `json:"env"`
RestartPolicy string `json:"restartPolicy"`
}
type ContainerNetwork struct {
Network string `json:"network"`
Ipv4 string `json:"ipv4"`
Ipv6 string `json:"ipv6"`
MacAddr string `json:"macAddr"`
}
type ContainerCreateByCommand struct {
TaskID string `json:"taskID"`
@@ -112,6 +118,19 @@ type ContainerUpgrade struct {
ForcePull bool `json:"forcePull"`
}
type ContainerItemStats struct {
SizeRw int64 `json:"sizeRw"`
SizeRootFs int64 `json:"sizeRootFs"`
ContainerUsage int64 `json:"containerUsage"`
ContainerReclaimable int64 `json:"containerReclaimable"`
ImageUsage int64 `json:"imageUsage"`
ImageReclaimable int64 `json:"imageReclaimable"`
VolumeUsage int64 `json:"volumeUsage"`
VolumeReclaimable int64 `json:"volumeReclaimable"`
BuildCacheUsage int64 `json:"buildCacheUsage"`
BuildCacheReclaimable int64 `json:"buildCacheReclaimable"`
}
type ContainerListStats struct {
ContainerID string `json:"containerID"`
@@ -153,6 +172,7 @@ type PortHelper struct {
}
type ContainerOperation struct {
TaskID string `json:"taskID"`
Names []string `json:"names" validate:"required"`
Operation string `json:"operation" validate:"required,oneof=up start stop restart kill pause unpause remove"`
}
@@ -242,35 +262,42 @@ type ComposeInfo struct {
Workdir string `json:"workdir"`
Path string `json:"path"`
Containers []ComposeContainer `json:"containers"`
Env []string `json:"env"`
Env string `json:"env"`
}
type ComposeContainer struct {
ContainerID string `json:"containerID"`
Name string `json:"name"`
CreateTime string `json:"createTime"`
State string `json:"state"`
ContainerID string `json:"containerID"`
Name string `json:"name"`
CreateTime string `json:"createTime"`
State string `json:"state"`
Ports []string `json:"ports"`
}
type ComposeCreate struct {
TaskID string `json:"taskID"`
Name string `json:"name"`
From string `json:"from" validate:"required,oneof=edit path template"`
File string `json:"file"`
Path string `json:"path"`
Template uint `json:"template"`
Env []string `json:"env"`
TaskID string `json:"taskID"`
Name string `json:"name"`
From string `json:"from" validate:"required,oneof=edit path template"`
File string `json:"file"`
Path string `json:"path"`
Template uint `json:"template"`
Env string `json:"env"`
}
type ComposeOperation struct {
Name string `json:"name" validate:"required"`
Path string `json:"path"`
Operation string `json:"operation" validate:"required,oneof=up start restart stop down delete"`
WithFile bool `json:"withFile"`
Force bool `josn:"force"`
Force bool `json:"force"`
}
type ComposeUpdate struct {
Name string `json:"name" validate:"required"`
Path string `json:"path" validate:"required"`
Content string `json:"content" validate:"required"`
Env []string `json:"env"`
Name string `json:"name" validate:"required"`
Path string `json:"path" validate:"required"`
DetailPath string `json:"detailPath"`
Content string `json:"content" validate:"required"`
Env string `json:"env"`
}
type ComposeLogClean struct {
Name string `json:"name" validate:"required"`
Path string `json:"path" validate:"required"`
DetailPath string `json:"detailPath"`
}
type ContainerLog struct {
+6
View File
@@ -53,6 +53,12 @@ type CronjobOperate struct {
AlertCount uint `json:"alertCount"`
AlertTitle string `json:"alertTitle"`
AlertMethod string `json:"alertMethod"`
CleanLogConfig
}
type CleanLogConfig struct {
Scopes []string `json:"scopes"`
}
type SnapshotRule struct {
+18 -10
View File
@@ -13,15 +13,17 @@ type DashboardBase struct {
Platform string `json:"platform"`
PlatformFamily string `json:"platformFamily"`
PlatformVersion string `json:"platformVersion"`
PrettyDistro string `json:"prettyDistro"`
KernelArch string `json:"kernelArch"`
KernelVersion string `json:"kernelVersion"`
VirtualizationSystem string `json:"virtualizationSystem"`
IpV4Addr string `json:"ipV4Addr"`
SystemProxy string `json:"systemProxy"`
CPUCores int `json:"cpuCores"`
CPULogicalCores int `json:"cpuLogicalCores"`
CPUModelName string `json:"cpuModelName"`
CPUCores int `json:"cpuCores"`
CPULogicalCores int `json:"cpuLogicalCores"`
CPUModelName string `json:"cpuModelName"`
CPUMhz float64 `json:"cpuMhz"`
QuickJumps []QuickJump `json:"quickJump"`
CurrentInfo DashboardCurrent `json:"currentInfo"`
@@ -48,6 +50,7 @@ type OsInfo struct {
PlatformFamily string `json:"platformFamily"`
KernelArch string `json:"kernelArch"`
KernelVersion string `json:"kernelVersion"`
PrettyDistro string `json:"prettyDistro"`
DiskSize int64 `json:"diskSize"`
}
@@ -58,9 +61,10 @@ type NodeCurrent struct {
Load15 float64 `json:"load15"`
LoadUsagePercent float64 `json:"loadUsagePercent"`
CPUUsedPercent float64 `json:"cpuUsedPercent"`
CPUUsed float64 `json:"cpuUsed"`
CPUTotal int `json:"cpuTotal"`
CPUUsedPercent float64 `json:"cpuUsedPercent"`
CPUUsed float64 `json:"cpuUsed"`
CPUTotal int `json:"cpuTotal"`
CPUDetailedPercent []float64 `json:"cpuDetailedPercent"`
MemoryTotal uint64 `json:"memoryTotal"`
MemoryAvailable uint64 `json:"memoryAvailable"`
@@ -84,10 +88,11 @@ type DashboardCurrent struct {
Load15 float64 `json:"load15"`
LoadUsagePercent float64 `json:"loadUsagePercent"`
CPUPercent []float64 `json:"cpuPercent"`
CPUUsedPercent float64 `json:"cpuUsedPercent"`
CPUUsed float64 `json:"cpuUsed"`
CPUTotal int `json:"cpuTotal"`
CPUPercent []float64 `json:"cpuPercent"`
CPUUsedPercent float64 `json:"cpuUsedPercent"`
CPUUsed float64 `json:"cpuUsed"`
CPUTotal int `json:"cpuTotal"`
CPUDetailedPercent []float64 `json:"cpuDetailedPercent"`
MemoryTotal uint64 `json:"memoryTotal"`
MemoryUsed uint64 `json:"memoryUsed"`
@@ -116,6 +121,9 @@ type DashboardCurrent struct {
GPUData []GPUInfo `json:"gpuData"`
XPUData []XPUInfo `json:"xpuData"`
TopCPUItems []Process `json:"topCPUItems"`
TopMemItems []Process `json:"topMemItems"`
ShotTime time.Time `json:"shotTime"`
}
+26 -16
View File
@@ -38,6 +38,7 @@ type MysqlDBInfo struct {
From string `json:"from"`
MysqlName string `json:"mysqlName"`
Format string `json:"format"`
Collation string `json:"collation"`
Username string `json:"username"`
Password string `json:"password"`
Permission string `json:"permission"`
@@ -57,13 +58,19 @@ type MysqlDBCreate struct {
Name string `json:"name" validate:"required"`
From string `json:"from" validate:"required,oneof=local remote"`
Database string `json:"database" validate:"required"`
Format string `json:"format" validate:"required,oneof=utf8mb4 utf8 gbk big5"`
Format string `json:"format" validate:"required"`
Collation string `json:"collation"`
Username string `json:"username" validate:"required"`
Password string `json:"password" validate:"required"`
Permission string `json:"permission" validate:"required"`
Description string `json:"description"`
}
type MysqlFormatCollationOption struct {
Format string `json:"format"`
Collations []string `json:"collations"`
}
type BindUser struct {
Database string `json:"database" validate:"required"`
DB string `json:"db" validate:"required"`
@@ -251,6 +258,7 @@ type DatabaseInfo struct {
Version string `json:"version"`
Address string `json:"address"`
Port uint `json:"port"`
InitialDB string `json:"initialDB"`
Username string `json:"username"`
Password string `json:"password"`
@@ -281,14 +289,15 @@ type DatabaseItem struct {
}
type DatabaseCreate struct {
Name string `json:"name" validate:"required,max=256"`
Type string `json:"type" validate:"required"`
From string `json:"from" validate:"required,oneof=local remote"`
Version string `json:"version" validate:"required"`
Address string `json:"address"`
Port uint `json:"port"`
Username string `json:"username" validate:"required"`
Password string `json:"password"`
Name string `json:"name" validate:"required,max=256"`
Type string `json:"type" validate:"required"`
From string `json:"from" validate:"required,oneof=local remote"`
Version string `json:"version" validate:"required"`
Address string `json:"address"`
Port uint `json:"port"`
InitialDB string `json:"initialDB"`
Username string `json:"username" validate:"required"`
Password string `json:"password"`
SSL bool `json:"ssl"`
RootCert string `json:"rootCert"`
@@ -301,13 +310,14 @@ type DatabaseCreate struct {
}
type DatabaseUpdate struct {
ID uint `json:"id"`
Type string `json:"type" validate:"required"`
Version string `json:"version" validate:"required"`
Address string `json:"address"`
Port uint `json:"port"`
Username string `json:"username" validate:"required"`
Password string `json:"password"`
ID uint `json:"id"`
Type string `json:"type" validate:"required"`
Version string `json:"version" validate:"required"`
Address string `json:"address"`
Port uint `json:"port"`
InitialDB string `json:"initialDB"`
Username string `json:"username" validate:"required"`
Password string `json:"password"`
SSL bool `json:"ssl"`
RootCert string `json:"rootCert"`
+38 -3
View File
@@ -4,6 +4,8 @@ type FirewallBaseInfo struct {
Name string `json:"name"`
IsExist bool `json:"isExist"`
IsActive bool `json:"isActive"`
IsInit bool `json:"isInit"`
IsBind bool `json:"isBind"`
Version string `json:"version"`
PingStatus string `json:"pingStatus"`
}
@@ -17,12 +19,14 @@ type RuleSearch struct {
}
type FirewallOperation struct {
Operation string `json:"operation" validate:"required,oneof=start stop restart disablePing enablePing"`
Operation string `json:"operation" validate:"required,oneof=start stop restart disableBanPing enableBanPing"`
WithDockerRestart bool `json:"withDockerRestart"`
}
type PortRuleOperate struct {
ID uint `json:"id"`
Operation string `json:"operation" validate:"required,oneof=add remove"`
Chain string `json:"chain"`
Address string `json:"address"`
Port string `json:"port" validate:"required"`
Protocol string `json:"protocol" validate:"required,oneof=tcp udp tcp/udp"`
@@ -46,8 +50,11 @@ type ForwardRuleOperate struct {
type UpdateFirewallDescription struct {
Type string `json:"type"`
Address string `json:"address"`
Port string `json:"port"`
Chain string `json:"chain"`
SrcIP string `json:"srcIP"`
DstIP string `json:"dstIP"`
SrcPort string `json:"srcPort"`
DstPort string `json:"dstPort"`
Protocol string `json:"protocol"`
Strategy string `json:"strategy" validate:"required,oneof=accept drop"`
@@ -55,6 +62,7 @@ type UpdateFirewallDescription struct {
}
type AddrRuleOperate struct {
ID uint `json:"id"`
Operation string `json:"operation" validate:"required,oneof=add remove"`
Address string `json:"address" validate:"required"`
Strategy string `json:"strategy" validate:"required,oneof=accept drop"`
@@ -76,3 +84,30 @@ type BatchRuleOperate struct {
Type string `json:"type" validate:"required"`
Rules []PortRuleOperate `json:"rules"`
}
type IptablesOp struct {
Name string `json:"name" validate:"required,oneof=1PANEL_INPUT 1PANEL_OUTPUT 1PANEL_BASIC"`
Operate string `json:"operate" validate:"required,oneof=init-base init-forward init-advance bind-base unbind-base bind unbind"`
}
type IptablesRuleOp struct {
Operation string `json:"operation" validate:"required,oneof=add remove"`
ID uint `json:"id"`
Chain string `json:"chain" validate:"required,oneof=1PANEL_BASIC 1PANEL_BASIC_BEFORE 1PANEL_INPUT 1PANEL_OUTPUT"`
Protocol string `json:"protocol"`
SrcIP string `json:"srcIP"`
SrcPort uint `json:"srcPort"`
DstIP string `json:"dstIP"`
DstPort uint `json:"dstPort"`
Strategy string `json:"strategy" validate:"required,oneof=accept drop reject"`
Description string `json:"description"`
}
type IptablesBatchOperate struct {
Rules []IptablesRuleOp `json:"rules"`
}
type IptablesChainStatus struct {
IsBind bool `json:"isBind"`
DefaultStrategy string `json:"defaultStrategy"`
}
+7 -1
View File
@@ -15,10 +15,14 @@ type ImageInfo struct {
IsUsed bool `json:"isUsed"`
Tags []string `json:"tags"`
Size int64 `json:"size"`
IsPinned bool `json:"isPinned"`
Description string `json:"description"`
}
type ImageLoad struct {
Path string `json:"path" validate:"required"`
TaskID string `json:"taskID"`
Path string `json:"path" validate:"required"`
}
type ImageBuild struct {
@@ -27,6 +31,7 @@ type ImageBuild struct {
Name string `json:"name" validate:"required"`
Dockerfile string `json:"dockerfile" validate:"required"`
Tags []string `json:"tags"`
Args []string `json:"args"`
}
type ImagePull struct {
@@ -48,6 +53,7 @@ type ImagePush struct {
}
type ImageSave struct {
TaskID string `json:"taskID"`
TagName string `json:"tagName" validate:"required"`
Path string `json:"path" validate:"required"`
Name string `json:"name" validate:"required"`
+56 -3
View File
@@ -4,25 +4,78 @@ import "time"
type MonitorSearch struct {
Param string `json:"param" validate:"required,oneof=all cpu memory load io network"`
Info string `json:"info"`
IO string `json:"io"`
Network string `json:"network"`
StartTime time.Time `json:"startTime"`
EndTime time.Time `json:"endTime"`
}
type MonitorData struct {
Param string `json:"param" validate:"required,oneof=cpu memory load io network"`
Param string `json:"param"`
Date []time.Time `json:"date"`
Value []interface{} `json:"value"`
}
type Process struct {
Name string `json:"name"`
Pid int32 `json:"pid"`
Percent float64 `json:"percent"`
Memory uint64 `json:"memory"`
Cmd string `json:"cmd"`
User string `json:"user"`
}
type MonitorSetting struct {
MonitorStatus string `json:"monitorStatus"`
MonitorStoreDays string `json:"monitorStoreDays"`
MonitorInterval string `json:"monitorInterval"`
DefaultNetwork string `json:"defaultNetwork"`
DefaultIO string `json:"defaultIO"`
}
type MonitorSettingUpdate struct {
Key string `json:"key" validate:"required,oneof=MonitorStatus MonitorStoreDays MonitorInterval DefaultNetwork"`
Key string `json:"key" validate:"required,oneof=MonitorStatus MonitorStoreDays MonitorInterval DefaultNetwork DefaultIO"`
Value string `json:"value"`
}
type MonitorGPUOptions struct {
GPUType string `json:"gpuType"`
ChartHide []GPUChartHide `json:"chartHide"`
Options []string `json:"options"`
}
type GPUChartHide struct {
ProductName string `json:"productName"`
Process bool `json:"process"`
GPU bool `json:"gpu"`
Memory bool `json:"memory"`
Power bool `json:"power"`
Temperature bool `json:"temperature"`
Speed bool `json:"speed"`
}
type MonitorGPUSearch struct {
ProductName string `json:"productName"`
StartTime time.Time `json:"startTime"`
EndTime time.Time `json:"endTime"`
}
type MonitorGPUData struct {
Date []time.Time `json:"date"`
GPUValue []float64 `json:"gpuValue"`
TemperatureValue []float64 `json:"temperatureValue"`
PowerTotal []float64 `json:"powerTotal"`
PowerUsed []float64 `json:"powerUsed"`
PowerPercent []float64 `json:"powerPercent"`
MemoryTotal []float64 `json:"memoryTotal"`
MemoryUsed []float64 `json:"memoryUsed"`
MemoryPercent []float64 `json:"memoryPercent"`
SpeedValue []int `json:"speedValue"`
ProcessCount []int `json:"processCount"`
GPUProcesses [][]GPUProcess `json:"gpuProcesses"`
}
type GPUProcess struct {
Pid string `json:"pid"`
Type string `json:"type"`
ProcessName string `json:"processName"`
UsedMemory string `json:"usedMemory"`
}
+7 -6
View File
@@ -73,12 +73,13 @@ type NginxUpstream struct {
}
type NginxUpstreamServer struct {
Server string `json:"server"`
Weight int `json:"weight"`
FailTimeout string `json:"failTimeout"`
MaxFails int `json:"maxFails"`
MaxConns int `json:"maxConns"`
Flag string `json:"flag"`
Server string `json:"server"`
Weight int `json:"weight"`
FailTimeout int `json:"failTimeout"`
FailTimeoutUnit string `json:"failTimeoutUnit"`
MaxFails int `json:"maxFails"`
MaxConns int `json:"maxConns"`
Flag string `json:"flag"`
}
var LBAlgorithms = map[string]struct{}{"ip_hash": {}, "least_conn": {}}
+9
View File
@@ -22,7 +22,16 @@ type AppInstallCreate struct {
Name string `json:"name" validate:"required"`
Services map[string]string `json:"services"`
TaskID string `json:"taskID"`
AppContainerConfig
NodePushConfig
}
type NodePushConfig struct {
Nodes []string `json:"nodes"`
PushNode bool `json:"pushNode"`
AppKey string `json:"appKey"`
Version string `json:"version"`
}
type AppContainerConfig struct {
+1
View File
@@ -13,6 +13,7 @@ type DiskMountRequest struct {
MountPoint string `json:"mountPoint" validate:"required"`
Filesystem string `json:"filesystem" validate:"required,oneof=ext4 xfs"`
AutoMount bool `json:"autoMount"`
NoFail bool `json:"noFail"`
}
type DiskUnmountRequest struct {
-1
View File
@@ -13,7 +13,6 @@ type FileContentReq struct {
Path string `json:"path" validate:"required"`
IsDetail bool `json:"isDetail"`
}
type SearchUploadWithPage struct {
dto.PageInfo
Path string `json:"path" validate:"required"`
+5
View File
@@ -130,3 +130,8 @@ type NginxModuleUpdate struct {
type NginxOperateReq struct {
Operate string `json:"operate" validate:"required,oneof=enable disable"`
}
type NginxDefaultHTTPSUpdate struct {
Operate string `json:"operate" validate:"required,oneof=enable disable"`
SSLRejectHandshake bool `json:"sslRejectHandshake"`
}
+7
View File
@@ -32,6 +32,7 @@ type NodeConfig struct {
ExposedPorts []ExposedPort `json:"exposedPorts"`
Environments []Environment `json:"environments"`
Volumes []Volume `json:"volumes"`
ExtraHosts []ExtraHost `json:"extraHosts"`
}
type Environment struct {
@@ -49,6 +50,11 @@ type ExposedPort struct {
HostIP string `json:"hostIP"`
}
type ExtraHost struct {
Hostname string `json:"hostname"`
IP string `json:"ip"`
}
type RuntimeDelete struct {
ID uint `json:"id"`
ForceDelete bool `json:"forceDelete"`
@@ -135,6 +141,7 @@ type PHPContainerConfig struct {
ExposedPorts []ExposedPort `json:"exposedPorts"`
Environments []Environment `json:"environments"`
Volumes []Volume `json:"volumes"`
ExtraHosts []ExtraHost `json:"extraHosts"`
}
type RuntimeRemark struct {
+2
View File
@@ -14,6 +14,8 @@ type TensorRTLLMCreate struct {
ModelDir string `json:"modelDir" validate:"required"`
Image string `json:"image" validate:"required"`
Command string `json:"command" validate:"required"`
ModelType string `json:"modelType"`
ModelSpeedup bool `json:"modelSpeedup"`
DockerConfig
}
+41
View File
@@ -38,6 +38,22 @@ type WebsiteCreate struct {
FtpConfig
DataBaseConfig
SSLConfig
StreamConfig
}
type StreamConfig struct {
StreamPorts string `json:"streamPorts"`
Name string `json:"name"`
Algorithm string `json:"algorithm"`
UDP bool `json:"udp"`
Servers []dto.NginxUpstreamServer `json:"servers"`
}
type StreamUpdate struct {
WebsiteID uint `json:"websiteID" validate:"required"`
StreamConfig
}
type WebsiteOptionReq struct {
@@ -109,6 +125,30 @@ type BatchWebsiteOp struct {
TaskID string `json:"taskID" validate:"required"`
}
type BatchWebsiteGroup struct {
IDs []uint `json:"ids" validate:"required"`
GroupID uint `json:"groupID" validate:"required"`
}
type BatchWebsiteHttps struct {
IDs []uint `json:"ids" validate:"required"`
TaskID string `json:"taskID" validate:"required"`
WebsiteSSLID uint `json:"websiteSSLId"`
Type string `json:"type" validate:"oneof=existed auto manual"`
PrivateKey string `json:"privateKey"`
Certificate string `json:"certificate"`
PrivateKeyPath string `json:"privateKeyPath"`
CertificatePath string `json:"certificatePath"`
ImportType string `json:"importType"`
HttpConfig string `json:"httpConfig" validate:"oneof=HTTPSOnly HTTPAlso HTTPToHTTPS"`
SSLProtocol []string `json:"SSLProtocol"`
Algorithm string `json:"algorithm"`
Hsts bool `json:"hsts"`
HstsIncludeSubDomains bool `json:"hstsIncludeSubDomains"`
HttpsPorts []int `json:"httpsPorts"`
Http3 bool `json:"http3"`
}
type WebsiteRedirectUpdate struct {
WebsiteID uint `json:"websiteId" validate:"required"`
Key string `json:"key" validate:"required"`
@@ -271,6 +311,7 @@ type WebsiteHtmlReq struct {
type WebsiteHtmlUpdate struct {
Type string `json:"type" validate:"required"`
Content string `json:"content" validate:"required"`
Sync bool `json:"sync"`
}
type WebsiteLBCreate struct {
+1
View File
@@ -31,6 +31,7 @@ type WebsiteSSLCreate struct {
Shell string `json:"shell"`
PushNode bool `json:"pushNode"`
Nodes string `json:"nodes"`
IsIp bool `json:"isIp"`
}
type WebsiteDNSReq struct {
+23 -17
View File
@@ -29,22 +29,18 @@ type AppDTO struct {
}
type AppItem struct {
Name string `json:"name"`
Key string `json:"key"`
ID uint `json:"id"`
Description string `json:"description"`
Icon string `json:"icon"`
Type string `json:"type"`
Status string `json:"status"`
Resource string `json:"resource"`
Installed bool `json:"installed"`
Versions []string `json:"versions"`
Limit int `json:"limit"`
Tags []TagDTO `json:"tags"`
Github string `json:"github"`
Website string `json:"website"`
GpuSupport bool `json:"gpuSupport"`
Recommend int `json:"recommend"`
Name string `json:"name"`
Key string `json:"key"`
ID uint `json:"id"`
Description string `json:"description"`
Status string `json:"status"`
Installed bool `json:"installed"`
Limit int `json:"limit"`
Tags []string `json:"tags"`
GpuSupport bool `json:"gpuSupport"`
Recommend int `json:"recommend"`
Type string `json:"type"`
BatchInstallSupport bool `json:"batchInstallSupport"`
}
type TagDTO struct {
@@ -80,6 +76,10 @@ type AppDetailDTO struct {
GpuSupport bool `json:"gpuSupport"`
}
type AppDetailSimpleDTO struct {
ID uint `json:"id"`
}
type IgnoredApp struct {
Icon string `json:"icon"`
Name string `json:"name"`
@@ -128,6 +128,9 @@ type AppInstallDTO struct {
Favorite bool `json:"favorite"`
App AppDetail `json:"app"`
Container string `json:"container"`
IsEdit bool `json:"isEdit"`
LinkDB bool `json:"linkDB"`
ServiceName string `json:"serviceName"`
}
type AppInstallInfo struct {
@@ -139,6 +142,8 @@ type AppInstallInfo struct {
HttpPort int `json:"HttpPort"`
Container string `json:"container"`
ComposePath string `json:"composePath"`
AppKey string `json:"appKey"`
AppPorts []int `json:"appPorts"`
Env map[string]interface{} `json:"env"`
}
@@ -176,6 +181,7 @@ type AppParam struct {
}
type AppConfig struct {
Params []AppParam `json:"params"`
Params []AppParam `json:"params"`
RawCompose string `json:"rawCompose"`
request.AppContainerConfig
}
+1 -1
View File
@@ -24,7 +24,7 @@ type DiskBasicInfo struct {
type CompleteDiskInfo struct {
Disks []DiskInfo `json:"disks"`
UnpartitionedDisks []DiskBasicInfo `json:"unpartitionedDisks"`
SystemDisk *DiskInfo `json:"systemDisk"`
SystemDisks []DiskInfo `json:"systemDisks"`
TotalDisks int `json:"totalDisks"`
TotalCapacity int64 `json:"totalCapacity"`
}
+2 -1
View File
@@ -82,5 +82,6 @@ type NginxBuildConfig struct {
}
type NginxConfigRes struct {
Https bool `json:"https"`
Https bool `json:"https"`
SSLRejectHandshake bool `json:"sslRejectHandshake"`
}
+1
View File
@@ -28,6 +28,7 @@ type RuntimeDTO struct {
ExposedPorts []request.ExposedPort `json:"exposedPorts"`
Environments []request.Environment `json:"environments"`
Volumes []request.Volume `json:"volumes"`
ExtraHosts []request.ExtraHost `json:"extraHosts"`
ContainerStatus string `json:"containerStatus"`
Container string `json:"container"`
Remark string `json:"remark"`
+5
View File
@@ -3,6 +3,7 @@ package response
import (
"time"
"github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/model"
)
@@ -16,6 +17,10 @@ type WebsiteDTO struct {
RuntimeType string `json:"runtimeType"`
SiteDir string `json:"siteDir"`
OpenBaseDir bool `json:"openBaseDir"`
Algorithm string `json:"algorithm"`
UDP bool `json:"udp"`
Servers []dto.NginxUpstreamServer `json:"servers"`
}
type WebsiteRes struct {
+14
View File
@@ -10,6 +10,7 @@ type SettingInfo struct {
NtpSite string `json:"ntpSite"`
DefaultNetwork string `json:"defaultNetwork"`
DefaultIO string `json:"defaultIO"`
LastCleanTime string `json:"lastCleanTime"`
LastCleanSize string `json:"lastCleanSize"`
LastCleanData string `json:"lastCleanData"`
@@ -36,6 +37,7 @@ type SyncTime struct {
type CleanData struct {
SystemClean []CleanTree `json:"systemClean"`
BackupClean []CleanTree `json:"backupClean"`
UploadClean []CleanTree `json:"uploadClean"`
DownloadClean []CleanTree `json:"downloadClean"`
SystemLogClean []CleanTree `json:"systemLogClean"`
@@ -61,6 +63,10 @@ type Clean struct {
Size uint64 `json:"size"`
}
type SSHDefaultConn struct {
WithReset bool `json:"withReset"`
DefaultConn string `json:"defaultConn"`
}
type SSHConnData struct {
Addr string `json:"addr" validate:"required"`
Port uint `json:"port" validate:"required,number,max=65535,min=1"`
@@ -80,3 +86,11 @@ type SystemProxy struct {
User string `json:"user"`
Password string `json:"password"`
}
type CommonDescription struct {
ID string `json:"id" validate:"required"`
Type string `json:"type" validate:"required"`
DetailType string `json:"detailType"`
IsPinned bool `json:"isPinned"`
Description string `json:"description"`
}
+1
View File
@@ -52,6 +52,7 @@ type DataTree struct {
Label string `json:"label"`
Key string `json:"key"`
Name string `json:"name"`
IsLocal bool `json:"isLocal"`
Size uint64 `json:"size"`
IsCheck bool `json:"isCheck"`
IsDisable bool `json:"isDisable"`
+1
View File
@@ -34,6 +34,7 @@ type App struct {
MemoryRequired int `json:"memoryRequired"`
GpuSupport bool `json:"gpuSupport"`
RequiredPanelVersion float64 `json:"requiredPanelVersion"`
BatchInstallSupport bool `json:"batchInstallSupport" yaml:"batchInstallSupport"`
Details []AppDetail `json:"-" gorm:"-:migration"`
TagsKey []string `json:"tags" yaml:"tags" gorm:"-"`
+2
View File
@@ -43,6 +43,8 @@ type Cronjob struct {
EntryIDs string `json:"entryIDs"`
Records []JobRecords `json:"records"`
Secret string `json:"secret"`
Config string `json:"config"`
}
type JobRecords struct {
+1
View File
@@ -9,6 +9,7 @@ type Database struct {
From string `json:"from" gorm:"not null"`
Address string `json:"address" gorm:"not null"`
Port uint `json:"port" gorm:"not null"`
InitialDB string `json:"initialDB"`
Username string `json:"username"`
Password string `json:"password"`
+1
View File
@@ -6,6 +6,7 @@ type DatabaseMysql struct {
From string `json:"from" gorm:"not null;default:local"`
MysqlName string `json:"mysqlName" gorm:"not null"`
Format string `json:"format" gorm:"not null"`
Collation string `json:"collation"`
Username string `json:"username" gorm:"not null"`
Password string `json:"password" gorm:"not null"`
Permission string `json:"permission" gorm:"not null"`
+11 -15
View File
@@ -3,20 +3,16 @@ package model
type Firewall struct {
BaseModel
Type string `gorm:"not null" json:"type"`
Port string `gorm:"not null" json:"port"`
Protocol string `gorm:"not null" json:"protocol"`
Address string `gorm:"not null" json:"address"`
Type string `json:"type"`
Port string `json:"port"` // Deprecated
Address string `json:"address"` // Deprecated
Chain string `json:"chain"`
Protocol string `json:"protocol"`
SrcIP string `json:"srcIP"`
SrcPort string `json:"srcPort"`
DstIP string `json:"dstIP"`
DstPort string `json:"dstPort"`
Strategy string `gorm:"not null" json:"strategy"`
Description string `gorm:"not null" json:"description"`
}
type Forward struct {
BaseModel
Protocol string `gorm:"not null" json:"protocol"`
Port string `gorm:"not null" json:"port"`
TargetIP string `gorm:"not null" json:"targetIP"`
TargetPort string `gorm:"not null" json:"targetPort"`
Interface string `json:"interface"`
Description string `json:"description"`
}
+20 -3
View File
@@ -2,14 +2,18 @@ package model
type MonitorBase struct {
BaseModel
Cpu float64 `json:"cpu"`
Cpu float64 `json:"cpu"`
TopCPU string `json:"topCPU"`
TopCPUItems interface{} `gorm:"-" json:"topCPUItems"`
Memory float64 `json:"memory"`
TopMem string `json:"topMem"`
TopMemItems interface{} `gorm:"-" json:"topMemItems"`
LoadUsage float64 `json:"loadUsage"`
CpuLoad1 float64 `json:"cpuLoad1"`
CpuLoad5 float64 `json:"cpuLoad5"`
CpuLoad15 float64 `json:"cpuLoad15"`
Memory float64 `json:"memory"`
}
type MonitorIO struct {
@@ -27,3 +31,16 @@ type MonitorNetwork struct {
Up float64 `json:"up"`
Down float64 `json:"down"`
}
type MonitorGPU struct {
BaseModel
ProductName string `json:"productName"`
GPUUtil float64 `json:"gpuUtil"`
Temperature float64 `json:"temperature"`
PowerDraw float64 `json:"powerDraw"`
MaxPowerLimit float64 `json:"maxPowerLimit"`
MemUsed float64 `json:"memUsed"`
MemTotal float64 `json:"memTotal"`
FanSpeed int `json:"fanSpeed"`
Processes string `json:"processes"`
}
+8
View File
@@ -7,6 +7,14 @@ type Setting struct {
About string `json:"about"`
}
type CommonDescription struct {
ID string `json:"id"`
Type string `json:"type"`
DetailType string `json:"detailType"`
IsPinned bool `json:"isPinned"`
Description string `json:"description"`
}
type NodeInfo struct {
Scope string `json:"scope"`
BaseDir string `json:"baseDir"`
+5 -4
View File
@@ -6,8 +6,9 @@ type TensorRTLLM struct {
DockerCompose string `json:"dockerCompose"`
ContainerName string `json:"containerName"`
Message string `json:"message"`
//Port int `json:"port"`
Status string `json:"status"`
Env string `json:"env"`
TaskID string `json:"taskID"`
Status string `json:"status"`
Env string `json:"env"`
TaskID string `json:"taskID"`
ModelType string `json:"modelType"`
ModelSpeedup bool `json:"modelSpeedup"`
}
+2
View File
@@ -37,6 +37,8 @@ type Website struct {
Favorite bool `json:"favorite"`
StreamPorts string `json:"streamPorts"`
Domains []WebsiteDomain `json:"domains" gorm:"-:migration"`
WebsiteSSL WebsiteSSL `json:"webSiteSSL" gorm:"-:migration"`
}
+1
View File
@@ -41,6 +41,7 @@ type WebsiteSSL struct {
PushNode bool `json:"pushNode"`
PrivateKeyPath string `json:"privateKeyPath"`
CertPath string `json:"certPath"`
IsIp bool `json:"isIP"`
AcmeAccount WebsiteAcmeAccount `json:"acmeAccount" gorm:"-:migration"`
DnsAccount WebsiteDnsAccount `json:"dnsAccount" gorm:"-:migration"`
+2 -11
View File
@@ -27,14 +27,13 @@ type IAppRepo interface {
GetFirst(opts ...DBOption) (model.App, error)
GetBy(opts ...DBOption) ([]model.App, error)
BatchCreate(ctx context.Context, apps []model.App) error
GetByKey(ctx context.Context, key string) (model.App, error)
Create(ctx context.Context, app *model.App) error
Save(ctx context.Context, app *model.App) error
BatchDelete(ctx context.Context, apps []model.App) error
DeleteByIDs(ctx context.Context, ids []uint) error
DeleteBy(opts ...DBOption) error
GetTopRecomment() ([]string, error)
GetTopRecommend() ([]string, error)
}
func NewIAppRepo() IAppRepo {
@@ -125,7 +124,7 @@ func (a AppRepo) GetBy(opts ...DBOption) ([]model.App, error) {
return apps, nil
}
func (a AppRepo) GetTopRecomment() ([]string, error) {
func (a AppRepo) GetTopRecommend() ([]string, error) {
var (
apps []model.App
names []string
@@ -144,14 +143,6 @@ func (a AppRepo) BatchCreate(ctx context.Context, apps []model.App) error {
return getTx(ctx).Omit(clause.Associations).Create(&apps).Error
}
func (a AppRepo) GetByKey(ctx context.Context, key string) (model.App, error) {
var app model.App
if err := getTx(ctx).Where("key = ?", key).First(&app).Error; err != nil {
return app, err
}
return app, nil
}
func (a AppRepo) Create(ctx context.Context, app *model.App) error {
return getTx(ctx).Omit(clause.Associations).Create(app).Error
}
+2 -1
View File
@@ -20,6 +20,7 @@ type IBackupRepo interface {
WithByPublic(isPublic bool) DBOption
ListRecord(opts ...DBOption) ([]model.BackupRecord, error)
GetRecord(opts ...DBOption) (*model.BackupRecord, error)
PageRecord(page, size int, opts ...DBOption) (int64, []model.BackupRecord, error)
CreateRecord(record *model.BackupRecord) error
DeleteRecord(ctx context.Context, opts ...DBOption) error
@@ -160,7 +161,7 @@ func (u *BackupRepo) WithByCronID(cronjobID uint) DBOption {
}
func (u *BackupRepo) GetRecord(opts ...DBOption) (*model.BackupRecord, error) {
var record *model.BackupRecord
record := &model.BackupRecord{}
db := global.DB.Model(&model.BackupRecord{})
for _, opt := range opts {
db = opt(db)
+5
View File
@@ -77,6 +77,11 @@ func WithByType(tp string) DBOption {
return g.Where("`type` = ?", tp)
}
}
func WithByDetailType(tp string) DBOption {
return func(g *gorm.DB) *gorm.DB {
return g.Where("`detail_type` = ?", tp)
}
}
func WithTypes(types []string) DBOption {
return func(db *gorm.DB) *gorm.DB {
+1 -1
View File
@@ -173,7 +173,7 @@ func (u *CronjobRepo) AddFailedRecord(cronjobID uint, message string) {
var record model.JobRecords
record.StartTime = time.Now()
record.CronjobID = cronjobID
record.Status = constant.StatusFailed
record.Status = constant.StatusUnexecuted
record.Message = message
if err := global.DB.Create(&record).Error; err != nil {
global.LOG.Errorf("create record status failed, err: %v", err)
+40 -21
View File
@@ -4,16 +4,16 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/global"
"github.com/1Panel-dev/1Panel/agent/utils/encrypt"
"gorm.io/gorm"
)
type HostRepo struct{}
type IHostRepo interface {
GetFirewallRecord(opts ...DBOption) (model.Firewall, error)
ListFirewallRecord() ([]model.Firewall, error)
ListFirewallRecord(opts ...DBOption) ([]model.Firewall, error)
SaveFirewallRecord(firewall *model.Firewall) error
DeleteFirewallRecordByID(id uint) error
DeleteFirewallRecord(fType, port, protocol, address, strategy string) error
SyncCert(data []model.RootCert) error
GetCert(opts ...DBOption) (model.RootCert, error)
@@ -22,6 +22,8 @@ type IHostRepo interface {
SaveCert(cert *model.RootCert) error
UpdateCert(id uint, vars map[string]interface{}) error
DeleteCert(opts ...DBOption) error
WithByChain(chain string) DBOption
}
func NewIHostRepo() IHostRepo {
@@ -38,12 +40,16 @@ func (h *HostRepo) GetFirewallRecord(opts ...DBOption) (model.Firewall, error) {
return firewall, err
}
func (h *HostRepo) ListFirewallRecord() ([]model.Firewall, error) {
var datas []model.Firewall
if err := global.DB.Find(&datas).Error; err != nil {
return datas, nil
func (h *HostRepo) ListFirewallRecord(opts ...DBOption) ([]model.Firewall, error) {
var firewalls []model.Firewall
db := global.DB
for _, opt := range opts {
db = opt(db)
}
return datas, nil
if err := global.DB.Find(&firewalls).Error; err != nil {
return firewalls, nil
}
return firewalls, nil
}
func (h *HostRepo) SaveFirewallRecord(firewall *model.Firewall) error {
@@ -51,16 +57,27 @@ func (h *HostRepo) SaveFirewallRecord(firewall *model.Firewall) error {
return global.DB.Save(firewall).Error
}
var data model.Firewall
if firewall.Type == "port" {
_ = global.DB.Where("type = ? AND port = ? AND protocol = ? AND address = ? AND strategy = ?", "port", firewall.Port, firewall.Protocol, firewall.Address, firewall.Strategy).First(&data)
if data.ID != 0 {
firewall.ID = data.ID
}
} else {
_ = global.DB.Where("type = ? AND address = ? AND strategy = ?", "address", firewall.Address, firewall.Strategy).First(&data)
if data.ID != 0 {
firewall.ID = data.ID
}
switch firewall.Type {
case "port":
_ = global.DB.Where("type = ? AND dst_port = ? AND protocol = ? AND src_ip = ? AND strategy = ?", "port",
firewall.DstPort,
firewall.Protocol,
firewall.SrcIP,
firewall.Strategy,
).First(&data).Error
case "ip":
_ = global.DB.Where("type = ? AND src_ip = ? AND strategy = ?", "address", firewall.SrcIP, firewall.Strategy).First(&data)
default:
_ = global.DB.Where("type = ? AND chain = ? AND src_port = ? AND dst_port = ? AND protocol = ? AND src_ip = ? AND dst_ip = ? AND strategy = ?",
firewall.Type,
firewall.Chain,
firewall.SrcPort,
firewall.DstPort,
firewall.Protocol,
firewall.SrcIP,
firewall.DstIP,
firewall.Strategy,
).First(&data).Error
}
return global.DB.Save(firewall).Error
}
@@ -69,10 +86,6 @@ func (h *HostRepo) DeleteFirewallRecordByID(id uint) error {
return global.DB.Where("id = ?", id).Delete(&model.Firewall{}).Error
}
func (h *HostRepo) DeleteFirewallRecord(fType, port, protocol, address, strategy string) error {
return global.DB.Where("type = ? AND port = ? AND protocol = ? AND address = ? AND strategy = ?", fType, port, protocol, address, strategy).Delete(&model.Firewall{}).Error
}
func (u *HostRepo) GetCert(opts ...DBOption) (model.RootCert, error) {
var cert model.RootCert
db := global.DB
@@ -151,3 +164,9 @@ func (u *HostRepo) SyncCert(data []model.RootCert) error {
tx.Commit()
return nil
}
func (u *HostRepo) WithByChain(chain string) DBOption {
return func(g *gorm.DB) *gorm.DB {
return g.Where("chain = ?", chain)
}
}
+27
View File
@@ -5,21 +5,27 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/global"
"gorm.io/gorm"
)
type MonitorRepo struct{}
type IMonitorRepo interface {
GetBase(opts ...DBOption) ([]model.MonitorBase, error)
GetGPU(opts ...DBOption) ([]model.MonitorGPU, error)
GetIO(opts ...DBOption) ([]model.MonitorIO, error)
GetNetwork(opts ...DBOption) ([]model.MonitorNetwork, error)
CreateMonitorBase(model model.MonitorBase) error
BatchCreateMonitorGPU(list []model.MonitorGPU) error
BatchCreateMonitorIO(ioList []model.MonitorIO) error
BatchCreateMonitorNet(ioList []model.MonitorNetwork) error
DelMonitorBase(timeForDelete time.Time) error
DelMonitorGPU(timeForDelete time.Time) error
DelMonitorIO(timeForDelete time.Time) error
DelMonitorNet(timeForDelete time.Time) error
WithByProductName(name string) DBOption
}
func NewIMonitorRepo() IMonitorRepo {
@@ -53,10 +59,22 @@ func (u *MonitorRepo) GetNetwork(opts ...DBOption) ([]model.MonitorNetwork, erro
err := db.Find(&data).Error
return data, err
}
func (u *MonitorRepo) GetGPU(opts ...DBOption) ([]model.MonitorGPU, error) {
var data []model.MonitorGPU
db := global.GPUMonitorDB
for _, opt := range opts {
db = opt(db)
}
err := db.Find(&data).Error
return data, err
}
func (u *MonitorRepo) CreateMonitorBase(model model.MonitorBase) error {
return global.MonitorDB.Create(&model).Error
}
func (s *MonitorRepo) BatchCreateMonitorGPU(list []model.MonitorGPU) error {
return global.GPUMonitorDB.CreateInBatches(&list, len(list)).Error
}
func (u *MonitorRepo) BatchCreateMonitorIO(ioList []model.MonitorIO) error {
return global.MonitorDB.CreateInBatches(ioList, len(ioList)).Error
}
@@ -72,3 +90,12 @@ func (u *MonitorRepo) DelMonitorIO(timeForDelete time.Time) error {
func (u *MonitorRepo) DelMonitorNet(timeForDelete time.Time) error {
return global.MonitorDB.Where("created_at < ?", timeForDelete).Delete(&model.MonitorNetwork{}).Error
}
func (s *MonitorRepo) DelMonitorGPU(timeForDelete time.Time) error {
return global.GPUMonitorDB.Where("created_at < ?", timeForDelete).Delete(&model.MonitorGPU{}).Error
}
func (s *MonitorRepo) WithByProductName(name string) DBOption {
return func(g *gorm.DB) *gorm.DB {
return g.Where("product_name = ?", name)
}
}
+40 -26
View File
@@ -2,7 +2,6 @@ package repo
import (
"errors"
"time"
"github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/global"
@@ -19,13 +18,14 @@ type ISettingRepo interface {
Update(key, value string) error
WithByKey(key string) DBOption
CreateMonitorBase(model model.MonitorBase) error
BatchCreateMonitorIO(ioList []model.MonitorIO) error
BatchCreateMonitorNet(ioList []model.MonitorNetwork) error
DelMonitorBase(timeForDelete time.Time) error
DelMonitorIO(timeForDelete time.Time) error
DelMonitorNet(timeForDelete time.Time) error
UpdateOrCreate(key, value string) error
GetDescription(opts ...DBOption) (model.CommonDescription, error)
GetDescriptionList(opts ...DBOption) ([]model.CommonDescription, error)
CreateDescription(data *model.CommonDescription) error
UpdateDescription(id string, val map[string]interface{}) error
DelDescription(id string) error
WithByDescriptionID(id string) DBOption
}
func NewISettingRepo() ISettingRepo {
@@ -78,25 +78,6 @@ func (s *SettingRepo) Update(key, value string) error {
return global.DB.Model(&model.Setting{}).Where("key = ?", key).Updates(map[string]interface{}{"value": value}).Error
}
func (s *SettingRepo) CreateMonitorBase(model model.MonitorBase) error {
return global.MonitorDB.Create(&model).Error
}
func (s *SettingRepo) BatchCreateMonitorIO(ioList []model.MonitorIO) error {
return global.MonitorDB.CreateInBatches(ioList, len(ioList)).Error
}
func (s *SettingRepo) BatchCreateMonitorNet(ioList []model.MonitorNetwork) error {
return global.MonitorDB.CreateInBatches(ioList, len(ioList)).Error
}
func (s *SettingRepo) DelMonitorBase(timeForDelete time.Time) error {
return global.MonitorDB.Where("created_at < ?", timeForDelete).Delete(&model.MonitorBase{}).Error
}
func (s *SettingRepo) DelMonitorIO(timeForDelete time.Time) error {
return global.MonitorDB.Where("created_at < ?", timeForDelete).Delete(&model.MonitorIO{}).Error
}
func (s *SettingRepo) DelMonitorNet(timeForDelete time.Time) error {
return global.MonitorDB.Where("created_at < ?", timeForDelete).Delete(&model.MonitorNetwork{}).Error
}
func (s *SettingRepo) UpdateOrCreate(key, value string) error {
var setting model.Setting
result := global.DB.Where("key = ?", key).First(&setting)
@@ -108,3 +89,36 @@ func (s *SettingRepo) UpdateOrCreate(key, value string) error {
}
return global.DB.Model(&setting).UpdateColumn("value", value).Error
}
func (s *SettingRepo) GetDescriptionList(opts ...DBOption) ([]model.CommonDescription, error) {
var lists []model.CommonDescription
db := global.DB.Model(&model.CommonDescription{})
for _, opt := range opts {
db = opt(db)
}
err := db.Find(&lists).Error
return lists, err
}
func (s *SettingRepo) GetDescription(opts ...DBOption) (model.CommonDescription, error) {
var data model.CommonDescription
db := global.DB.Model(&model.CommonDescription{})
for _, opt := range opts {
db = opt(db)
}
err := db.First(&data).Error
return data, err
}
func (s *SettingRepo) CreateDescription(data *model.CommonDescription) error {
return global.DB.Create(data).Error
}
func (s *SettingRepo) UpdateDescription(id string, val map[string]interface{}) error {
return global.DB.Model(&model.CommonDescription{}).Where("id = ?", id).Updates(val).Error
}
func (s *SettingRepo) DelDescription(id string) error {
return global.DB.Where("id = ?", id).Delete(&model.CommonDescription{}).Error
}
func (s *SettingRepo) WithByDescriptionID(id string) DBOption {
return func(g *gorm.DB) *gorm.DB {
return g.Where("id = ?", id)
}
}
+4 -6
View File
@@ -134,9 +134,8 @@ func (u *AIToolService) Close(name string) error {
if err != nil {
return err
}
stdout, err := cmd.RunDefaultWithStdoutBashCf("docker exec %s ollama stop %s", containerName, name)
if err != nil {
return fmt.Errorf("handle ollama stop %s failed, stdout: %s, err: %v", name, stdout, err)
if err := cmd.RunDefaultBashCf("docker exec %s ollama stop %s", containerName, name); err != nil {
return fmt.Errorf("handle ollama stop %s failed, %v", name, err)
}
return nil
}
@@ -193,9 +192,8 @@ func (u *AIToolService) Delete(req dto.ForceDelete) error {
}
for _, item := range ollamaList {
if item.Status != constant.StatusDeleted {
stdout, err := cmd.RunDefaultWithStdoutBashCf("docker exec %s ollama rm %s", containerName, item.Name)
if err != nil && !req.ForceDelete {
return fmt.Errorf("handle ollama rm %s failed, stdout: %s, err: %v", item.Name, stdout, err)
if err := cmd.RunDefaultBashCf("docker exec %s ollama rm %s", containerName, item.Name); err != nil && !req.ForceDelete {
return fmt.Errorf("handle ollama rm %s failed, %v", item.Name, err)
}
}
_ = aiRepo.Delete(repo.WithByID(item.ID))
+2 -1
View File
@@ -486,9 +486,10 @@ func (a AlertService) TestAlertConfig(req dto.AlertConfigTest) (bool, error) {
cfg := email.SMTPConfig{
Host: req.Host,
Port: req.Port,
Sender: req.Sender,
Username: username,
Password: req.Password,
From: fmt.Sprintf("%s <%s>", req.DisplayName, req.Sender),
From: fmt.Sprintf(`"%s" <%s>`, req.DisplayName, req.Sender),
Encryption: req.Encryption,
Recipient: req.Recipient,
}
+3 -2
View File
@@ -9,6 +9,7 @@ import (
"github.com/1Panel-dev/1Panel/agent/global"
alertUtil "github.com/1Panel-dev/1Panel/agent/utils/alert"
"github.com/1Panel-dev/1Panel/agent/utils/common"
"github.com/1Panel-dev/1Panel/agent/utils/psutil"
versionUtil "github.com/1Panel-dev/1Panel/agent/utils/version"
"github.com/1Panel-dev/1Panel/agent/utils/xpack"
"github.com/shirou/gopsutil/v4/cpu"
@@ -352,7 +353,7 @@ func loadLoadInfo(alert dto.AlertDTO) {
return
}
var loadValue float64
CPUTotal, _ := cpu.Counts(true)
CPUTotal, _ := psutil.CPUInfo.GetLogicalCores(false)
switch alert.Cycle {
case 1:
loadValue = avgStat.Load1 / (float64(CPUTotal*2) * 0.75) * 100
@@ -839,7 +840,7 @@ func processSingleDisk(alert dto.AlertDTO) error {
}
func checkAndCreateDiskAlert(alert dto.AlertDTO, path string) (bool, error) {
usageStat, err := disk.Usage(path)
usageStat, err := psutil.DISK.GetUsage(path, false)
if err != nil {
global.LOG.Errorf("error getting disk usage for %s, err: %v", path, err)
return false, err
+63 -40
View File
@@ -37,7 +37,7 @@ type AppService struct {
}
type IAppService interface {
PageApp(ctx *gin.Context, req request.AppSearch) (interface{}, error)
PageApp(ctx *gin.Context, req request.AppSearch) (*response.AppRes, error)
GetAppTags(ctx *gin.Context) ([]response.TagDTO, error)
GetApp(ctx *gin.Context, key string) (*response.AppDTO, error)
GetAppDetail(appId uint, version, appType string) (response.AppDetailDTO, error)
@@ -46,13 +46,15 @@ type IAppService interface {
GetAppUpdate() (*response.AppUpdateRes, error)
GetAppDetailByID(id uint) (*response.AppDetailDTO, error)
SyncAppListFromLocal(taskID string)
GetAppIcon(appID uint) ([]byte, error)
GetAppDetailByKey(appKey, version string) (response.AppDetailSimpleDTO, error)
}
func NewIAppService() IAppService {
return &AppService{}
}
func (a AppService) PageApp(ctx *gin.Context, req request.AppSearch) (interface{}, error) {
func (a AppService) PageApp(ctx *gin.Context, req request.AppSearch) (*response.AppRes, error) {
var opts []repo.DBOption
opts = append(opts, appRepo.OrderByRecommend())
if req.Name != "" {
@@ -98,7 +100,7 @@ func (a AppService) PageApp(ctx *gin.Context, req request.AppSearch) (interface{
}
opts = append(opts, repo.WithByIDs(appIds))
}
var res response.AppRes
res := &response.AppRes{}
total, apps, err := appRepo.Page(req.Page, req.PageSize, opts...)
if err != nil {
@@ -117,25 +119,24 @@ func (a AppService) PageApp(ctx *gin.Context, req request.AppSearch) (interface{
}
}
appDTO := &response.AppItem{
ID: ap.ID,
Name: ap.Name,
Key: ap.Key,
Type: ap.Type,
Icon: ap.Icon,
Resource: ap.Resource,
Limit: ap.Limit,
Website: ap.Website,
Github: ap.Github,
GpuSupport: ap.GpuSupport,
Recommend: ap.Recommend,
Description: ap.GetDescription(ctx),
ID: ap.ID,
Name: ap.Name,
Key: ap.Key,
Limit: ap.Limit,
GpuSupport: ap.GpuSupport,
Recommend: ap.Recommend,
Description: ap.GetDescription(ctx),
Type: ap.Type,
BatchInstallSupport: ap.BatchInstallSupport,
}
appDTOs = append(appDTOs, appDTO)
tags, err := getAppTags(ap.ID, lang)
if err != nil {
continue
}
appDTO.Tags = tags
for _, tag := range tags {
appDTO.Tags = append(appDTO.Tags, tag.Name)
}
if ap.Type == constant.RuntimePHP || ap.Type == constant.RuntimeGo || ap.Type == constant.RuntimeNode || ap.Type == constant.RuntimePython || ap.Type == constant.RuntimeJava || ap.Type == constant.RuntimeDotNet {
details, _ := appDetailRepo.GetBy(appDetailRepo.WithAppId(ap.ID))
var ids []uint
@@ -195,24 +196,7 @@ func (a AppService) GetApp(ctx *gin.Context, key string) (*response.AppDTO, erro
if err != nil {
return nil, err
}
var versionsRaw []string
hasLatest := false
latestVersion := ""
for _, detail := range details {
if strings.Contains(detail.Version, "latest") {
hasLatest = true
latestVersion = detail.Version
continue
}
if key == "openresty" && !common.CompareAppVersion(detail.Version, "1.27") {
continue
}
versionsRaw = append(versionsRaw, detail.Version)
}
appDTO.Versions = common.GetSortedVersions(versionsRaw)
if hasLatest {
appDTO.Versions = append([]string{latestVersion}, appDTO.Versions...)
}
appDTO.Versions = getAppVersions(key, details)
tags, err := getAppTags(app.ID, strings.ToLower(common.GetLang(ctx)))
if err != nil {
return nil, err
@@ -221,6 +205,20 @@ func (a AppService) GetApp(ctx *gin.Context, key string) (*response.AppDTO, erro
return &appDTO, nil
}
func (a AppService) GetAppDetailByKey(appKey, version string) (response.AppDetailSimpleDTO, error) {
var appDetailDTO response.AppDetailSimpleDTO
app, err := appRepo.GetFirst(appRepo.WithKey(appKey))
if err != nil {
return appDetailDTO, err
}
appDetail, err := appDetailRepo.GetFirst(appDetailRepo.WithAppId(app.ID), appDetailRepo.WithVersion(version))
if err != nil {
return appDetailDTO, err
}
appDetailDTO.ID = appDetail.ID
return appDetailDTO, nil
}
func (a AppService) GetAppDetail(appID uint, version, appType string) (response.AppDetailDTO, error) {
var (
appDetailDTO response.AppDetailDTO
@@ -404,11 +402,21 @@ func (a AppService) Install(req request.AppInstallCreate) (appInstall *model.App
App: app,
}
composeMap := make(map[string]interface{})
var composeRes []byte
if req.EditCompose {
if err = yaml.Unmarshal([]byte(req.DockerCompose), &composeMap); err != nil {
return
}
} else {
if appDetail.DockerCompose == "" {
dockerComposeUrl := fmt.Sprintf("%s/%s/1panel/%s/%s/docker-compose.yml", global.CONF.RemoteURL.AppRepo, global.CONF.Base.Mode, app.Key, appDetail.Version)
_, composeRes, err = req_helper.HandleRequest(dockerComposeUrl, http.MethodGet, constant.TimeOut20s)
if err != nil {
return
}
appDetail.DockerCompose = string(composeRes)
_ = appDetailRepo.Update(context.Background(), appDetail)
}
if err = yaml.Unmarshal([]byte(appDetail.DockerCompose), &composeMap); err != nil {
return
}
@@ -450,10 +458,11 @@ func (a AppService) Install(req request.AppInstallCreate) (appInstall *model.App
}
index++
}
if app.Limit == 0 && appInstall.Name != serviceName && len(servicesMap) == 1 {
servicesMap[appInstall.Name] = servicesMap[serviceName]
newServiceName := strings.ToLower(appInstall.Name)
if app.Limit == 0 && newServiceName != serviceName && len(servicesMap) == 1 {
servicesMap[newServiceName] = servicesMap[serviceName]
delete(servicesMap, serviceName)
serviceName = appInstall.Name
serviceName = newServiceName
}
appInstall.ServiceName = serviceName
@@ -863,13 +872,15 @@ func getAppList() (*dto.AppList, error) {
return nil, err
}
listFile := filepath.Join(global.Dir.ResourceDir, "1panel.json")
content, err := os.ReadFile(listFile)
file, err := os.Open(listFile)
if err != nil {
return nil, err
}
if err = json.Unmarshal(content, list); err != nil {
defer file.Close()
if err = json.NewDecoder(file).Decode(list); err != nil {
return nil, err
}
return list, nil
}
@@ -1152,7 +1163,7 @@ func (a AppService) SyncAppListFromRemote(taskID string) (err error) {
}, nil)
go func() {
if err = syncTask.Execute(); err != nil {
if err := syncTask.Execute(); err != nil {
_ = NewISettingService().Update("AppStoreLastModified", "0")
_ = NewISettingService().Update("AppStoreSyncStatus", constant.StatusError)
}
@@ -1160,3 +1171,15 @@ func (a AppService) SyncAppListFromRemote(taskID string) (err error) {
return nil
}
func (a AppService) GetAppIcon(appID uint) ([]byte, error) {
app, err := appRepo.GetFirst(repo.WithByID(appID))
if err != nil {
return nil, err
}
iconBytes, err := base64.StdEncoding.DecodeString(app.Icon)
if err != nil {
return nil, err
}
return iconBytes, nil
}
+22
View File
@@ -515,6 +515,7 @@ func (a *AppInstallService) GetServices(key string) ([]response.AppService, erro
} else {
service.From = constant.AppResourceRemote
service.Status = constant.StatusRunning
service.Config = map[string]string{"PANEL_DB_ROOT_PASSWORD": db.Password, "PANEL_DB_ROOT_USER": db.Username}
}
res = append(res, service)
}
@@ -796,6 +797,9 @@ func (a *AppInstallService) GetParams(id uint) (*response.AppConfig, error) {
res.RestartPolicy = getRestartPolicy(install.DockerCompose)
res.WebUI = install.WebUI
res.Type = install.App.Type
if rawCompose, err := getUpgradeCompose(install, detail); err == nil {
res.RawCompose = rawCompose
}
return &res, nil
}
@@ -940,8 +944,26 @@ func (a *AppInstallService) GetAppInstallInfo(installID uint) (*response.AppInst
HttpPort: appInstall.HttpPort,
Status: appInstall.Status,
Message: appInstall.Message,
AppKey: appInstall.App.Key,
Env: envMap,
ComposePath: appInstall.GetComposePath(),
}
for k, v := range envMap {
if strings.Contains(strings.ToUpper(k), "PANEL_APP_PORT") {
var port int
switch val := v.(type) {
case int:
port = val
case string:
port, err = strconv.Atoi(val)
if err != nil {
continue
}
default:
continue
}
res.AppPorts = append(res.AppPorts, port)
}
}
return res, nil
}
+199 -130
View File
@@ -6,7 +6,6 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"log"
"maps"
"math"
"net/http"
@@ -15,7 +14,6 @@ import (
"path"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"time"
@@ -40,11 +38,13 @@ import (
"github.com/1Panel-dev/1Panel/agent/utils/files"
"github.com/1Panel-dev/1Panel/agent/utils/nginx"
"github.com/1Panel-dev/1Panel/agent/utils/nginx/parser"
"github.com/1Panel-dev/1Panel/agent/utils/re"
"github.com/1Panel-dev/1Panel/agent/utils/req_helper"
"github.com/1Panel-dev/1Panel/agent/utils/xpack"
"github.com/compose-spec/compose-go/v2/types"
"github.com/docker/docker/api/types/container"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/subosito/gotenv"
"gopkg.in/yaml.v3"
)
@@ -134,6 +134,76 @@ var ToolKeys = map[string]uint{
"minio": 9001,
}
func CreateDB(ctx context.Context, app model.App, appInstall *model.AppInstall, params map[string]interface{}) error {
database := &model.Database{
AppInstallID: appInstall.ID,
Name: appInstall.Name,
Type: app.Key,
Version: appInstall.Version,
From: "local",
Address: appInstall.ServiceName,
Port: DatabaseKeys[app.Key],
}
detail, err := appDetailRepo.GetFirst(repo.WithByID(appInstall.AppDetailId))
if err != nil {
return err
}
formFields := &dto.AppForm{}
if err := json.Unmarshal([]byte(detail.Params), formFields); err != nil {
return err
}
for _, form := range formFields.FormFields {
if form.EnvKey == "PANEL_APP_PORT_HTTP" {
portFloat, ok := form.Default.(float64)
if ok {
database.Port = uint(int(portFloat))
}
break
}
}
switch app.Key {
case constant.AppMysql, constant.AppMariaDB, constant.AppPostgresql, constant.AppMongodb, constant.AppMysqlCluster, constant.AppPostgresqlCluster:
if password, ok := params["PANEL_DB_ROOT_PASSWORD"]; ok {
if password != "" {
database.Password = password.(string)
if app.Key == "mysql" || app.Key == "mariadb" || app.Key == constant.AppMysqlCluster {
database.Username = "root"
}
if rootUser, ok := params["PANEL_DB_ROOT_USER"]; ok {
database.Username = rootUser.(string)
}
authParam := dto.AuthParam{
RootPassword: password.(string),
RootUser: database.Username,
}
authByte, err := json.Marshal(authParam)
if err != nil {
return err
}
appInstall.Param = string(authByte)
}
}
case constant.AppRedis, constant.AppRedisCluster:
if password, ok := params["PANEL_REDIS_ROOT_PASSWORD"]; ok {
authParam := dto.RedisAuthParam{
RootPassword: "",
}
if password != "" {
authParam.RootPassword = password.(string)
database.Password = password.(string)
}
authByte, err := json.Marshal(authParam)
if err != nil {
return err
}
appInstall.Param = string(authByte)
}
}
return databaseRepo.Create(ctx, database)
}
func createLink(ctx context.Context, installTask *task.Task, app model.App, appInstall *model.AppInstall, params map[string]interface{}) error {
deleteAppLink := func(t *task.Task) {
del := dto.DelAppLink{
@@ -145,74 +215,7 @@ func createLink(ctx context.Context, installTask *task.Task, app model.App, appI
}
if DatabaseKeys[app.Key] > 0 {
handleDataBaseApp := func(task *task.Task) error {
database := &model.Database{
AppInstallID: appInstall.ID,
Name: appInstall.Name,
Type: app.Key,
Version: appInstall.Version,
From: "local",
Address: appInstall.ServiceName,
Port: DatabaseKeys[app.Key],
}
detail, err := appDetailRepo.GetFirst(repo.WithByID(appInstall.AppDetailId))
if err != nil {
return err
}
formFields := &dto.AppForm{}
if err := json.Unmarshal([]byte(detail.Params), formFields); err != nil {
return err
}
for _, form := range formFields.FormFields {
if form.EnvKey == "PANEL_APP_PORT_HTTP" {
portFloat, ok := form.Default.(float64)
if ok {
database.Port = uint(int(portFloat))
}
break
}
}
switch app.Key {
case constant.AppMysql, constant.AppMariaDB, constant.AppPostgresql, constant.AppMongodb, constant.AppMysqlCluster, constant.AppPostgresqlCluster:
if password, ok := params["PANEL_DB_ROOT_PASSWORD"]; ok {
if password != "" {
database.Password = password.(string)
if app.Key == "mysql" || app.Key == "mariadb" || app.Key == constant.AppMysqlCluster {
database.Username = "root"
}
if rootUser, ok := params["PANEL_DB_ROOT_USER"]; ok {
database.Username = rootUser.(string)
}
authParam := dto.AuthParam{
RootPassword: password.(string),
RootUser: database.Username,
}
authByte, err := json.Marshal(authParam)
if err != nil {
return err
}
appInstall.Param = string(authByte)
}
}
case constant.AppRedis, constant.AppRedisCluster:
if password, ok := params["PANEL_REDIS_ROOT_PASSWORD"]; ok {
authParam := dto.RedisAuthParam{
RootPassword: "",
}
if password != "" {
authParam.RootPassword = password.(string)
database.Password = password.(string)
}
authByte, err := json.Marshal(authParam)
if err != nil {
return err
}
appInstall.Param = string(authByte)
}
}
return databaseRepo.Create(ctx, database)
return CreateDB(ctx, app, appInstall, params)
}
installTask.AddSubTask(i18n.GetMsgByKey("HandleDatabaseApp"), handleDataBaseApp, deleteAppLink)
}
@@ -297,10 +300,11 @@ func createLink(ctx context.Context, installTask *task.Task, app model.App, appI
createMysql.Name = dbConfig.DbName
createMysql.Username = dbConfig.DbUser
createMysql.Database = database.Name
createMysql.Format = "utf8mb4"
createMysql.Format = dbConfig.Format
createMysql.Permission = "%"
createMysql.Password = dbConfig.Password
createMysql.From = database.From
createMysql.Collation = dbConfig.Collation
mysqldb, err := NewIMysqlService().Create(ctx, createMysql)
if err != nil {
return err
@@ -537,8 +541,18 @@ func handleUpgradeCompose(install model.AppInstall, detail model.AppDetail) (map
if !ok || oldValue == nil {
return nil, buserr.New("ErrFileParse")
}
oldValueMap := oldValue.(map[string]interface{})
oldServiceValue := oldValueMap[install.ServiceName].(map[string]interface{})
oldValueMap, ok := oldValue.(map[string]interface{})
if !ok {
return nil, buserr.New("ErrFileParse")
}
oldServiceValueInterface, ok := oldValueMap[install.ServiceName]
if !ok || oldServiceValueInterface == nil {
return nil, buserr.New("ErrFileParse")
}
oldServiceValue, ok := oldServiceValueInterface.(map[string]interface{})
if !ok {
return nil, buserr.New("ErrFileParse")
}
if oldServiceValue["deploy"] != nil {
serviceValue["deploy"] = oldServiceValue["deploy"]
}
@@ -945,7 +959,7 @@ func handleMap(params map[string]interface{}, envParams map[string]string) {
}
}
func downloadApp(app model.App, appDetail model.AppDetail, appInstall *model.AppInstall, logger *log.Logger) (err error) {
func downloadApp(app model.App, appDetail model.AppDetail, appInstall *model.AppInstall, logger *logrus.Logger) (err error) {
if app.IsLocalApp() || app.IsCustomApp() {
return nil
}
@@ -1082,11 +1096,7 @@ func runScript(task *task.Task, appInstall *model.AppInstall, operate string) er
task.LogStart(logStr)
cmdMgr := cmd.NewCommandMgr(cmd.WithTimeout(10*time.Minute), cmd.WithWorkDir(workDir))
out, err := cmdMgr.RunWithStdoutBashC(scriptPath)
if err != nil {
if out != "" {
err = errors.New(out)
}
if err := cmdMgr.RunBashC(scriptPath); err != nil {
task.LogFailedWithErr(logStr, err)
return err
}
@@ -1302,6 +1312,7 @@ func getApps(oldApps []model.App, items []dto.AppDefine, systemVersion string, t
app.MemoryRequired = config.MemoryRequired
app.Architectures = strings.Join(config.Architectures, ",")
app.GpuSupport = config.GpuSupport
app.BatchInstallSupport = config.BatchInstallSupport
apps[key] = app
}
return apps
@@ -1413,6 +1424,9 @@ func handleLocalApp(appDir string) (app *model.App, err error) {
desc, _ := json.Marshal(appDefine.Description)
app.Description = string(desc)
app.Key = "local" + appDefine.Key
app.Architectures = strings.Join(appDefine.Architectures, ",")
app.GpuSupport = appDefine.GpuSupport
app.MemoryRequired = appDefine.MemoryRequired
app.Resource = constant.AppResourceLocal
app.Status = constant.AppNormal
@@ -1554,7 +1568,6 @@ func handleInstalled(appInstallList []model.AppInstall, updated bool, sync bool)
Message: installed.Message,
HttpPort: installed.HttpPort,
HttpsPort: installed.HttpsPort,
Icon: installed.App.Icon,
AppName: installed.App.Name,
AppKey: installed.App.Key,
AppType: installed.App.Type,
@@ -1566,41 +1579,41 @@ func handleInstalled(appInstallList []model.AppInstall, updated bool, sync bool)
Website: installed.App.Website,
Document: installed.App.Document,
},
Favorite: installed.Favorite,
Container: installed.ContainerName,
Favorite: installed.Favorite,
Container: installed.ContainerName,
ServiceName: strings.ToLower(installed.ServiceName),
}
if updated {
installDTO.DockerCompose = installed.DockerCompose
if !updated {
installDTO.LinkDB = hasLinkDB(installed.ID)
res = append(res, installDTO)
continue
}
app, err := appRepo.GetFirst(repo.WithByID(installed.AppId))
if err != nil {
return nil, err
if installed.Version == "latest" {
continue
}
details, err := appDetailRepo.GetBy(appDetailRepo.WithAppId(app.ID))
installDTO.DockerCompose = installed.DockerCompose
installDTO.IsEdit = isEditCompose(installed)
details, err := appDetailRepo.GetBy(appDetailRepo.WithAppId(installed.App.ID))
if err != nil {
return nil, err
}
var versions []string
for _, detail := range details {
ignores, _ := appIgnoreUpgradeRepo.List(runtimeRepo.WithDetailId(detail.ID), appIgnoreUpgradeRepo.WithScope("version"))
if len(ignores) > 0 || installed.Version == "latest" {
for _, appDetail := range details {
ignores, _ := appIgnoreUpgradeRepo.List(runtimeRepo.WithDetailId(appDetail.ID), appIgnoreUpgradeRepo.WithScope("version"))
if len(ignores) > 0 {
continue
}
if common.IsCrossVersion(installed.Version, detail.Version) && !app.CrossVersionUpdate {
if common.IsCrossVersion(installed.Version, appDetail.Version) && !installed.App.CrossVersionUpdate {
continue
}
versions = append(versions, detail.Version)
versions = append(versions, appDetail.Version)
}
versions = common.GetSortedVersions(versions)
if len(versions) == 0 {
if !updated {
installDTO.CanUpdate = false
res = append(res, installDTO)
}
continue
}
versions = common.GetSortedVersions(versions)
lastVersion := versions[0]
if app.Key == constant.AppMysql || app.Key == constant.AppMysqlCluster {
if installed.App.Key == constant.AppMysql || installed.App.Key == constant.AppMysqlCluster {
for _, version := range versions {
majorVersion := getMajorVersion(installed.Version)
if !strings.HasPrefix(version, majorVersion) {
@@ -1612,15 +1625,11 @@ func handleInstalled(appInstallList []model.AppInstall, updated bool, sync bool)
}
}
if common.IsCrossVersion(installed.Version, lastVersion) {
installDTO.CanUpdate = app.CrossVersionUpdate
installDTO.CanUpdate = installed.App.CrossVersionUpdate
} else {
installDTO.CanUpdate = common.CompareVersion(lastVersion, installed.Version)
}
if updated {
if installDTO.CanUpdate {
res = append(res, installDTO)
}
} else {
if installDTO.CanUpdate {
res = append(res, installDTO)
}
}
@@ -1824,8 +1833,7 @@ func getAppCommonConfig(envs map[string]interface{}) request.AppContainerConfig
config.CpuQuota = 0
}
if memLimit, ok := envs[constant.MemoryLimit]; ok {
re := regexp.MustCompile(`(\d+)([A-Za-z]+)`)
matches := re.FindStringSubmatch(memLimit.(string))
matches := re.GetRegex(re.NumberAlphaPattern).FindStringSubmatch(memLimit.(string))
if len(matches) == 3 {
num, err := strconv.ParseFloat(matches[1], 64)
if err == nil {
@@ -1999,7 +2007,7 @@ func handleOpenrestyFile(appInstall *model.AppInstall) error {
break
}
}
if err := handleSSLConfig(appInstall, hasDefaultWebsite); err != nil {
if err := handleSSLConfig(appInstall, hasDefaultWebsite, true); err != nil {
return err
}
if len(websites) == 0 {
@@ -2028,34 +2036,37 @@ func handleDefaultServer(appInstall *model.AppInstall) error {
return nil
}
func handleSSLConfig(appInstall *model.AppInstall, hasDefaultWebsite bool) error {
func handleSSLConfig(appInstall *model.AppInstall, hasDefaultWebsite bool, sslRejectHandshake bool) error {
sslDir := path.Join(appInstall.GetPath(), "conf", "ssl")
fileOp := files.NewFileOp()
if !fileOp.Stat(sslDir) {
return errors.New("ssl dir not found")
}
ca, _ := websiteCARepo.GetFirst(repo.WithByName("1Panel"))
if ca.ID == 0 {
global.LOG.Errorf("create openresty default ssl failed ca not found")
return nil
hasDefaultSSL := fileOp.Stat(path.Join(sslDir, "fullchain.pem")) && fileOp.Stat(path.Join(sslDir, "privkey.pem")) && fileOp.Stat(path.Join(sslDir, "root_ssl.conf"))
if !hasDefaultSSL {
ca, _ := websiteCARepo.GetFirst(repo.WithByName("1Panel"))
if ca.ID == 0 {
global.LOG.Errorf("create openresty default ssl failed ca not found")
return nil
}
caService := NewIWebsiteCAService()
caRequest := request.WebsiteCAObtain{
ID: ca.ID,
Domains: "localhost",
KeyType: "4096",
Time: 99,
Unit: "year",
Dir: sslDir,
PushDir: true,
}
websiteSSL, err := caService.ObtainSSL(caRequest)
if err != nil {
return err
}
defer func() {
_ = NewIWebsiteSSLService().Delete([]uint{websiteSSL.ID})
}()
}
caService := NewIWebsiteCAService()
caRequest := request.WebsiteCAObtain{
ID: ca.ID,
Domains: "localhost",
KeyType: "4096",
Time: 99,
Unit: "year",
Dir: sslDir,
PushDir: true,
}
websiteSSL, err := caService.ObtainSSL(caRequest)
if err != nil {
return err
}
defer func() {
_ = NewIWebsiteSSLService().Delete([]uint{websiteSSL.ID})
}()
defaultConfigPath := path.Join(appInstall.GetPath(), "conf", "default", "00.default.conf")
content, err := os.ReadFile(defaultConfigPath)
if err != nil {
@@ -2070,6 +2081,11 @@ func handleSSLConfig(appInstall *model.AppInstall, hasDefaultWebsite bool) error
updateDefaultServer(defaultServer, appInstall.HttpPort, appInstall.HttpsPort, !hasDefaultWebsite, true)
defaultServer.UpdateDirective("include", []string{"/usr/local/openresty/nginx/conf/ssl/root_ssl.conf"})
defaultServer.UpdateDirective("http2", []string{"on"})
if sslRejectHandshake {
defaultServer.UpdateDirective("ssl_reject_handshake", []string{"on"})
} else {
defaultServer.RemoveDirective("ssl_reject_handshake", []string{})
}
if err = nginx.WriteConfig(defaultConfig, nginx.IndentedStyle); err != nil {
return err
}
@@ -2131,3 +2147,56 @@ func needsUpdate(localTag *model.Tag, remoteTag dto.Tag, translations string) bo
localTag.Sort != remoteTag.Sort ||
localTag.Translations != translations
}
func hasLinkDB(installID uint) bool {
resources, _ := appInstallResourceRepo.GetBy(appInstallResourceRepo.WithAppInstallId(installID))
hasDB := false
if len(resources) > 0 {
for _, resource := range resources {
if resource.Key == constant.AppPostgres || resource.Key == constant.AppMysql ||
resource.Key == constant.AppMariaDB || resource.Key == constant.AppMysqlCluster ||
resource.Key == constant.AppPostgresql || resource.Key == constant.AppPostgresqlCluster {
hasDB = true
break
}
}
}
return hasDB
}
func isEditCompose(installed model.AppInstall) bool {
detail, _ := appDetailRepo.GetFirst(repo.WithByID(installed.AppDetailId))
rawCompose, err := getUpgradeCompose(installed, detail)
if rawCompose == "" || err != nil {
return false
}
if rawCompose != installed.DockerCompose {
return true
}
return false
}
func getAppVersions(key string, details []model.AppDetail) []string {
var (
versionsRaw []string
versions []string
)
hasLatest := false
latestVersion := ""
for _, detail := range details {
if key != "mssql" && strings.Contains(detail.Version, "latest") {
hasLatest = true
latestVersion = detail.Version
continue
}
if key == "openresty" && !common.CompareAppVersion(detail.Version, "1.27") {
continue
}
versionsRaw = append(versionsRaw, detail.Version)
}
versions = common.GetSortedVersions(versionsRaw)
if hasLatest {
versions = append([]string{latestVersion}, versions...)
}
return versions
}
+50 -37
View File
@@ -34,6 +34,7 @@ type IBackupService interface {
LoadBackupOptions() ([]dto.BackupOption, error)
SearchWithPage(search dto.SearchPageWithType) (int64, interface{}, error)
Create(backupDto dto.BackupOperate) error
CheckConn(req dto.BackupOperate) dto.BackupCheckRes
GetBuckets(backupDto dto.ForBuckets) ([]interface{}, error)
Update(req dto.BackupOperate) error
Delete(id uint) error
@@ -123,6 +124,43 @@ func (u *BackupService) SearchWithPage(req dto.SearchPageWithType) (int64, inter
return count, data, nil
}
func (u *BackupService) CheckConn(req dto.BackupOperate) dto.BackupCheckRes {
var res dto.BackupCheckRes
var backup model.BackupAccount
if err := copier.Copy(&backup, &req); err != nil {
res.Msg = i18n.GetMsgWithDetail("ErrStructTransform", err.Error())
return res
}
itemAccessKey, err := base64.StdEncoding.DecodeString(backup.AccessKey)
if err != nil {
res.Msg = err.Error()
return res
}
backup.AccessKey = string(itemAccessKey)
itemCredential, err := base64.StdEncoding.DecodeString(backup.Credential)
if err != nil {
res.Msg = err.Error()
return res
}
backup.Credential = string(itemCredential)
if req.Type == constant.OneDrive || req.Type == constant.GoogleDrive {
refreshToken, err := loadRefreshTokenByCode(&backup)
if err != nil {
res.Msg = err.Error()
return res
}
res.Token = base64.StdEncoding.EncodeToString([]byte(refreshToken))
}
isOk, err := u.checkBackupConn(&backup)
if err != nil {
res.Msg = err.Error()
return res
}
res.IsOk = isOk
return res
}
func (u *BackupService) Create(req dto.BackupOperate) error {
if req.Type == constant.Local {
return buserr.New("ErrBackupLocalCreate")
@@ -147,19 +185,6 @@ func (u *BackupService) Create(req dto.BackupOperate) error {
return err
}
backup.Credential = string(itemCredential)
if req.Type == constant.OneDrive || req.Type == constant.GoogleDrive || req.Type == constant.ALIYUN {
if err := loadRefreshTokenByCode(&backup); err != nil {
return err
}
}
if req.Type != constant.Local {
isOk, err := u.checkBackupConn(&backup)
if err != nil || !isOk {
return buserr.WithMap("ErrBackupCheck", map[string]interface{}{"err": err.Error()}, err)
}
}
backup.AccessKey, err = encrypt.StringEncrypt(backup.AccessKey)
if err != nil {
return err
@@ -248,16 +273,7 @@ func (u *BackupService) Update(req dto.BackupOperate) error {
global.Dir.LocalBackupDir = newBackup.BackupPath
}
if newBackup.Type == constant.OneDrive || newBackup.Type == constant.GoogleDrive || newBackup.Type == constant.ALIYUN {
if err := loadRefreshTokenByCode(&newBackup); err != nil {
return err
}
}
if backup.Type != constant.Local {
isOk, err := u.checkBackupConn(&newBackup)
if err != nil || !isOk {
return buserr.WithMap("ErrBackupCheck", map[string]interface{}{"err": err.Error()}, err)
}
newBackup.AccessKey, err = encrypt.StringEncrypt(newBackup.AccessKey)
if err != nil {
return err
@@ -514,37 +530,34 @@ func newClient(account *model.BackupAccount, isEncrypt bool) (cloud_storage.Clou
return client, nil
}
func loadRefreshTokenByCode(backup *model.BackupAccount) error {
func loadRefreshTokenByCode(backup *model.BackupAccount) (string, error) {
varMap := make(map[string]interface{})
if err := json.Unmarshal([]byte(backup.Vars), &varMap); err != nil {
return fmt.Errorf("unmarshal backup vars failed, err: %v", err)
return "", fmt.Errorf("unmarshal backup vars failed, err: %v", err)
}
if _, ok := varMap["refresh_token"]; ok {
return "", nil
}
refreshToken := ""
var err error
if backup.Type == constant.GoogleDrive {
switch backup.Type {
case constant.GoogleDrive:
refreshToken, err = client.RefreshGoogleToken("authorization_code", "refreshToken", varMap)
if err != nil {
return err
return "", err
}
}
if backup.Type == constant.OneDrive {
case constant.OneDrive:
refreshToken, err = client.RefreshToken("authorization_code", "refreshToken", varMap)
if err != nil {
return err
return "", err
}
}
if backup.Type != constant.ALIYUN {
delete(varMap, "code")
varMap["refresh_token"] = refreshToken
}
varMap["refresh_status"] = constant.StatusSuccess
varMap["refresh_time"] = time.Now().Format(constant.DateTimeLayout)
itemVars, err := json.Marshal(varMap)
if err != nil {
return fmt.Errorf("json marshal var map failed, err: %v", err)
}
itemVars, _ := json.Marshal(varMap)
backup.Vars = string(itemVars)
return nil
return refreshToken, nil
}
func loadBackupNamesByID(accountIDs string, downloadID uint) ([]string, string, error) {
+3 -3
View File
@@ -102,7 +102,7 @@ func backupDatabaseWithTask(parentTask *task.Task, resourceKey, tmpDir, name str
}
parentTask.LogStart(task.GetTaskName(db.Name, task.TaskBackup, task.TaskScopeDatabase))
databaseHelper := DatabaseHelper{Database: db.MysqlName, DBType: resourceKey, Name: db.Name}
if err := handleMysqlBackup(databaseHelper, parentTask, 0, tmpDir, fmt.Sprintf("%s.sql.gz", name), ""); err != nil {
if err := handleMysqlBackup(databaseHelper, parentTask, 0, tmpDir, fmt.Sprintf("%s.sql.gz", name), "", ""); err != nil {
return err
}
parentTask.LogSuccess(task.GetTaskName(db.Name, task.TaskBackup, task.TaskScopeDatabase))
@@ -113,7 +113,7 @@ func backupDatabaseWithTask(parentTask *task.Task, resourceKey, tmpDir, name str
}
parentTask.LogStart(task.GetTaskName(db.Name, task.TaskBackup, task.TaskScopeDatabase))
databaseHelper := DatabaseHelper{Database: db.PostgresqlName, DBType: resourceKey, Name: db.Name}
if err := handlePostgresqlBackup(databaseHelper, parentTask, 0, tmpDir, fmt.Sprintf("%s.sql.gz", name), ""); err != nil {
if err := handlePostgresqlBackup(databaseHelper, parentTask, 0, tmpDir, fmt.Sprintf("%s.sql.gz", name), "", ""); err != nil {
return err
}
parentTask.LogSuccess(task.GetTaskName(db.Name, task.TaskBackup, task.TaskScopeDatabase))
@@ -260,7 +260,7 @@ func handleAppRecover(install *model.AppInstall, parentTask *task.Task, recoverF
Name: newDB.MysqlName,
DetailName: newDB.Name,
File: fmt.Sprintf("%s/%s.sql.gz", tmpPath, install.Name),
}, parentTask, true, ""); err != nil {
}, parentTask, true); err != nil {
t.LogFailedWithErr(taskName, err)
return err
}
+41 -20
View File
@@ -8,17 +8,14 @@ import (
"strings"
"time"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/i18n"
"github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/app/task"
"github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/global"
"github.com/1Panel-dev/1Panel/agent/i18n"
"github.com/1Panel-dev/1Panel/agent/utils/common"
"github.com/1Panel-dev/1Panel/agent/utils/files"
"github.com/1Panel-dev/1Panel/agent/utils/mysql/client"
@@ -48,7 +45,7 @@ func (u *BackupService) MysqlBackup(req dto.CommonBackup) error {
}
databaseHelper := DatabaseHelper{Database: req.Name, DBType: req.Type, Name: req.DetailName}
if err := handleMysqlBackup(databaseHelper, nil, record.ID, targetDir, fileName, req.TaskID); err != nil {
if err := handleMysqlBackup(databaseHelper, nil, record.ID, targetDir, fileName, req.TaskID, req.Secret); err != nil {
backupRepo.UpdateRecordByMap(record.ID, map[string]interface{}{"status": constant.StatusFailed, "message": err.Error()})
return err
}
@@ -56,23 +53,23 @@ func (u *BackupService) MysqlBackup(req dto.CommonBackup) error {
}
func (u *BackupService) MysqlRecover(req dto.CommonRecover) error {
return handleMysqlRecover(req, nil, false, req.TaskID)
return handleMysqlRecover(req, nil, false)
}
func (u *BackupService) MysqlRecoverByUpload(req dto.CommonRecover) error {
recoveFile, err := loadSqlFile(req.File)
recoverFile, err := loadSqlFile(req.File)
if err != nil {
return err
}
req.File = recoveFile
req.File = recoverFile
if err := handleMysqlRecover(req, nil, false, req.TaskID); err != nil {
if err := handleMysqlRecover(req, nil, false); err != nil {
return err
}
return nil
}
func handleMysqlBackup(db DatabaseHelper, parentTask *task.Task, recordID uint, targetDir, fileName, taskID string) error {
func handleMysqlBackup(db DatabaseHelper, parentTask *task.Task, recordID uint, targetDir, fileName, taskID, secret string) error {
var (
err error
backupTask *task.Task
@@ -90,11 +87,11 @@ func handleMysqlBackup(db DatabaseHelper, parentTask *task.Task, recordID uint,
}
}
itemHandler := func() error { return doMysqlBackup(db, targetDir, fileName) }
itemHandler := func() error { return doMysqlBackup(db, targetDir, fileName, secret) }
if parentTask != nil {
return itemHandler()
}
backupTask.AddSubTaskWithOps(task.GetTaskName(itemName, task.TaskBackup, task.TaskScopeBackup), func(t *task.Task) error { return itemHandler() }, nil, 3, time.Hour)
backupTask.AddSubTaskWithOps(task.GetTaskName(itemName, task.TaskBackup, task.TaskScopeBackup), func(t *task.Task) error { return itemHandler() }, nil, 0, 3*time.Hour)
go func() {
if err := backupTask.Execute(); err != nil {
backupRepo.UpdateRecordByMap(recordID, map[string]interface{}{"status": constant.StatusFailed, "message": err.Error()})
@@ -105,7 +102,7 @@ func handleMysqlBackup(db DatabaseHelper, parentTask *task.Task, recordID uint,
return nil
}
func handleMysqlRecover(req dto.CommonRecover, parentTask *task.Task, isRollback bool, taskID string) error {
func handleMysqlRecover(req dto.CommonRecover, parentTask *task.Task, isRollback bool) error {
var (
err error
itemTask *task.Task
@@ -117,7 +114,7 @@ func handleMysqlRecover(req dto.CommonRecover, parentTask *task.Task, isRollback
}
itemName := fmt.Sprintf("%s[%s] - %s", req.Name, req.Type, req.DetailName)
if parentTask == nil {
itemTask, err = task.NewTaskWithOps(itemName, task.TaskRecover, task.TaskScopeBackup, taskID, dbInfo.ID)
itemTask, err = task.NewTaskWithOps(itemName, task.TaskRecover, task.TaskScopeBackup, req.TaskID, dbInfo.ID)
if err != nil {
return err
}
@@ -170,6 +167,15 @@ func handleMysqlRecover(req dto.CommonRecover, parentTask *task.Task, isRollback
}
}()
}
if len(req.Secret) != 0 {
err = files.OpensslDecrypt(req.File, req.Secret)
if err != nil {
return err
}
req.File = path.Join(path.Dir(req.File), "tmp_"+path.Base(req.File))
defer os.Remove(req.File)
t.LogWithStatus(i18n.GetMsgByKey("Decrypt"), err)
}
if err := cli.Recover(client.RecoverInfo{
Name: req.DetailName,
Type: req.Type,
@@ -187,14 +193,23 @@ func handleMysqlRecover(req dto.CommonRecover, parentTask *task.Task, isRollback
return recoverDatabase(parentTask)
}
itemTask.AddSubTaskWithOps(i18n.GetMsgByKey("TaskRecover"), recoverDatabase, nil, 3, time.Hour)
var timeout time.Duration
switch req.Timeout {
case -1:
timeout = 0
case 0:
timeout = 3 * time.Hour
default:
timeout = time.Duration(req.Timeout) * time.Second
}
itemTask.AddSubTaskWithOps(i18n.GetMsgByKey("TaskRecover"), recoverDatabase, nil, 0, timeout)
go func() {
_ = itemTask.Execute()
}()
return nil
}
func doMysqlBackup(db DatabaseHelper, targetDir, fileName string) error {
func doMysqlBackup(db DatabaseHelper, targetDir, fileName, secret string) error {
dbInfo, err := mysqlRepo.Get(repo.WithByName(db.Name), mysqlRepo.WithByMysqlName(db.Database))
if err != nil {
return err
@@ -211,7 +226,13 @@ func doMysqlBackup(db DatabaseHelper, targetDir, fileName string) error {
TargetDir: targetDir,
FileName: fileName,
}
return cli.Backup(backupInfo)
if err := cli.Backup(backupInfo); err != nil {
return err
}
if len(secret) != 0 {
return files.OpensslEncrypt(path.Join(targetDir, fileName), secret)
}
return nil
}
func loadSqlFile(file string) (string, error) {
+47 -19
View File
@@ -6,19 +6,15 @@ import (
"path"
"time"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/i18n"
"github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/utils/common"
pgclient "github.com/1Panel-dev/1Panel/agent/utils/postgresql/client"
"github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/app/task"
"github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/global"
"github.com/1Panel-dev/1Panel/agent/i18n"
"github.com/1Panel-dev/1Panel/agent/utils/common"
"github.com/1Panel-dev/1Panel/agent/utils/files"
"github.com/1Panel-dev/1Panel/agent/utils/postgresql/client"
)
@@ -46,7 +42,7 @@ func (u *BackupService) PostgresqlBackup(req dto.CommonBackup) error {
}
databaseHelper := DatabaseHelper{Database: req.Name, DBType: req.Type, Name: req.DetailName}
if err := handlePostgresqlBackup(databaseHelper, nil, record.ID, targetDir, fileName, req.TaskID); err != nil {
if err := handlePostgresqlBackup(databaseHelper, nil, record.ID, targetDir, fileName, req.TaskID, req.Secret); err != nil {
return err
}
return nil
@@ -59,11 +55,11 @@ func (u *BackupService) PostgresqlRecover(req dto.CommonRecover) error {
}
func (u *BackupService) PostgresqlRecoverByUpload(req dto.CommonRecover) error {
recoveFile, err := loadSqlFile(req.File)
recoverFile, err := loadSqlFile(req.File)
if err != nil {
return err
}
req.File = recoveFile
req.File = recoverFile
if err := handlePostgresqlRecover(req, nil, false); err != nil {
return err
}
@@ -71,7 +67,7 @@ func (u *BackupService) PostgresqlRecoverByUpload(req dto.CommonRecover) error {
return nil
}
func handlePostgresqlBackup(db DatabaseHelper, parentTask *task.Task, recordID uint, targetDir, fileName, taskID string) error {
func handlePostgresqlBackup(db DatabaseHelper, parentTask *task.Task, recordID uint, targetDir, fileName, taskID, secret string) error {
var (
err error
backupTask *task.Task
@@ -85,11 +81,11 @@ func handlePostgresqlBackup(db DatabaseHelper, parentTask *task.Task, recordID u
}
}
itemHandler := func() error { return doPostgresqlgBackup(db, targetDir, fileName) }
itemHandler := func() error { return doPostgresqlBackup(db, targetDir, fileName, secret, backupTask) }
if parentTask != nil {
return itemHandler()
}
backupTask.AddSubTaskWithOps(task.GetTaskName(itemName, task.TaskBackup, task.TaskScopeBackup), func(t *task.Task) error { return itemHandler() }, nil, 3, time.Hour)
backupTask.AddSubTaskWithOps(task.GetTaskName(itemName, task.TaskBackup, task.TaskScopeBackup), func(t *task.Task) error { return itemHandler() }, nil, 0, 3*time.Hour)
go func() {
if err := backupTask.Execute(); err != nil {
backupRepo.UpdateRecordByMap(recordID, map[string]interface{}{"status": constant.StatusFailed, "message": err.Error()})
@@ -133,10 +129,12 @@ func handlePostgresqlRecover(req dto.CommonRecover, parentTask *task.Task, isRol
if !isRollback {
rollbackFile := path.Join(global.Dir.TmpDir, fmt.Sprintf("database/%s/%s_%s.sql.gz", req.Type, req.DetailName, time.Now().Format(constant.DateTimeSlimLayout)))
if err := cli.Backup(client.BackupInfo{
Database: req.Name,
Name: req.DetailName,
TargetDir: path.Dir(rollbackFile),
FileName: path.Base(rollbackFile),
Task: t,
Timeout: 300,
}); err != nil {
return fmt.Errorf("backup postgresql db %s for rollback before recover failed, err: %v", req.DetailName, err)
@@ -145,9 +143,11 @@ func handlePostgresqlRecover(req dto.CommonRecover, parentTask *task.Task, isRol
if !isOk {
global.LOG.Info("recover failed, start to rollback now")
if err := cli.Recover(client.RecoverInfo{
Database: req.Name,
Name: req.DetailName,
SourceFile: rollbackFile,
Task: t,
Timeout: 300,
}); err != nil {
global.LOG.Errorf("rollback postgresql db %s from %s failed, err: %v", req.DetailName, rollbackFile, err)
@@ -160,10 +160,21 @@ func handlePostgresqlRecover(req dto.CommonRecover, parentTask *task.Task, isRol
}
}()
}
if len(req.Secret) != 0 {
err = files.OpensslDecrypt(req.File, req.Secret)
if err != nil {
return err
}
req.File = path.Join(path.Dir(req.File), "tmp_"+path.Base(req.File))
defer os.Remove(req.File)
t.LogWithStatus(i18n.GetMsgByKey("Decrypt"), err)
}
if err := cli.Recover(client.RecoverInfo{
Database: req.Name,
Name: req.DetailName,
SourceFile: req.File,
Username: dbInfo.Username,
Task: t,
Timeout: 300,
}); err != nil {
global.LOG.Errorf("recover postgresql db %s from %s failed, err: %v", req.DetailName, req.File, err)
@@ -176,25 +187,42 @@ func handlePostgresqlRecover(req dto.CommonRecover, parentTask *task.Task, isRol
return recoverDatabase(parentTask)
}
itemTask.AddSubTaskWithOps(i18n.GetMsgByKey("TaskRecover"), recoverDatabase, nil, 3, time.Hour)
var timeout time.Duration
switch req.Timeout {
case -1:
timeout = 0
case 0:
timeout = 3 * time.Hour
default:
timeout = time.Duration(req.Timeout) * time.Second
}
itemTask.AddSubTaskWithOps(i18n.GetMsgByKey("TaskRecover"), recoverDatabase, nil, 0, timeout)
go func() {
_ = itemTask.Execute()
}()
return nil
}
func doPostgresqlgBackup(db DatabaseHelper, targetDir, fileName string) error {
func doPostgresqlBackup(db DatabaseHelper, targetDir, fileName, secret string, task *task.Task) error {
cli, err := LoadPostgresqlClientByFrom(db.Database)
if err != nil {
return err
}
defer cli.Close()
backupInfo := pgclient.BackupInfo{
backupInfo := client.BackupInfo{
Database: db.Database,
Name: db.Name,
TargetDir: targetDir,
FileName: fileName,
Task: task,
Timeout: 300,
}
return cli.Backup(backupInfo)
if err := cli.Backup(backupInfo); err != nil {
return err
}
if len(secret) != 0 {
return files.OpensslEncrypt(path.Join(targetDir, fileName), secret)
}
return nil
}
+6 -10
View File
@@ -19,7 +19,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/utils/common"
"github.com/1Panel-dev/1Panel/agent/utils/compose"
"github.com/1Panel-dev/1Panel/agent/utils/files"
"github.com/pkg/errors"
)
func (u *BackupService) RedisBackup(req dto.CommonBackup) error {
@@ -98,9 +97,8 @@ func handleRedisBackup(redisInfo *repo.RootInfo, parentTask *task.Task, recordID
}
}
stdout, err := cmd.RunDefaultWithStdoutBashCf("docker exec %s redis-cli -a %s --no-auth-warning save", redisInfo.ContainerName, redisInfo.Password)
if err != nil {
return errors.New(string(stdout))
if err := cmd.RunDefaultBashCf("docker exec %s redis-cli -a %s --no-auth-warning save", redisInfo.ContainerName, redisInfo.Password); err != nil {
return err
}
if strings.HasSuffix(fileName, ".tar.gz") {
@@ -111,16 +109,14 @@ func handleRedisBackup(redisInfo *repo.RootInfo, parentTask *task.Task, recordID
return nil
}
if strings.HasSuffix(fileName, ".aof") {
stdout1, err := cmd.RunDefaultWithStdoutBashCf("docker cp %s:/data/appendonly.aof %s/%s", redisInfo.ContainerName, backupDir, fileName)
if err != nil {
return errors.New(stdout1)
if err := cmd.RunDefaultBashCf("docker cp %s:/data/appendonly.aof %s/%s", redisInfo.ContainerName, backupDir, fileName); err != nil {
return err
}
return nil
}
stdout1, err1 := cmd.RunDefaultWithStdoutBashCf("docker cp %s:/data/dump.rdb %s/%s", redisInfo.ContainerName, backupDir, fileName)
if err1 != nil {
return errors.New(stdout1)
if err := cmd.RunDefaultBashCf("docker cp %s:/data/dump.rdb %s/%s", redisInfo.ContainerName, backupDir, fileName); err != nil {
return err
}
return nil
}
+5 -7
View File
@@ -16,7 +16,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/i18n"
"github.com/1Panel-dev/1Panel/agent/utils/cmd"
"github.com/1Panel-dev/1Panel/agent/utils/compose"
"github.com/pkg/errors"
"github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/model"
@@ -132,7 +131,7 @@ func handleWebsiteRecover(website *model.Website, parentTask *task.Task, recover
if err != nil {
return err
}
if err = fileOp.CopyFile(fmt.Sprintf("%s/%s.conf", tmpPath, website.Alias), GetOpenrestyDir(SiteConfDir)); err != nil {
if err = fileOp.CopyFile(fmt.Sprintf("%s/%s.conf", tmpPath, website.Alias), GetConfDir(*website)); err != nil {
return err
}
@@ -179,9 +178,8 @@ func handleWebsiteRecover(website *model.Website, parentTask *task.Task, recover
if err = fileOp.TarGzExtractPro(fmt.Sprintf("%s/%s.web.tar.gz", tmpPath, website.Alias), GetOpenrestyDir(SitesRootDir), ""); err != nil {
return err
}
stdout, err := cmd.RunDefaultWithStdoutBashCf("docker exec -i %s nginx -s reload", nginxInfo.ContainerName)
if err != nil {
return errors.New(stdout)
if err := cmd.RunDefaultBashCf("docker exec -i %s nginx -s reload", nginxInfo.ContainerName); err != nil {
return err
}
oldWebsite.ID = website.ID
if err := websiteRepo.SaveWithoutCtx(&oldWebsite); err != nil {
@@ -261,7 +259,7 @@ func doWebsiteBackup(website *model.Website, parentTask *task.Task, backupDir, f
if err := fileOp.SaveFile(tmpDir+"/website.json", string(remarkInfo), fs.ModePerm); err != nil {
return err
}
nginxConfFile := GetSitePath(*website, SiteConf)
nginxConfFile := GetWebsiteConfigPath(*website)
if err := fileOp.CopyFile(nginxConfFile, tmpDir); err != nil {
return err
}
@@ -365,7 +363,7 @@ func recoverWebsiteDatabase(t *task.Task, dbID uint, dbType, tmpPath, websiteKey
Name: db.MysqlName,
DetailName: db.Name,
File: fmt.Sprintf("%s/%s.sql.gz", tmpPath, websiteKey),
}, t, true, ""); err != nil {
}, t, true); err != nil {
t.LogFailedWithErr(taskName, err)
return err
}
+76 -90
View File
@@ -21,14 +21,15 @@ import (
"github.com/1Panel-dev/1Panel/agent/utils/clam"
"github.com/1Panel-dev/1Panel/agent/utils/cmd"
"github.com/1Panel-dev/1Panel/agent/utils/common"
"github.com/1Panel-dev/1Panel/agent/utils/systemctl"
"github.com/1Panel-dev/1Panel/agent/utils/controller"
"github.com/1Panel-dev/1Panel/agent/utils/xpack"
"github.com/jinzhu/copier"
"github.com/robfig/cron/v3"
)
type ClamService struct {
serviceName string
serviceName string
freshClamService string
}
type IClamService interface {
@@ -56,23 +57,31 @@ func (c *ClamService) LoadBaseInfo() (dto.ClamBaseInfo, error) {
var baseInfo dto.ClamBaseInfo
baseInfo.Version = "-"
baseInfo.FreshVersion = "-"
exist1, _ := systemctl.IsExist(constant.ClamServiceNameCentOs)
if exist1 {
c.serviceName = constant.ClamServiceNameCentOs
baseInfo.IsExist = true
baseInfo.IsActive, _ = systemctl.IsActive(constant.ClamServiceNameCentOs)
clamSvc, err := controller.LoadServiceName("clam")
if err != nil {
baseInfo.IsExist = false
return baseInfo, nil
}
exist2, _ := systemctl.IsExist(constant.ClamServiceNameUbuntu)
if exist2 {
c.serviceName = constant.ClamServiceNameUbuntu
c.serviceName = clamSvc
exist, _ := controller.CheckExist(clamSvc)
if exist {
baseInfo.IsExist = true
baseInfo.IsActive, _ = systemctl.IsActive(constant.ClamServiceNameUbuntu)
baseInfo.IsActive, _ = controller.CheckActive(clamSvc)
}
freshExist, _ := systemctl.IsExist(constant.FreshClamService)
freshSvc, err := controller.LoadServiceName("freshclam")
if err != nil {
baseInfo.FreshIsExist = false
return baseInfo, nil
}
c.freshClamService = freshSvc
freshExist, _ := controller.CheckExist(freshSvc)
if freshExist {
baseInfo.FreshIsExist = true
baseInfo.FreshIsActive, _ = systemctl.IsActive(constant.FreshClamService)
baseInfo.FreshIsActive, _ = controller.CheckActive(freshSvc)
}
if !cmd.Which("clamdscan") {
baseInfo.IsActive = false
}
@@ -87,7 +96,7 @@ func (c *ClamService) LoadBaseInfo() (dto.ClamBaseInfo, error) {
}
}
} else {
_ = clam.CheckClamIsActive(false, clamRepo)
_ = clam.StopAllClamJob(false, clamRepo)
}
if baseInfo.FreshIsActive {
version, err := cmd.RunDefaultWithStdoutBashC("freshclam --version")
@@ -105,15 +114,13 @@ func (c *ClamService) LoadBaseInfo() (dto.ClamBaseInfo, error) {
func (c *ClamService) Operate(operate string) error {
switch operate {
case "start", "restart", "stop":
stdout, err := cmd.RunDefaultWithStdoutBashCf("systemctl %s %s", operate, c.serviceName)
if err != nil {
return fmt.Errorf("%s the %s failed, err: %s", operate, c.serviceName, stdout)
if err := controller.Handle(operate, c.serviceName); err != nil {
return fmt.Errorf("%s the %s failed, err: %s", operate, c.serviceName, err)
}
return nil
case "fresh-start", "fresh-restart", "fresh-stop":
stdout, err := cmd.RunDefaultWithStdoutBashCf("systemctl %s %s", strings.TrimPrefix(operate, "fresh-"), constant.FreshClamService)
if err != nil {
return fmt.Errorf("%s the %s failed, err: %s", operate, c.serviceName, stdout)
if err := controller.Handle(strings.TrimPrefix(operate, "fresh-"), c.freshClamService); err != nil {
return fmt.Errorf("%s the %s failed, err: %s", operate, c.serviceName, err)
}
return nil
default:
@@ -306,7 +313,7 @@ func (c *ClamService) Delete(req dto.ClamDelete) error {
}
func (c *ClamService) HandleOnce(id uint) error {
if active := clam.CheckClamIsActive(true, clamRepo); !active {
if active := clam.StopAllClamJob(true, clamRepo); !active {
return buserr.New("ErrClamdscanNotFound")
}
clamItem, _ := clamRepo.Get(repo.WithByID(id))
@@ -379,37 +386,13 @@ func (c *ClamService) LoadFile(req dto.ClamFileReq) (string, error) {
filePath := ""
switch req.Name {
case "clamd":
if c.serviceName == constant.ClamServiceNameUbuntu {
filePath = "/etc/clamav/clamd.conf"
} else {
filePath = "/etc/clamd.d/scan.conf"
}
filePath = c.loadConfigPath("clamd")
case "clamd-log":
filePath = c.loadLogPath("clamd-log")
if len(filePath) != 0 {
break
}
if c.serviceName == constant.ClamServiceNameUbuntu {
filePath = "/var/log/clamav/clamav.log"
} else {
filePath = "/var/log/clamd.scan"
}
case "freshclam":
if c.serviceName == constant.ClamServiceNameUbuntu {
filePath = "/etc/clamav/freshclam.conf"
} else {
filePath = "/etc/freshclam.conf"
}
filePath = c.loadConfigPath("freshclam")
case "freshclam-log":
filePath = c.loadLogPath("freshclam-log")
if len(filePath) != 0 {
break
}
if c.serviceName == constant.ClamServiceNameUbuntu {
filePath = "/var/log/clamav/freshclam.log"
} else {
filePath = "/var/log/freshclam.log"
}
default:
return "", fmt.Errorf("not support such type")
}
@@ -432,23 +415,11 @@ func (c *ClamService) LoadFile(req dto.ClamFileReq) (string, error) {
func (c *ClamService) UpdateFile(req dto.UpdateByNameAndFile) error {
filePath := ""
service := ""
switch req.Name {
case "clamd":
if c.serviceName == constant.ClamServiceNameUbuntu {
service = constant.ClamServiceNameUbuntu
filePath = "/etc/clamav/clamd.conf"
} else {
service = constant.ClamServiceNameCentOs
filePath = "/etc/clamd.d/scan.conf"
}
filePath = c.loadConfigPath("clamd")
case "freshclam":
if c.serviceName == constant.ClamServiceNameUbuntu {
filePath = "/etc/clamav/freshclam.conf"
} else {
filePath = "/etc/freshclam.conf"
}
service = "clamav-freshclam.service"
filePath = c.loadConfigPath("freshclam")
default:
return fmt.Errorf("not support such type")
}
@@ -461,50 +432,65 @@ func (c *ClamService) UpdateFile(req dto.UpdateByNameAndFile) error {
_, _ = write.WriteString(req.File)
write.Flush()
_ = systemctl.Restart(service)
_ = controller.HandleRestart(c.serviceName)
return nil
}
func (c *ClamService) loadLogPath(name string) string {
confPath := ""
if name == "clamd-log" {
if c.serviceName == constant.ClamServiceNameUbuntu {
confPath = "/etc/clamav/clamd.conf"
} else {
confPath = "/etc/clamd.d/scan.conf"
}
} else {
if c.serviceName == constant.ClamServiceNameUbuntu {
confPath = "/etc/clamav/freshclam.conf"
} else {
confPath = "/etc/freshclam.conf"
}
}
if _, err := os.Stat(confPath); err != nil {
return ""
configKey := "clamd"
searchPrefix := "LogFile "
if name != "clamd-log" {
configKey = "freshclam"
searchPrefix = "UpdateLogFile "
}
confPath := c.loadConfigPath(configKey)
content, err := os.ReadFile(confPath)
if err != nil {
global.LOG.Debugf("read config of %s failed, err: %v", configKey, err)
return ""
}
lines := strings.Split(string(content), "\n")
if name == "clamd-log" {
for _, line := range lines {
if strings.HasPrefix(line, "LogFile ") {
return strings.Trim(strings.ReplaceAll(line, "LogFile ", ""), " ")
}
}
} else {
for _, line := range lines {
if strings.HasPrefix(line, "UpdateLogFile ") {
return strings.Trim(strings.ReplaceAll(line, "UpdateLogFile ", ""), " ")
}
for _, line := range lines {
if strings.HasPrefix(line, searchPrefix) {
return strings.Trim(strings.ReplaceAll(line, searchPrefix, ""), " ")
}
}
if configKey == "clamd" {
if _, err := os.Stat("/var/log/clamav/clamav.log"); err == nil {
return "/var/log/clamav/clamav.log"
}
if _, err := os.Stat("/var/log/clamd.scan"); err == nil {
return "/var/log/clamd.scan"
}
}
if configKey == "freshclam" {
if _, err := os.Stat("/var/log/clamav/freshclam.log"); err == nil {
return "/var/log/clamav/freshclam.log"
}
if _, err := os.Stat("/var/log/freshclam.log"); err == nil {
return "/var/log/freshclam.log"
}
}
return ""
}
func (c *ClamService) loadConfigPath(confType string) string {
switch confType {
case "clamd":
if _, err := os.Stat("/etc/clamav/clamd.conf"); err == nil {
return "/etc/clamav/clamd.conf"
}
return "/etc/clamd.d/scan.conf"
case "freshclam":
if _, err := os.Stat("/etc/clamav/freshclam.conf"); err == nil {
return "/etc/clamav/freshclam.conf"
}
return "/etc/freshclam.conf"
default:
return ""
}
}
func handleAlert(infectedFiles, clamName string, clamId uint) {
itemInfected, _ := strconv.Atoi(strings.TrimSpace(infectedFiles))
if itemInfected < 0 {
+19 -1
View File
@@ -2,6 +2,7 @@ package service
import (
"github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/jinzhu/copier"
@@ -12,8 +13,9 @@ type ComposeTemplateService struct{}
type IComposeTemplateService interface {
List() ([]dto.ComposeTemplateInfo, error)
SearchWithPage(search dto.SearchWithPage) (int64, interface{}, error)
Create(composeDto dto.ComposeTemplateCreate) error
Create(req dto.ComposeTemplateCreate) error
Update(id uint, upMap map[string]interface{}) error
Batch(req dto.ComposeTemplateBatch) error
Delete(ids []uint) error
}
@@ -64,6 +66,22 @@ func (u *ComposeTemplateService) Create(composeDto dto.ComposeTemplateCreate) er
return nil
}
func (u *ComposeTemplateService) Batch(req dto.ComposeTemplateBatch) error {
for _, item := range req.Templates {
template, _ := composeRepo.Get(repo.WithByName(item.Name))
if template.ID == 0 {
if err := composeRepo.Create(&model.ComposeTemplate{Name: item.Name, Content: item.Content, Description: item.Description}); err != nil {
return err
}
} else {
if err := composeRepo.Update(template.ID, map[string]interface{}{"content": item.Content, "description": item.Description}); err != nil {
return err
}
}
}
return nil
}
func (u *ComposeTemplateService) Delete(ids []uint) error {
if len(ids) == 1 {
compose, _ := composeRepo.Get(repo.WithByID(ids[0]))
+265 -175
View File
@@ -12,7 +12,6 @@ import (
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
@@ -20,12 +19,8 @@ import (
"syscall"
"time"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/app/task"
"github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant"
@@ -34,6 +29,8 @@ import (
"github.com/1Panel-dev/1Panel/agent/utils/cmd"
"github.com/1Panel-dev/1Panel/agent/utils/common"
"github.com/1Panel-dev/1Panel/agent/utils/docker"
"github.com/1Panel-dev/1Panel/agent/utils/re"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/build"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
@@ -44,7 +41,9 @@ import (
"github.com/docker/docker/api/types/volume"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
"github.com/gin-gonic/gin"
v1 "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
"github.com/shirou/gopsutil/v4/cpu"
"github.com/shirou/gopsutil/v4/mem"
)
@@ -69,6 +68,7 @@ type IContainerService interface {
ContainerUpgrade(req dto.ContainerUpgrade) error
ContainerInfo(req dto.OperationWithName) (*dto.ContainerOperate, error)
ContainerListStats() ([]dto.ContainerListStats, error)
ContainerItemStats(req dto.OperationWithName) (dto.ContainerItemStats, error)
LoadResourceLimit() (*dto.ResourceLimit, error)
ContainerRename(req dto.ContainerRename) error
ContainerCommit(req dto.ContainerCommit) error
@@ -83,6 +83,7 @@ type IContainerService interface {
CreateVolume(req dto.VolumeCreate) error
TestCompose(req dto.ComposeCreate) (bool, error)
ComposeUpdate(req dto.ComposeUpdate) error
ComposeLogClean(req dto.ComposeLogClean) error
Prune(req dto.ContainerPrune) error
LoadUsers(req dto.OperationWithName) []string
@@ -95,18 +96,12 @@ func NewIContainerService() IContainerService {
}
func (u *ContainerService) Page(req dto.PageContainer) (int64, interface{}, error) {
var (
records []container.Summary
list []container.Summary
)
client, err := docker.NewDockerClient()
if err != nil {
return 0, nil, err
}
defer client.Close()
options := container.ListOptions{
All: true,
}
options := container.ListOptions{All: true}
if len(req.Filters) != 0 {
options.Filters = filters.NewArgs()
options.Filters.Add("label", req.Filters)
@@ -115,112 +110,32 @@ func (u *ContainerService) Page(req dto.PageContainer) (int64, interface{}, erro
if err != nil {
return 0, nil, err
}
if req.ExcludeAppStore {
for _, item := range containers {
if created, ok := item.Labels[composeCreatedBy]; ok && created == "Apps" {
continue
}
list = append(list, item)
}
} else {
list = containers
}
records := searchWithFilter(req, containers)
if len(req.Name) != 0 {
length, count := len(list), 0
for count < length {
if !strings.Contains(list[count].Names[0][1:], req.Name) && !strings.Contains(list[count].Image, req.Name) {
list = append(list[:count], list[(count+1):]...)
length--
} else {
count++
}
}
}
if req.State != "all" {
length, count := len(list), 0
for count < length {
if list[count].State != req.State {
list = append(list[:count], list[(count+1):]...)
length--
} else {
count++
}
}
}
switch req.OrderBy {
case "name":
sort.Slice(list, func(i, j int) bool {
if req.Order == constant.OrderAsc {
return list[i].Names[0][1:] < list[j].Names[0][1:]
}
return list[i].Names[0][1:] > list[j].Names[0][1:]
})
default:
sort.Slice(list, func(i, j int) bool {
if req.Order == constant.OrderAsc {
return list[i].Created < list[j].Created
}
return list[i].Created > list[j].Created
})
}
total, start, end := len(list), (req.Page-1)*req.PageSize, req.Page*req.PageSize
var backData []dto.ContainerInfo
total, start, end := len(records), (req.Page-1)*req.PageSize, req.Page*req.PageSize
if start > total {
records = make([]container.Summary, 0)
backData = make([]dto.ContainerInfo, 0)
} else {
if end >= total {
end = total
}
records = list[start:end]
backData = records[start:end]
}
backDatas := make([]dto.ContainerInfo, len(records))
for i := 0; i < len(records); i++ {
item := records[i]
IsFromCompose := false
if _, ok := item.Labels[composeProjectLabel]; ok {
IsFromCompose = true
}
IsFromApp := false
if created, ok := item.Labels[composeCreatedBy]; ok && created == "Apps" {
IsFromApp = true
}
exposePorts := transPortToStr(records[i].Ports)
info := dto.ContainerInfo{
ContainerID: item.ID,
CreateTime: time.Unix(item.Created, 0).Format(constant.DateTimeLayout),
Name: item.Names[0][1:],
ImageId: strings.Split(item.ImageID, ":")[1],
ImageName: item.Image,
State: item.State,
RunTime: item.Status,
Ports: exposePorts,
IsFromApp: IsFromApp,
IsFromCompose: IsFromCompose,
}
install, _ := appInstallRepo.GetFirst(appInstallRepo.WithContainerName(info.Name))
for i := 0; i < len(backData); i++ {
install, _ := appInstallRepo.GetFirst(appInstallRepo.WithContainerName(backData[i].Name))
if install.ID > 0 {
info.AppInstallName = install.Name
info.AppName = install.App.Name
backData[i].AppInstallName = install.Name
backData[i].AppName = install.App.Name
websites, _ := websiteRepo.GetBy(websiteRepo.WithAppInstallId(install.ID))
for _, website := range websites {
info.Websites = append(info.Websites, website.PrimaryDomain)
backData[i].Websites = append(backData[i].Websites, website.PrimaryDomain)
}
}
backDatas[i] = info
if item.NetworkSettings != nil && len(item.NetworkSettings.Networks) > 0 {
networks := make([]string, 0, len(item.NetworkSettings.Networks))
for key := range item.NetworkSettings.Networks {
networks = append(networks, item.NetworkSettings.Networks[key].IPAddress)
}
sort.Strings(networks)
backDatas[i].Network = networks
}
}
return int64(total), backDatas, nil
return int64(total), backData, nil
}
func (u *ContainerService) List() []dto.ContainerOptions {
@@ -282,10 +197,8 @@ func (u *ContainerService) LoadStatus() (dto.ContainerStatus, error) {
}
defer client.Close()
c := context.Background()
images, _ := client.ImageList(c, image.ListOptions{})
for _, image := range images {
data.ImageSize += uint64(image.Size)
}
images, _ := client.ImageList(c, image.ListOptions{All: true})
data.ImageCount = len(images)
repo, _ := imageRepoRepo.List()
data.RepoCount = len(repo)
@@ -296,11 +209,8 @@ func (u *ContainerService) LoadStatus() (dto.ContainerStatus, error) {
volumes, _ := client.VolumeList(c, volume.ListOptions{})
data.VolumeCount = len(volumes.Volumes)
data.ComposeCount = loadComposeCount(client)
containers, err := client.ContainerList(c, container.ListOptions{All: true})
if err != nil {
return data, err
}
data.All = uint(len(containers))
containers, _ := client.ContainerList(c, container.ListOptions{All: true})
data.ContainerCount = len(containers)
for _, item := range containers {
switch item.State {
case "created":
@@ -319,7 +229,50 @@ func (u *ContainerService) LoadStatus() (dto.ContainerStatus, error) {
data.Removing++
}
}
data.ContainerCount = int(data.All)
return data, nil
}
func (u *ContainerService) ContainerItemStats(req dto.OperationWithName) (dto.ContainerItemStats, error) {
var data dto.ContainerItemStats
client, err := docker.NewDockerClient()
if err != nil {
return data, err
}
if req.Name != "system" {
defer client.Close()
containerInfo, _, err := client.ContainerInspectWithRaw(context.Background(), req.Name, true)
if err != nil {
return data, err
}
data.SizeRw = *containerInfo.SizeRw
data.SizeRootFs = *containerInfo.SizeRootFs
return data, nil
}
usage, err := client.DiskUsage(context.Background(), types.DiskUsageOptions{})
if err != nil {
return data, err
}
for _, item := range usage.Images {
data.ImageUsage += item.Size
if item.Containers < 1 {
data.ImageReclaimable += item.Size
}
}
for _, item := range usage.Containers {
data.ContainerUsage += item.SizeRw
if item.State != "running" {
data.ContainerReclaimable += item.SizeRw
}
}
for _, item := range usage.Volumes {
data.VolumeUsage += item.UsageData.Size
if item.UsageData.RefCount == 0 {
data.VolumeReclaimable += item.UsageData.Size
}
}
for _, item := range usage.BuildCache {
data.BuildCacheUsage += item.Size
}
return data, nil
}
func (u *ContainerService) ContainerListStats() ([]dto.ContainerListStats, error) {
@@ -407,6 +360,9 @@ func (u *ContainerService) Inspect(req dto.InspectReq) (string, error) {
}
for _, container := range containers {
config := container.Labels[composeConfigLabel]
if len(req.Detail) != 0 && strings.Contains(config, req.Detail) {
config = req.Detail
}
workdir := container.Labels[composeWorkdirLabel]
if len(config) != 0 && len(workdir) != 0 && strings.Contains(config, workdir) {
filePath = config
@@ -478,6 +434,7 @@ func (u *ContainerService) Prune(req dto.ContainerPrune) error {
pruneFilters.Add("until", "24h")
}
}
taskItem.Log(i18n.GetMsgByKey("PruneStart"))
DeletedNumber := 0
SpaceReclaimed := 0
switch req.PruneType {
@@ -643,27 +600,27 @@ func (u *ContainerService) ContainerInfo(req dto.OperationWithName) (*dto.Contai
data.Name = strings.ReplaceAll(oldContainer.Name, "/", "")
data.Image = oldContainer.Config.Image
if oldContainer.NetworkSettings != nil {
for network := range oldContainer.NetworkSettings.Networks {
data.Network = network
break
for net, val := range oldContainer.NetworkSettings.Networks {
netItem := dto.ContainerNetwork{
Network: net,
MacAddr: val.MacAddress,
}
if val.IPAMConfig != nil {
if netItem.Network != "bridge" {
netItem.Ipv4 = val.IPAMConfig.IPv4Address
netItem.Ipv6 = val.IPAMConfig.IPv6Address
}
} else {
if netItem.Network != "bridge" {
netItem.Ipv4 = val.IPAddress
}
}
data.Networks = append(data.Networks, netItem)
}
}
exposePorts, _ := loadPortByInspect(oldContainer.ID, client)
data.ExposedPorts = loadContainerPortForInfo(exposePorts)
networkSettings := oldContainer.NetworkSettings
bridgeNetworkSettings := networkSettings.Networks[data.Network]
if bridgeNetworkSettings.IPAMConfig != nil {
data.MacAddr = bridgeNetworkSettings.MacAddress
if data.Network != "bridge" {
data.Ipv4 = bridgeNetworkSettings.IPAMConfig.IPv4Address
data.Ipv6 = bridgeNetworkSettings.IPAMConfig.IPv6Address
}
} else {
if data.Network != "bridge" {
data.Ipv4 = bridgeNetworkSettings.IPAddress
}
}
data.Hostname = oldContainer.Config.Hostname
data.DNS = oldContainer.HostConfig.DNS
data.DomainName = oldContainer.Config.Domainname
@@ -895,25 +852,36 @@ func (u *ContainerService) ContainerOperation(req dto.ContainerOperation) error
return err
}
defer client.Close()
for _, item := range req.Names {
global.LOG.Infof("start container %s operation %s", item, req.Operation)
switch req.Operation {
case constant.ContainerOpStart:
err = client.ContainerStart(ctx, item, container.StartOptions{})
case constant.ContainerOpStop:
err = client.ContainerStop(ctx, item, container.StopOptions{})
case constant.ContainerOpRestart:
err = client.ContainerRestart(ctx, item, container.StopOptions{})
case constant.ContainerOpKill:
err = client.ContainerKill(ctx, item, "SIGKILL")
case constant.ContainerOpPause:
err = client.ContainerPause(ctx, item)
case constant.ContainerOpUnpause:
err = client.ContainerUnpause(ctx, item)
case constant.ContainerOpRemove:
err = client.ContainerRemove(ctx, item, container.RemoveOptions{RemoveVolumes: true, Force: true})
}
taskItem, err := task.NewTaskWithOps(strings.Join(req.Names, " "), req.Operation, task.TaskScopeContainer, req.TaskID, 1)
if err != nil {
return fmt.Errorf("new task for container commit failed, err: %v", err)
}
for _, item := range req.Names {
taskItem.AddSubTask(item, func(t *task.Task) error {
switch req.Operation {
case constant.ContainerOpStart:
err = client.ContainerStart(ctx, item, container.StartOptions{})
case constant.ContainerOpStop:
err = client.ContainerStop(ctx, item, container.StopOptions{})
case constant.ContainerOpRestart:
err = client.ContainerRestart(ctx, item, container.StopOptions{})
case constant.ContainerOpKill:
err = client.ContainerKill(ctx, item, "SIGKILL")
case constant.ContainerOpPause:
err = client.ContainerPause(ctx, item)
case constant.ContainerOpUnpause:
err = client.ContainerUnpause(ctx, item)
case constant.ContainerOpRemove:
err = client.ContainerRemove(ctx, item, container.RemoveOptions{RemoveVolumes: true, Force: true})
}
return err
}, nil)
}
go func() {
_ = taskItem.Execute()
}()
return err
}
@@ -1002,12 +970,18 @@ func collectLogs(done <-chan struct{}, params dto.StreamLog, messageChan chan<-
var dockerCmd *exec.Cmd
if params.Type == "compose" {
dockerComposCmd := common.GetDockerComposeCommand()
if dockerComposCmd == "docker-compose" {
newCmdArgs := append([]string{"-f", params.Compose}, cmdArgs...)
dockerCmd = exec.Command(dockerComposCmd, newCmdArgs...)
dockerComposeCmd := common.GetDockerComposeCommand()
var yamlFiles []string
for _, item := range strings.Split(params.Compose, ",") {
if len(item) != 0 {
yamlFiles = append(yamlFiles, "-f", item)
}
}
if dockerComposeCmd == "docker-compose" {
newCmdArgs := append(yamlFiles, cmdArgs...)
dockerCmd = exec.Command(dockerComposeCmd, newCmdArgs...)
} else {
newCmdArgs := append([]string{"compose", "-f", params.Compose}, cmdArgs...)
newCmdArgs := append(append([]string{"compose"}, yamlFiles...), cmdArgs...)
dockerCmd = exec.Command("docker", newCmdArgs...)
}
} else {
@@ -1087,10 +1061,16 @@ func (u *ContainerService) DownloadContainerLogs(containerType, container, since
commandArg := []string{"logs", container}
dockerCommand := global.CONF.DockerConfig.Command
if containerType == "compose" {
var yamlFiles []string
for _, item := range strings.Split(container, ",") {
if len(item) != 0 {
yamlFiles = append(yamlFiles, "-f", item)
}
}
if dockerCommand == "docker-compose" {
commandArg = []string{"-f", container, "logs"}
commandArg = append(yamlFiles, "logs")
} else {
commandArg = []string{"compose", "-f", container, "logs"}
commandArg = append(append([]string{"compose"}, yamlFiles...), "logs")
}
}
@@ -1132,7 +1112,7 @@ func (u *ContainerService) DownloadContainerLogs(containerType, container, since
errCh := make(chan error)
go func() {
scanner := bufio.NewScanner(stdout)
var ansiRegex = regexp.MustCompile(`\x1b\[[0-9;?]*[A-Za-z]|\x1b=|\x1b>`)
var ansiRegex = re.GetRegex(re.AnsiEscapePattern)
for scanner.Scan() {
line := scanner.Text()
cleanLine := ansiRegex.ReplaceAllString(line, "")
@@ -1177,10 +1157,8 @@ func (u *ContainerService) ContainerStats(id string) (*dto.ContainerStats, error
body, err := io.ReadAll(res.Body)
if err != nil {
res.Body.Close()
return nil, err
}
res.Body.Close()
var stats *container.StatsResponse
if err := json.Unmarshal(body, &stats); err != nil {
return nil, err
@@ -1222,6 +1200,16 @@ func stringsToMap(list []string) map[string]string {
}
return labelMap
}
func stringsToMap2(list []string) map[string]*string {
var labelMap = make(map[string]*string)
for _, label := range list {
if strings.Contains(label, "=") {
sps := strings.SplitN(label, "=", 2)
labelMap[sps[0]] = &sps[1]
}
}
return labelMap
}
func calculateCPUPercentUnix(stats *container.StatsResponse) float64 {
cpuPercent := 0.0
@@ -1460,25 +1448,25 @@ func loadConfigInfo(isCreate bool, req dto.ContainerOperate, oldContainer *conta
config.User = req.User
config.WorkingDir = req.WorkingDir
if len(req.Network) != 0 {
switch req.Network {
case "host", "none", "bridge":
hostConf.NetworkMode = container.NetworkMode(req.Network)
}
if req.Ipv4 != "" || req.Ipv6 != "" {
networkConf.EndpointsConfig = map[string]*network.EndpointSettings{req.Network: {
IPAMConfig: &network.EndpointIPAMConfig{
IPv4Address: req.Ipv4,
IPv6Address: req.Ipv6,
}, MacAddress: req.MacAddr}}
} else {
networkConf.EndpointsConfig = map[string]*network.EndpointSettings{req.Network: {}}
if len(req.Networks) != 0 {
networkConf.EndpointsConfig = make(map[string]*network.EndpointSettings)
for _, item := range req.Networks {
switch item.Network {
case "host", "none", "bridge":
hostConf.NetworkMode = container.NetworkMode(item.Network)
}
if item.Ipv4 != "" || item.Ipv6 != "" {
networkConf.EndpointsConfig[item.Network] = &network.EndpointSettings{
IPAMConfig: &network.EndpointIPAMConfig{
IPv4Address: item.Ipv4,
IPv6Address: item.Ipv6,
}, MacAddress: item.MacAddr}
} else {
networkConf.EndpointsConfig[item.Network] = &network.EndpointSettings{}
}
}
} else {
if req.Ipv4 != "" || req.Ipv6 != "" {
return nil, nil, nil, fmt.Errorf("please set up the network")
}
networkConf = network.NetworkingConfig{}
return nil, nil, nil, fmt.Errorf("please set up the network")
}
hostConf.Privileged = req.Privileged
@@ -1726,3 +1714,105 @@ func loadContainerPortForInfo(itemPorts []container.Port) []dto.PortHelper {
}
return exposedPorts
}
func searchWithFilter(req dto.PageContainer, containers []container.Summary) []dto.ContainerInfo {
var (
records []dto.ContainerInfo
list []container.Summary
)
if req.ExcludeAppStore {
for _, item := range containers {
if created, ok := item.Labels[composeCreatedBy]; ok && created == "Apps" {
continue
}
list = append(list, item)
}
} else {
list = containers
}
if len(req.Name) != 0 {
length, count := len(list), 0
for count < length {
if !strings.Contains(list[count].Names[0][1:], req.Name) && !strings.Contains(list[count].Image, req.Name) {
list = append(list[:count], list[(count+1):]...)
length--
} else {
count++
}
}
}
if req.State != "all" {
length, count := len(list), 0
for count < length {
if list[count].State != req.State {
list = append(list[:count], list[(count+1):]...)
length--
} else {
count++
}
}
}
switch req.OrderBy {
case "name":
sort.Slice(list, func(i, j int) bool {
if req.Order == constant.OrderAsc {
return list[i].Names[0][1:] < list[j].Names[0][1:]
}
return list[i].Names[0][1:] > list[j].Names[0][1:]
})
default:
sort.Slice(list, func(i, j int) bool {
if req.Order == constant.OrderAsc {
return list[i].Created < list[j].Created
}
return list[i].Created > list[j].Created
})
}
for _, item := range list {
IsFromCompose := false
if _, ok := item.Labels[composeProjectLabel]; ok {
IsFromCompose = true
}
IsFromApp := false
if created, ok := item.Labels[composeCreatedBy]; ok && created == "Apps" {
IsFromApp = true
}
exposePorts := transPortToStr(item.Ports)
info := dto.ContainerInfo{
ContainerID: item.ID,
CreateTime: time.Unix(item.Created, 0).Format(constant.DateTimeLayout),
Name: item.Names[0][1:],
Ports: exposePorts,
ImageId: strings.Split(item.ImageID, ":")[1],
ImageName: item.Image,
State: item.State,
RunTime: item.Status,
IsFromApp: IsFromApp,
IsFromCompose: IsFromCompose,
}
if item.NetworkSettings != nil && len(item.NetworkSettings.Networks) > 0 {
networks := make([]string, 0, len(item.NetworkSettings.Networks))
for key := range item.NetworkSettings.Networks {
networks = append(networks, item.NetworkSettings.Networks[key].IPAddress)
}
sort.Strings(networks)
info.Network = networks
}
records = append(records, info)
}
descriptions, _ := settingRepo.GetDescriptionList(repo.WithByType("container"))
for i := 0; i < len(records); i++ {
for _, desc := range descriptions {
if desc.ID == records[i].ContainerID {
records[i].Description = desc.Description
records[i].IsPinned = desc.IsPinned
}
}
}
sort.Slice(records, func(i, j int) bool {
return records[i].IsPinned && !records[j].IsPinned
})
return records
}
+86 -45
View File
@@ -2,10 +2,12 @@ package service
import (
"bufio"
"context"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"sort"
"strings"
"time"
@@ -23,7 +25,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/utils/docker"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"golang.org/x/net/context"
)
const composeProjectLabel = "com.docker.compose.project"
@@ -73,6 +74,7 @@ func (u *ContainerService) PageCompose(req dto.SearchWithPage) (int64, interface
Name: container.Names[0][1:],
State: container.State,
CreateTime: time.Unix(container.Created, 0).Format(constant.DateTimeLayout),
Ports: transPortToStr(container.Ports),
}
if compose, has := composeMap[name]; has {
compose.ContainerCount++
@@ -179,7 +181,7 @@ func (u *ContainerService) TestCompose(req dto.ComposeCreate) (bool, error) {
cmd := getComposeCmd(req.Path, "config")
stdout, err := cmd.CombinedOutput()
if err != nil {
return false, errors.New(string(stdout))
return false, fmt.Errorf("docker-compose config failed, std: %s, err: %v", string(stdout), err)
}
return true, nil
}
@@ -203,14 +205,13 @@ func (u *ContainerService) CreateCompose(req dto.ComposeCreate) error {
}
go func() {
taskItem.AddSubTask(i18n.GetMsgByKey("ComposeCreate"), func(t *task.Task) error {
cmd := getComposeCmd(req.Path, "up")
out, err := cmd.CombinedOutput()
taskItem.Log(i18n.GetWithName("ComposeCreateRes", string(out)))
err := compose.UpWithTask(req.Path, t)
t.LogWithStatus(i18n.GetMsgByKey("ComposeCreate"), err)
if err != nil {
_, _ = compose.Down(req.Path)
return err
}
_ = composeRepo.CreateRecord(&model.Compose{Name: req.Name, Path: req.Path})
_ = composeRepo.CreateRecord(&model.Compose{Name: strings.ToLower(req.Name), Path: req.Path})
return nil
}, nil)
_ = taskItem.Execute()
@@ -232,24 +233,24 @@ func (u *ContainerService) ComposeOperation(req dto.ComposeOperation) error {
return err
}
if req.WithFile {
_ = os.RemoveAll(path.Dir(req.Path))
for _, item := range strings.Split(req.Path, ",") {
if len(item) != 0 {
_ = os.RemoveAll(path.Dir(item))
}
}
}
_ = composeRepo.DeleteRecord(repo.WithByName(req.Name))
return nil
}
if _, err := os.Stat(req.Path); err != nil {
return fmt.Errorf("load file with path %s failed, %v", req.Path, err)
}
if req.Operation == "up" {
if stdout, err := compose.Up(req.Path); err != nil {
return errors.New(string(stdout))
return fmt.Errorf("docker-compose up failed, std: %s, err: %v", stdout, err)
}
} else {
if stdout, err := compose.Operate(req.Path, req.Operation); err != nil {
return errors.New(string(stdout))
return fmt.Errorf("docker-compose %s failed, std: %s, err: %v", req.Operation, stdout, err)
}
}
global.LOG.Infof("docker-compose %s %s successful", req.Operation, req.Name)
return nil
}
@@ -257,11 +258,11 @@ func (u *ContainerService) ComposeUpdate(req dto.ComposeUpdate) error {
if cmd.CheckIllegal(req.Name, req.Path) {
return buserr.New("ErrCmdIllegal")
}
oldFile, err := os.ReadFile(req.Path)
oldFile, err := os.ReadFile(req.DetailPath)
if err != nil {
return fmt.Errorf("load file with path %s failed, %v", req.Path, err)
return fmt.Errorf("load file with path %s failed, %v", req.DetailPath, err)
}
file, err := os.OpenFile(req.Path, os.O_WRONLY|os.O_TRUNC, 0640)
file, err := os.OpenFile(req.DetailPath, os.O_WRONLY|os.O_TRUNC, 0640)
if err != nil {
return err
}
@@ -270,21 +271,73 @@ func (u *ContainerService) ComposeUpdate(req dto.ComposeUpdate) error {
_, _ = write.WriteString(req.Content)
write.Flush()
global.LOG.Infof("docker-compose.yml %s has been replaced, now start to docker-compose restart", req.Path)
if err := newComposeEnv(req.Path, req.Env); err != nil {
global.LOG.Infof("docker-compose.yml %s has been replaced, now start to docker-compose restart", req.DetailPath)
if err := newComposeEnv(req.DetailPath, req.Env); err != nil {
return err
}
if stdout, err := compose.Up(req.Path); err != nil {
global.LOG.Errorf("update failed when handle compose up, std: %s, err: %s, now try to recreate the old compose file", stdout, err)
if err := recreateCompose(string(oldFile), req.Path); err != nil {
return fmt.Errorf("update failed when handle compose up, err: %s, recreate failed: %v", string(stdout), err)
return fmt.Errorf("update failed and recreate old compose file also failed, err: %v", err)
}
return fmt.Errorf("update failed when handle compose up, err: %s", string(stdout))
return fmt.Errorf("update failed when handle compose up, std: %v, err: %s", stdout, err)
}
return nil
}
func (u *ContainerService) ComposeLogClean(req dto.ComposeLogClean) error {
client, err := docker.NewDockerClient()
if err != nil {
return err
}
defer client.Close()
options := container.ListOptions{All: true}
options.Filters = filters.NewArgs()
options.Filters.Add("label", composeProjectLabel)
list, err := client.ContainerList(context.Background(), options)
if err != nil {
return err
}
ctx := context.Background()
for _, item := range list {
if name, ok := item.Labels[composeProjectLabel]; ok {
if name != req.Name {
continue
}
containerItem, err := client.ContainerInspect(ctx, item.ID)
if err != nil {
return err
}
if err := client.ContainerStop(ctx, containerItem.ID, container.StopOptions{}); err != nil {
return err
}
file, err := os.OpenFile(containerItem.LogPath, os.O_RDWR|os.O_CREATE, constant.FilePerm)
if err != nil {
return err
}
defer file.Close()
if err = file.Truncate(0); err != nil {
return err
}
_, _ = file.Seek(0, 0)
files, _ := filepath.Glob(fmt.Sprintf("%s.*", containerItem.LogPath))
for _, file := range files {
_ = os.Remove(file)
}
}
}
return u.ComposeOperation(dto.ComposeOperation{
Name: req.Name,
Path: req.Path,
Operation: "restart",
})
}
func (u *ContainerService) loadPath(req *dto.ComposeCreate) error {
if req.From == "template" || req.From == "edit" {
dir := fmt.Sprintf("%s/docker/compose/%s", global.Dir.DataDir, req.Name)
@@ -309,11 +362,8 @@ func (u *ContainerService) loadPath(req *dto.ComposeCreate) error {
}
func removeContainerForCompose(composeName, composePath string) error {
if _, err := os.Stat(composePath); err == nil {
if stdout, err := compose.Operate(composePath, "down"); err != nil {
return errors.New(stdout)
}
return nil
if stdout, err := compose.Operate(composePath, "down"); err != nil {
return errors.New(stdout)
}
var options container.ListOptions
options.All = true
@@ -353,40 +403,31 @@ func recreateCompose(content, path string) error {
func loadEnv(list []dto.ComposeInfo) []dto.ComposeInfo {
for i := 0; i < len(list); i++ {
envFilePath := path.Join(path.Dir(list[i].Path), "1panel.env")
tmpPath := list[i].Path
if strings.Contains(list[i].Path, ",") {
tmpPath = strings.Split(list[i].Path, ",")[0]
}
envFilePath := path.Join(path.Dir(tmpPath), ".env")
file, err := os.ReadFile(envFilePath)
if err != nil {
continue
}
lines := strings.Split(string(file), "\n")
for _, line := range lines {
lineItem := strings.TrimSpace(line)
if len(lineItem) != 0 && !strings.HasPrefix(lineItem, "#") {
list[i].Env = append(list[i].Env, lineItem)
}
}
list[i].Env = string(file)
}
return list
}
func newComposeEnv(pathItem string, env []string) error {
if len(env) == 0 {
return nil
}
envFilePath := path.Join(path.Dir(pathItem), "1panel.env")
func newComposeEnv(pathItem string, env string) error {
envFilePath := path.Join(path.Dir(pathItem), ".env")
file, err := os.OpenFile(envFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, constant.FilePerm)
if err != nil {
global.LOG.Errorf("failed to create env file: %v", err)
return err
}
defer file.Close()
for _, env := range env {
envItem := strings.TrimSpace(env)
if _, err := file.WriteString(fmt.Sprintf("%s\n", envItem)); err != nil {
global.LOG.Errorf("failed to write env to file: %v", err)
return err
}
if _, err := file.WriteString(env); err != nil {
global.LOG.Errorf("failed to write env to file: %v", err)
return err
}
global.LOG.Infof("1panel.env file successfully created or updated with env variables in %s", envFilePath)
return nil
}
+3 -6
View File
@@ -117,10 +117,8 @@ func (u *ContainerService) CreateNetwork(req dto.NetworkCreate) error {
return err
}
defer client.Close()
var (
ipams []network.IPAMConfig
enableV6 bool
)
var ipams []network.IPAMConfig
if req.Ipv4 {
var itemIpam network.IPAMConfig
if len(req.AuxAddress) != 0 {
@@ -141,7 +139,6 @@ func (u *ContainerService) CreateNetwork(req dto.NetworkCreate) error {
ipams = append(ipams, itemIpam)
}
if req.Ipv6 {
enableV6 = true
var itemIpam network.IPAMConfig
if len(req.AuxAddress) != 0 {
itemIpam.AuxAddress = make(map[string]string)
@@ -162,7 +159,7 @@ func (u *ContainerService) CreateNetwork(req dto.NetworkCreate) error {
}
options := network.CreateOptions{
EnableIPv6: &enableV6,
EnableIPv6: &req.Ipv6,
Driver: req.Driver,
Options: stringsToMap(req.Options),
Labels: stringsToMap(req.Labels),
+2 -15
View File
@@ -5,7 +5,6 @@ import (
"sort"
"strings"
"time"
"unicode"
"github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/buserr"
@@ -20,6 +19,7 @@ func (u *ContainerService) PageVolume(req dto.SearchWithPage) (int64, interface{
if err != nil {
return 0, nil, err
}
defer client.Close()
list, err := client.VolumeList(context.TODO(), volume.ListOptions{})
if err != nil {
return 0, nil, err
@@ -57,7 +57,7 @@ func (u *ContainerService) PageVolume(req dto.SearchWithPage) (int64, interface{
var volume dto.Volume
volume.Driver = item.Driver
volume.Mountpoint = item.Mountpoint
volume.Name = simplifyVolumeName(item.Name)
volume.Name = item.Name
for key, val := range item.Labels {
volume.Labels = append(volume.Labels, dto.VolumeOption{Key: key, Value: val})
}
@@ -143,16 +143,3 @@ func (u *ContainerService) CreateVolume(req dto.VolumeCreate) error {
}
return nil
}
func simplifyVolumeName(name string) string {
if len(name) != 64 {
return name
}
for _, char := range name {
if !unicode.Is(unicode.ASCII_Hex_Digit, char) {
return name
}
}
return name[:12]
}
+14 -7
View File
@@ -108,6 +108,9 @@ func (u *CronjobService) LoadInfo(req dto.OperateByID) (*dto.CronjobOperate, err
if cronjob.Type == "snapshot" && len(cronjob.SnapshotRule) != 0 {
_ = json.Unmarshal([]byte(cronjob.SnapshotRule), &item.SnapshotRule)
}
if cronjob.Type == "cleanLog" {
_ = json.Unmarshal([]byte(cronjob.Config), &item.CleanLogConfig)
}
return &item, err
}
@@ -444,7 +447,7 @@ func (u *CronjobService) SearchRecords(search dto.SearchRecord) (int64, interfac
func (u *CronjobService) LoadNextHandle(specStr string) ([]string, error) {
spec := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)
now := time.Now()
var nexts [5]string
var next [5]string
if strings.HasPrefix(specStr, "@every ") {
duration := time.Minute
if strings.HasSuffix(specStr, "s") {
@@ -459,10 +462,10 @@ func (u *CronjobService) LoadNextHandle(specStr string) ([]string, error) {
}
for i := 0; i < 5; i++ {
nextTime := now.Add(time.Duration(durationItem) * duration)
nexts[i] = nextTime.Format(constant.DateTimeLayout)
next[i] = nextTime.Format(constant.DateTimeLayout)
now = nextTime
}
return nexts[:], nil
return next[:], nil
}
sched, err := spec.Parse(specStr)
if err != nil {
@@ -470,10 +473,10 @@ func (u *CronjobService) LoadNextHandle(specStr string) ([]string, error) {
}
for i := 0; i < 5; i++ {
nextTime := sched.Next(now)
nexts[i] = nextTime.Format(constant.DateTimeLayout)
next[i] = nextTime.Format(constant.DateTimeLayout)
now = nextTime
}
return nexts[:], nil
return next[:], nil
}
func (u *CronjobService) LoadRecordLog(req dto.OperateByID) string {
@@ -577,6 +580,10 @@ func (u *CronjobService) Create(req dto.CronjobOperate) error {
}
cronjob.Spec = spec
cronjob.EntryIDs = entryIDs
if req.Type == "cleanLog" {
config, _ := json.Marshal(req.CleanLogConfig)
cronjob.Config = string(config)
}
if err := cronjobRepo.Create(&cronjob); err != nil {
return err
}
@@ -626,8 +633,8 @@ func (u *CronjobService) HandleStop(id uint) error {
if len(record.TaskID) == 0 {
return nil
}
if cancle, ok := global.TaskCtxMap[record.TaskID]; ok {
cancle()
if cancel, ok := global.TaskCtxMap[record.TaskID]; ok {
cancel()
}
return nil
}
+14 -14
View File
@@ -13,6 +13,7 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/app/task"
"github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/i18n"
"github.com/1Panel-dev/1Panel/agent/app/dto"
@@ -21,7 +22,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/global"
"github.com/1Panel-dev/1Panel/agent/utils/common"
"github.com/1Panel-dev/1Panel/agent/utils/files"
"github.com/pkg/errors"
)
func (u *CronjobService) handleApp(cronjob model.Cronjob, startTime time.Time, taskItem *task.Task) error {
@@ -32,7 +32,7 @@ func (u *CronjobService) handleApp(cronjob model.Cronjob, startTime time.Time, t
}
accountMap := NewBackupClientMap(strings.Split(cronjob.SourceAccountIDs, ","))
if !accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].isOk {
return errors.New(i18n.GetMsgWithDetail("LoadBackupFailed", accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].message))
return buserr.New(i18n.GetMsgWithDetail("LoadBackupFailed", accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].message))
}
for _, app := range apps {
retry := 0
@@ -90,7 +90,7 @@ func (u *CronjobService) handleWebsite(cronjob model.Cronjob, startTime time.Tim
}
accountMap := NewBackupClientMap(strings.Split(cronjob.SourceAccountIDs, ","))
if !accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].isOk {
return errors.New(i18n.GetMsgWithDetail("LoadBackupFailed", accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].message))
return buserr.New(i18n.GetMsgWithDetail("LoadBackupFailed", accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].message))
}
for _, web := range webs {
retry := 0
@@ -149,7 +149,7 @@ func (u *CronjobService) handleDatabase(cronjob model.Cronjob, startTime time.Ti
}
accountMap := NewBackupClientMap(strings.Split(cronjob.SourceAccountIDs, ","))
if !accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].isOk {
return errors.New(i18n.GetMsgWithDetail("LoadBackupFailed", accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].message))
return buserr.New(i18n.GetMsgWithDetail("LoadBackupFailed", accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].message))
}
for _, dbInfo := range dbs {
retry := 0
@@ -167,7 +167,7 @@ func (u *CronjobService) handleDatabase(cronjob model.Cronjob, startTime time.Ti
backupDir := path.Join(global.Dir.LocalBackupDir, fmt.Sprintf("tmp/database/%s/%s/%s", dbInfo.DBType, record.Name, dbInfo.Name))
record.FileName = simplifiedFileName(fmt.Sprintf("db_%s_%s.sql.gz", dbInfo.Name, startTime.Format(constant.DateTimeSlimLayout)+common.RandStrAndNum(5)))
if cronjob.DBType == "mysql" || cronjob.DBType == "mariadb" || cronjob.DBType == "mysql-cluster" {
if err := doMysqlBackup(dbInfo, backupDir, record.FileName); err != nil {
if err := doMysqlBackup(dbInfo, backupDir, record.FileName, cronjob.Secret); err != nil {
if retry < int(cronjob.RetryTimes) || !cronjob.IgnoreErr {
retry++
return err
@@ -178,7 +178,7 @@ func (u *CronjobService) handleDatabase(cronjob model.Cronjob, startTime time.Ti
}
}
} else {
if err := doPostgresqlgBackup(dbInfo, backupDir, record.FileName); err != nil {
if err := doPostgresqlBackup(dbInfo, backupDir, record.FileName, cronjob.Secret, taskItem); err != nil {
if retry < int(cronjob.RetryTimes) || !cronjob.IgnoreErr {
retry++
return err
@@ -217,7 +217,7 @@ func (u *CronjobService) handleDatabase(cronjob model.Cronjob, startTime time.Ti
func (u *CronjobService) handleDirectory(cronjob model.Cronjob, startTime time.Time, taskItem *task.Task) error {
accountMap := NewBackupClientMap(strings.Split(cronjob.SourceAccountIDs, ","))
if !accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].isOk {
return errors.New(i18n.GetMsgWithDetail("LoadBackupFailed", accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].message))
return buserr.New(i18n.GetMsgWithDetail("LoadBackupFailed", accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].message))
}
taskItem.AddSubTaskWithOps(task.GetTaskName(cronjob.SourceDir, task.TaskBackup, task.TaskScopeCronjob), func(task *task.Task) error {
fileName := fmt.Sprintf("%s.tar.gz", startTime.Format(constant.DateTimeSlimLayout)+common.RandStrAndNum(2))
@@ -267,7 +267,7 @@ func (u *CronjobService) handleDirectory(cronjob model.Cronjob, startTime time.T
func (u *CronjobService) handleSystemLog(cronjob model.Cronjob, startTime time.Time, taskItem *task.Task) error {
accountMap := NewBackupClientMap(strings.Split(cronjob.SourceAccountIDs, ","))
if !accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].isOk {
return errors.New(i18n.GetMsgWithDetail("LoadBackupFailed", accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].message))
return buserr.New(i18n.GetMsgWithDetail("LoadBackupFailed", accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].message))
}
taskItem.AddSubTaskWithOps(task.GetTaskName(i18n.GetMsgByKey("SystemLog"), task.TaskBackup, task.TaskScopeCronjob), func(task *task.Task) error {
nameItem := startTime.Format(constant.DateTimeSlimLayout) + common.RandStrAndNum(5)
@@ -303,7 +303,7 @@ func (u *CronjobService) handleSystemLog(cronjob model.Cronjob, startTime time.T
func (u *CronjobService) handleSnapshot(cronjob model.Cronjob, jobRecord model.JobRecords, taskItem *task.Task) error {
accountMap := NewBackupClientMap(strings.Split(cronjob.SourceAccountIDs, ","))
if !accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].isOk {
return errors.New(i18n.GetMsgWithDetail("LoadBackupFailed", accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].message))
return buserr.New(i18n.GetMsgWithDetail("LoadBackupFailed", accountMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].message))
}
var record model.BackupRecord
record.Status = constant.StatusSuccess
@@ -440,10 +440,10 @@ func loadDbsForJob(cronjob model.Cronjob) []DatabaseHelper {
}
func loadWebsForJob(cronjob model.Cronjob) []model.Website {
var weblist []model.Website
var list []model.Website
if cronjob.Website == "all" {
weblist, _ = websiteRepo.List()
return weblist
list, _ = websiteRepo.List()
return list
}
websites := strings.Split(cronjob.Website, ",")
var idItems []uint
@@ -451,8 +451,8 @@ func loadWebsForJob(cronjob model.Cronjob) []model.Website {
itemID, _ := strconv.Atoi(websites[i])
idItems = append(idItems, uint(itemID))
}
weblist, _ = websiteRepo.GetBy(repo.WithByIDs(idItems))
return weblist
list, _ = websiteRepo.GetBy(repo.WithByIDs(idItems))
return list
}
func handleBackupLogs(taskItem *task.Task, targetDir, fileName string, secret string) error {
+146 -11
View File
@@ -1,16 +1,20 @@
package service
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path"
pathUtils "path"
"path/filepath"
"strings"
"time"
"github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/utils/alert_push"
"github.com/pkg/errors"
"github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/model"
@@ -60,7 +64,7 @@ func (u *CronjobService) HandleJob(cronjob *model.Cronjob) {
return
}
if err = u.loadTask(cronjob, &record, taskItem); err != nil {
global.LOG.Debugf("preper to handle cron job [%s] %s failed, err: %v", cronjob.Type, cronjob.Name, err)
global.LOG.Debugf("prepare to handle cron job [%s] %s failed, err: %v", cronjob.Type, cronjob.Name, err)
item, _ := taskRepo.GetFirst(taskRepo.WithByID(record.TaskID))
if len(item.ID) == 0 {
record.TaskID = ""
@@ -127,6 +131,10 @@ func (u *CronjobService) loadTask(cronjob *model.Cronjob, record *model.JobRecor
err = u.handleDirectory(*cronjob, record.StartTime, taskItem)
case "log":
err = u.handleSystemLog(*cronjob, record.StartTime, taskItem)
case "syncIpGroup":
u.handleSyncIpGroup(*cronjob, taskItem)
case "cleanLog":
u.handleCleanLog(*cronjob, taskItem)
}
return err
}
@@ -138,7 +146,7 @@ func (u *CronjobService) handleShell(cronjob model.Cronjob, taskItem *task.Task)
if len(cronjob.ContainerName) != 0 {
scriptItem := cronjob.Script
if cronjob.ScriptMode == "select" {
scriptItem = path.Join("/tmp", path.Base(cronjob.Script))
scriptItem = pathUtils.Join("/tmp", pathUtils.Base(cronjob.Script))
if err := cmdMgr.Run("docker", "cp", cronjob.Script, cronjob.ContainerName+":"+scriptItem); err != nil {
return err
}
@@ -186,10 +194,17 @@ func (u *CronjobService) handleShell(cronjob model.Cronjob, taskItem *task.Task)
}
func (u *CronjobService) handleCurl(cronjob model.Cronjob, taskItem *task.Task) {
taskItem.AddSubTaskWithOps(i18n.GetWithName("HandleShell", cronjob.Name), func(t *task.Task) error {
cmdMgr := cmd.NewCommandMgr(cmd.WithTask(*taskItem))
return cmdMgr.Run("curl", cronjob.URL)
}, nil, int(cronjob.RetryTimes), time.Duration(cronjob.Timeout)*time.Second)
urls := strings.Split(cronjob.URL, ",")
for _, url := range urls {
if len(strings.TrimSpace(url)) == 0 {
continue
}
taskItem.AddSubTaskWithOps(i18n.GetWithName("HandleCurl", url), func(t *task.Task) error {
taskItem.LogStart(i18n.GetWithName("HandleCurl", url))
cmdMgr := cmd.NewCommandMgr(cmd.WithTask(*taskItem))
return cmdMgr.Run("curl", url)
}, nil, int(cronjob.RetryTimes), time.Duration(cronjob.Timeout)*time.Second)
}
}
func (u *CronjobService) handleNtpSync(cronjob model.Cronjob, taskItem *task.Task) {
@@ -210,10 +225,124 @@ func (u *CronjobService) handleNtpSync(cronjob model.Cronjob, taskItem *task.Tas
}, nil, int(cronjob.RetryTimes), time.Duration(cronjob.Timeout)*time.Second)
}
func (u *CronjobService) handleCleanLog(cronjob model.Cronjob, taskItem *task.Task) {
taskItem.AddSubTaskWithOps(i18n.GetWithName("CleanLog", cronjob.Name), func(t *task.Task) error {
config := GetCleanLogConfig(cronjob)
for _, scope := range config.Scopes {
switch scope {
case "website":
websites, _ := websiteRepo.List()
for _, website := range websites {
curStr := i18n.GetWithName("CleanLogByName", website.PrimaryDomain)
t.LogStart(curStr)
accessLogPath := GetSitePath(website, SiteAccessLog)
if err := os.Truncate(accessLogPath, 0); err != nil {
t.LogFailedWithErr(curStr, err)
continue
}
errLogPath := GetSitePath(website, SiteErrorLog)
if err := os.Truncate(errLogPath, 0); err != nil {
t.LogFailedWithErr(curStr, err)
continue
}
t.LogSuccess(curStr)
}
appInstall, _ := getAppInstallByKey(constant.AppOpenresty)
if appInstall.ID > 0 {
curStr := i18n.GetWithName("CleanLogByName", "OpenResty")
t.LogStart(curStr)
accessLogPath := pathUtils.Join(appInstall.GetPath(), "log", "access.log")
if err := os.Truncate(accessLogPath, 0); err != nil {
t.LogFailedWithErr(curStr, err)
}
errLogPath := pathUtils.Join(appInstall.GetPath(), "log", "error.log")
if err := os.Truncate(errLogPath, 0); err != nil {
t.LogFailedWithErr(curStr, err)
}
t.LogSuccess(curStr)
}
}
}
return nil
}, nil, int(cronjob.RetryTimes), time.Duration(cronjob.Timeout)*time.Second)
}
func (u *CronjobService) handleSyncIpGroup(cronjob model.Cronjob, taskItem *task.Task) {
taskItem.AddSubTaskWithOps(i18n.GetWithName("SyncIpGroup", cronjob.Name), func(t *task.Task) error {
appInstall, err := getAppInstallByKey(constant.AppOpenresty)
if err != nil {
return err
}
ipGroupDir := pathUtils.Join(appInstall.GetPath(), "1pwaf", "data", "rules", "ip_group")
urlDir := pathUtils.Join(ipGroupDir, "ip_group_url")
_, err = os.Stat(urlDir)
if err != nil && os.IsNotExist(err) {
return buserr.New("WafIpGroupNotFound")
}
urlsFiles, err := os.ReadDir(urlDir)
if err != nil {
return err
}
for _, file := range urlsFiles {
if file.IsDir() || !strings.HasSuffix(file.Name(), "_url") {
continue
}
urlFilePath := filepath.Join(urlDir, file.Name())
urlContent, err := os.ReadFile(urlFilePath)
if err != nil {
continue
}
remoteURL := strings.TrimSpace(string(urlContent))
if remoteURL == "" {
continue
}
resp, err := http.Get(remoteURL)
if err != nil {
continue
}
ipGroupFile := strings.TrimSuffix(file.Name(), "_url")
ipGroupPath := filepath.Join(ipGroupDir, ipGroupFile)
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
taskItem.Logf("get remote ip group %s failed %s status code %d", ipGroupFile, remoteURL, resp.StatusCode)
continue
}
outFile, err := os.OpenFile(ipGroupPath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
if err != nil {
resp.Body.Close()
taskItem.Logf("sync %s failed %v", ipGroupFile, err)
continue
}
writer := bufio.NewWriter(outFile)
_, err = io.Copy(writer, resp.Body)
if err != nil {
outFile.Close()
resp.Body.Close()
taskItem.Logf("sync %s failed , write file failed %v", ipGroupFile, err)
continue
}
writer.Flush()
outFile.Close()
resp.Body.Close()
taskItem.LogSuccess(i18n.Get("TaskSync") + " " + ipGroupFile)
}
if err := opNginx(appInstall.ContainerName, constant.NginxReload); err != nil {
return err
}
return nil
}, nil, int(cronjob.RetryTimes), time.Duration(cronjob.Timeout)*time.Second)
}
func (u *CronjobService) handleCutWebsiteLog(cronjob *model.Cronjob, startTime time.Time, taskItem *task.Task) error {
clientMap := NewBackupClientMap([]string{fmt.Sprintf("%v", cronjob.DownloadAccountID)})
if !clientMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].isOk {
return errors.New(i18n.GetMsgWithDetail("LoadBackupFailed", clientMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].message))
return buserr.New(i18n.GetMsgWithDetail("LoadBackupFailed", clientMap[fmt.Sprintf("%d", cronjob.DownloadAccountID)].message))
}
taskItem.AddSubTaskWithOps(i18n.GetWithName("CutWebsiteLog", cronjob.Name), func(t *task.Task) error {
websites := loadWebsForJob(*cronjob)
@@ -343,9 +472,9 @@ func (u *CronjobService) removeExpiredLog(cronjob model.Cronjob) {
_ = os.Remove(file)
}
}
_ = cronjobRepo.DeleteRecord(repo.WithByID(uint(records[i].ID)))
_ = cronjobRepo.DeleteRecord(repo.WithByID(records[i].ID))
_ = taskRepo.Delete(taskRepo.WithByID(records[i].TaskID))
_ = os.Remove(path.Join(global.CONF.Base.InstallDir, "1panel/log/task/Cronjob", records[i].TaskID+".log"))
_ = os.Remove(pathUtils.Join(global.CONF.Base.InstallDir, "1panel/log/task/Cronjob", records[i].TaskID+".log"))
}
}
@@ -362,3 +491,9 @@ func handleCronJobAlert(cronjob *model.Cronjob) {
}
_ = alert_push.PushAlert(pushAlert)
}
func GetCleanLogConfig(cronJob model.Cronjob) dto.CleanLogConfig {
config := &dto.CleanLogConfig{}
_ = json.Unmarshal([]byte(cronJob.Config), config)
return *config
}
+110 -73
View File
@@ -1,6 +1,7 @@
package service
import (
"cmp"
"context"
"encoding/json"
"fmt"
@@ -21,11 +22,11 @@ import (
"github.com/1Panel-dev/1Panel/agent/utils/ai_tools/xpu"
"github.com/1Panel-dev/1Panel/agent/utils/cmd"
"github.com/1Panel-dev/1Panel/agent/utils/common"
"github.com/1Panel-dev/1Panel/agent/utils/controller"
"github.com/1Panel-dev/1Panel/agent/utils/copier"
"github.com/1Panel-dev/1Panel/agent/utils/psutil"
"github.com/gin-gonic/gin"
"github.com/shirou/gopsutil/v4/cpu"
"github.com/shirou/gopsutil/v4/disk"
"github.com/shirou/gopsutil/v4/host"
"github.com/shirou/gopsutil/v4/load"
"github.com/shirou/gopsutil/v4/mem"
"github.com/shirou/gopsutil/v4/net"
@@ -38,6 +39,8 @@ type IDashboardService interface {
LoadBaseInfo(ioOption string, netOption string) (*dto.DashboardBase, error)
LoadCurrentInfoForNode() *dto.NodeCurrent
LoadCurrentInfo(ioOption string, netOption string) *dto.DashboardCurrent
LoadTopCPU() []dto.Process
LoadTopMem() []dto.Process
LoadQuickOptions() []dto.QuickJump
ChangeQuick(req dto.ChangeQuicks) error
@@ -53,28 +56,30 @@ func NewIDashboardService() IDashboardService {
}
func (u *DashboardService) Restart(operation string) error {
if operation != "1panel" && operation != "system" && operation != "1panel-agent" {
switch operation {
case "system":
{
go func() {
if err := cmd.RunDefaultBashCf("%s reboot", cmd.SudoHandleCmd()); err != nil {
global.LOG.Errorf("handle reboot failed, %v", err)
}
}()
return nil
}
case "1panel-agent":
controller.RestartPanel(false, true, false)
return nil
case "1panel":
controller.RestartPanel(true, true, false)
return nil
default:
return fmt.Errorf("handle restart operation %s failed, err: nonsupport such operation", operation)
}
itemCmd := fmt.Sprintf("%s systemctl restart 1panel-agent.service && %s systemctl restart 1panel-core.service", cmd.SudoHandleCmd(), cmd.SudoHandleCmd())
if operation == "system" {
itemCmd = fmt.Sprintf("%s reboot", cmd.SudoHandleCmd())
}
if operation == "1panel-agent" {
itemCmd = fmt.Sprintf("%s systemctl restart 1panel-agent.service", cmd.SudoHandleCmd())
}
go func() {
stdout, err := cmd.RunDefaultWithStdoutBashC(itemCmd)
if err != nil {
global.LOG.Errorf("handle %s failed, err: %v", itemCmd, stdout)
}
}()
return nil
}
func (u *DashboardService) LoadOsInfo() (*dto.OsInfo, error) {
var baseInfo dto.OsInfo
hostInfo, err := host.Info()
hostInfo, err := psutil.HOST.GetHostInfo(false)
if err != nil {
return nil, err
}
@@ -83,8 +88,9 @@ func (u *DashboardService) LoadOsInfo() (*dto.OsInfo, error) {
baseInfo.PlatformFamily = hostInfo.PlatformFamily
baseInfo.KernelArch = hostInfo.KernelArch
baseInfo.KernelVersion = hostInfo.KernelVersion
baseInfo.PrettyDistro = psutil.HOST.GetDistro()
diskInfo, err := disk.Usage(global.Dir.BaseDir)
diskInfo, err := psutil.DISK.GetUsage(global.Dir.BaseDir, false)
if err == nil {
baseInfo.DiskSize = int64(diskInfo.Free)
}
@@ -101,12 +107,17 @@ func (u *DashboardService) LoadOsInfo() (*dto.OsInfo, error) {
func (u *DashboardService) LoadCurrentInfoForNode() *dto.NodeCurrent {
var currentInfo dto.NodeCurrent
currentInfo.CPUTotal, _ = cpu.Counts(true)
totalPercent, _ := cpu.Percent(100*time.Millisecond, false)
if len(totalPercent) == 1 {
currentInfo.CPUUsedPercent = totalPercent[0]
currentInfo.CPUUsed = currentInfo.CPUUsedPercent * 0.01 * float64(currentInfo.CPUTotal)
currentInfo.CPUTotal, _ = psutil.CPUInfo.GetLogicalCores(false)
cpuUsedPercent, perCore, cpuDetailedPercent := psutil.CPU.GetCPUUsage()
if len(perCore) == 0 {
currentInfo.CPUTotal = psutil.CPU.NumCPU()
} else {
currentInfo.CPUTotal = len(perCore)
}
currentInfo.CPUUsedPercent = cpuUsedPercent
currentInfo.CPUUsed = cpuUsedPercent * 0.01 * float64(currentInfo.CPUTotal)
currentInfo.CPUDetailedPercent = cpuDetailedPercent
loadInfo, _ := load.Avg()
currentInfo.Load1 = loadInfo.Load1
@@ -117,7 +128,7 @@ func (u *DashboardService) LoadCurrentInfoForNode() *dto.NodeCurrent {
memoryInfo, _ := mem.VirtualMemory()
currentInfo.MemoryTotal = memoryInfo.Total
currentInfo.MemoryAvailable = memoryInfo.Available
currentInfo.MemoryUsed = memoryInfo.Used + memoryInfo.Shared
currentInfo.MemoryUsed = memoryInfo.Used
currentInfo.MemoryUsedPercent = memoryInfo.UsedPercent
swapInfo, _ := mem.SwapMemory()
@@ -131,38 +142,39 @@ func (u *DashboardService) LoadCurrentInfoForNode() *dto.NodeCurrent {
func (u *DashboardService) LoadBaseInfo(ioOption string, netOption string) (*dto.DashboardBase, error) {
var baseInfo dto.DashboardBase
hostInfo, err := host.Info()
hostInfo, err := psutil.HOST.GetHostInfo(false)
if err != nil {
return nil, err
}
baseInfo.Hostname = hostInfo.Hostname
baseInfo.OS = hostInfo.OS
baseInfo.Platform = hostInfo.Platform
baseInfo.PlatformFamily = hostInfo.PlatformFamily
baseInfo.PlatformVersion = hostInfo.PlatformVersion
baseInfo.KernelArch = hostInfo.KernelArch
baseInfo.KernelVersion = hostInfo.KernelVersion
ss, _ := json.Marshal(hostInfo)
baseInfo.VirtualizationSystem = string(ss)
baseInfo.IpV4Addr = loadOutboundIP()
httpProxy := os.Getenv("http_proxy")
if httpProxy == "" {
httpProxy = os.Getenv("HTTP_PROXY")
baseInfo = dto.DashboardBase{
Hostname: hostInfo.Hostname,
OS: hostInfo.OS,
Platform: hostInfo.Platform,
PlatformFamily: hostInfo.PlatformFamily,
PlatformVersion: hostInfo.PlatformVersion,
PrettyDistro: psutil.HOST.GetDistro(),
KernelArch: hostInfo.KernelArch,
KernelVersion: hostInfo.KernelVersion,
VirtualizationSystem: string(ss),
IpV4Addr: loadOutboundIP(),
SystemProxy: "noProxy",
}
if httpProxy != "" {
baseInfo.SystemProxy = httpProxy
if proxy := cmp.Or(os.Getenv("http_proxy"), os.Getenv("HTTP_PROXY")); proxy != "" {
baseInfo.SystemProxy = proxy
}
baseInfo.SystemProxy = "noProxy"
loadQuickJump(&baseInfo)
cpuInfo, err := cpu.Info()
if err == nil {
cpuInfo, err := psutil.CPUInfo.GetCPUInfo(false)
if err == nil && len(cpuInfo) > 0 {
baseInfo.CPUModelName = cpuInfo[0].ModelName
}
baseInfo.CPUCores, _ = cpu.Counts(false)
baseInfo.CPULogicalCores, _ = cpu.Counts(true)
baseInfo.CPUCores, _ = psutil.CPUInfo.GetPhysicalCores(false)
baseInfo.CPULogicalCores, _ = psutil.CPUInfo.GetLogicalCores(false)
baseInfo.CPUMhz = cpuInfo[0].Mhz
baseInfo.CurrentInfo = *u.LoadCurrentInfo(ioOption, netOption)
return &baseInfo, nil
@@ -170,18 +182,22 @@ func (u *DashboardService) LoadBaseInfo(ioOption string, netOption string) (*dto
func (u *DashboardService) LoadCurrentInfo(ioOption string, netOption string) *dto.DashboardCurrent {
var currentInfo dto.DashboardCurrent
hostInfo, _ := host.Info()
hostInfo, _ := psutil.HOST.GetHostInfo(false)
currentInfo.Uptime = hostInfo.Uptime
currentInfo.TimeSinceUptime = time.Now().Add(-time.Duration(hostInfo.Uptime) * time.Second).Format(constant.DateTimeLayout)
currentInfo.TimeSinceUptime = time.Unix(int64(hostInfo.BootTime), 0).Format(constant.DateTimeLayout)
currentInfo.Procs = hostInfo.Procs
currentInfo.CPUTotal, _ = psutil.CPUInfo.GetLogicalCores(false)
currentInfo.CPUTotal, _ = cpu.Counts(true)
totalPercent, _ := cpu.Percent(100*time.Millisecond, false)
if len(totalPercent) == 1 {
currentInfo.CPUUsedPercent = totalPercent[0]
currentInfo.CPUUsed = currentInfo.CPUUsedPercent * 0.01 * float64(currentInfo.CPUTotal)
cpuUsedPercent, perCore, cpuDetailedPercent := psutil.CPU.GetCPUUsage()
if len(perCore) == 0 {
currentInfo.CPUTotal = psutil.CPU.NumCPU()
} else {
currentInfo.CPUTotal = len(perCore)
}
currentInfo.CPUPercent, _ = cpu.Percent(100*time.Millisecond, true)
currentInfo.CPUPercent = perCore
currentInfo.CPUUsedPercent = cpuUsedPercent
currentInfo.CPUUsed = cpuUsedPercent * 0.01 * float64(currentInfo.CPUTotal)
currentInfo.CPUDetailedPercent = cpuDetailedPercent
loadInfo, _ := load.Avg()
currentInfo.Load1 = loadInfo.Load1
@@ -191,7 +207,7 @@ func (u *DashboardService) LoadCurrentInfo(ioOption string, netOption string) *d
memoryInfo, _ := mem.VirtualMemory()
currentInfo.MemoryTotal = memoryInfo.Total
currentInfo.MemoryUsed = memoryInfo.Used + memoryInfo.Shared
currentInfo.MemoryUsed = memoryInfo.Used
currentInfo.MemoryFree = memoryInfo.Free
currentInfo.MemoryCache = memoryInfo.Cached + memoryInfo.Buffers
currentInfo.MemoryShard = memoryInfo.Shared
@@ -240,6 +256,7 @@ func (u *DashboardService) LoadCurrentInfo(ioOption string, netOption string) *d
if state.Name == netOption {
currentInfo.NetBytesSent = state.BytesSent
currentInfo.NetBytesRecv = state.BytesRecv
break
}
}
}
@@ -248,6 +265,14 @@ func (u *DashboardService) LoadCurrentInfo(ioOption string, netOption string) *d
return &currentInfo
}
func (u *DashboardService) LoadTopCPU() []dto.Process {
return loadTopCPU()
}
func (u *DashboardService) LoadTopMem() []dto.Process {
return loadTopMem()
}
func (u *DashboardService) LoadAppLauncher(ctx *gin.Context) ([]dto.AppLauncher, error) {
var data []dto.AppLauncher
appInstalls, err := appInstallRepo.ListBy(context.Background())
@@ -260,7 +285,7 @@ func (u *DashboardService) LoadAppLauncher(ctx *gin.Context) ([]dto.AppLauncher,
}
showList, err := launcherRepo.ListName()
defaultList, err := appRepo.GetTopRecomment()
defaultList, err := appRepo.GetTopRecommend()
if err != nil {
return data, nil
}
@@ -401,10 +426,11 @@ type diskInfo struct {
func loadDiskInfo() []dto.DiskInfo {
var datas []dto.DiskInfo
cmdMgr := cmd.NewCommandMgr(cmd.WithTimeout(2 * time.Second))
stdout, err := cmdMgr.RunWithStdoutBashC("timeout 2 df -hT -P | awk 'NR>1 && !/tmpfs|snap\\/core|udev/ {print}'")
format := `awk 'NR>1 && !/tmpfs|snap\/core|udev/ {printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\n", $1, $2, $3, $4, $5, $6, $7}'`
stdout, err := cmdMgr.RunWithStdout("bash", "-c", `timeout 2 df -hT -P | `+format)
if err != nil {
cmdMgr2 := cmd.NewCommandMgr(cmd.WithTimeout(1 * time.Second))
stdout, err = cmdMgr2.RunWithStdoutBashC("timeout 1 df -lhT -P | awk 'NR>1 && !/tmpfs|snap\\/core|udev/ {print}'")
stdout, err = cmdMgr2.RunWithStdout("bash", "-c", `timeout 1 df -lhT -P | `+format)
if err != nil {
return datas
}
@@ -414,7 +440,7 @@ func loadDiskInfo() []dto.DiskInfo {
var mounts []diskInfo
var excludes = []string{"/mnt/cdrom", "/boot", "/boot/efi", "/dev", "/dev/shm", "/run/lock", "/run", "/run/shm", "/run/user"}
for _, line := range lines {
fields := strings.Fields(line)
fields := strings.Split(line, "\t")
if len(fields) < 7 {
continue
}
@@ -448,41 +474,52 @@ func loadDiskInfo() []dto.DiskInfo {
)
wg.Add(len(mounts))
for i := 0; i < len(mounts); i++ {
go func(timeoutCh <-chan time.Time, mount diskInfo) {
go func(mount diskInfo) {
defer wg.Done()
var itemData dto.DiskInfo
itemData.Path = mount.Mount
itemData.Type = mount.Type
itemData.Device = mount.Device
type diskResult struct {
state *disk.UsageStat
err error
}
resultCh := make(chan diskResult, 1)
go func() {
state, err := psutil.DISK.GetUsage(mount.Mount, false)
resultCh <- diskResult{state: state, err: err}
}()
select {
case <-timeoutCh:
case <-time.After(5 * time.Second):
mu.Lock()
datas = append(datas, itemData)
mu.Unlock()
global.LOG.Errorf("load disk info from %s failed, err: timeout", mount.Mount)
default:
state, err := disk.Usage(mount.Mount)
if err != nil {
case result := <-resultCh:
if result.err != nil {
mu.Lock()
datas = append(datas, itemData)
mu.Unlock()
global.LOG.Errorf("load disk info from %s failed, err: %v", mount.Mount, err)
global.LOG.Errorf("load disk info from %s failed, err: %v", mount.Mount, result.err)
return
}
itemData.Total = state.Total
itemData.Free = state.Free
itemData.Used = state.Used
itemData.UsedPercent = state.UsedPercent
itemData.InodesTotal = state.InodesTotal
itemData.InodesUsed = state.InodesUsed
itemData.InodesFree = state.InodesFree
itemData.InodesUsedPercent = state.InodesUsedPercent
itemData.Total = result.state.Total
itemData.Free = result.state.Free
itemData.Used = result.state.Used
itemData.UsedPercent = result.state.UsedPercent
itemData.InodesTotal = result.state.InodesTotal
itemData.InodesUsed = result.state.InodesUsed
itemData.InodesFree = result.state.InodesFree
itemData.InodesUsedPercent = result.state.InodesUsedPercent
mu.Lock()
datas = append(datas, itemData)
mu.Unlock()
}
}(time.After(5*time.Second), mounts[i])
}(mounts[i])
}
wg.Wait()
+31 -25
View File
@@ -119,27 +119,27 @@ func (u *DatabaseService) CheckDatabase(req dto.DatabaseCreate) bool {
if req.Timeout == 0 {
req.Timeout = 30
}
var err error
switch req.Type {
case constant.AppPostgresql:
_, err := postgresql.NewPostgresqlClient(pgclient.DBInfo{
From: "remote",
Address: req.Address,
Port: req.Port,
Username: req.Username,
Password: req.Password,
Timeout: req.Timeout,
_, err = postgresql.NewPostgresqlClient(pgclient.DBInfo{
From: "remote",
Address: req.Address,
Port: req.Port,
InitialDB: req.InitialDB,
Username: req.Username,
Password: req.Password,
Timeout: req.Timeout,
})
return err == nil
case constant.AppRedis:
_, err := redisclient.NewRedisClient(redisclient.DBInfo{
_, err = redisclient.NewRedisClient(redisclient.DBInfo{
Address: req.Address,
Port: req.Port,
Password: req.Password,
Timeout: req.Timeout,
})
return err == nil
case "mysql", "mariadb":
_, err := mysql.NewMysqlClient(client.DBInfo{
_, err = mysql.NewMysqlClient(client.DBInfo{
From: "remote",
Address: req.Address,
Port: req.Port,
@@ -153,10 +153,13 @@ func (u *DatabaseService) CheckDatabase(req dto.DatabaseCreate) bool {
SkipVerify: req.SkipVerify,
Timeout: req.Timeout,
})
return err == nil
}
if err != nil {
global.LOG.Errorf("check database connection failed, err: %v", err)
return false
}
return false
return true
}
func (u *DatabaseService) Create(req dto.DatabaseCreate) error {
@@ -173,12 +176,13 @@ func (u *DatabaseService) Create(req dto.DatabaseCreate) error {
switch req.Type {
case constant.AppPostgresql:
if _, err := postgresql.NewPostgresqlClient(pgclient.DBInfo{
From: "remote",
Address: req.Address,
Port: req.Port,
Username: req.Username,
Password: req.Password,
Timeout: req.Timeout,
From: "remote",
Address: req.Address,
Port: req.Port,
InitialDB: req.InitialDB,
Username: req.Username,
Password: req.Password,
Timeout: req.Timeout,
}); err != nil {
return err
}
@@ -274,12 +278,13 @@ func (u *DatabaseService) Update(req dto.DatabaseUpdate) error {
switch req.Type {
case constant.AppPostgresql:
if _, err := postgresql.NewPostgresqlClient(pgclient.DBInfo{
From: "remote",
Address: req.Address,
Port: req.Port,
Username: req.Username,
Password: req.Password,
Timeout: req.Timeout,
From: "remote",
Address: req.Address,
Port: req.Port,
InitialDB: req.InitialDB,
Username: req.Username,
Password: req.Password,
Timeout: req.Timeout,
}); err != nil {
return err
}
@@ -325,6 +330,7 @@ func (u *DatabaseService) Update(req dto.DatabaseUpdate) error {
upMap["port"] = req.Port
upMap["username"] = req.Username
upMap["password"] = pass
upMap["initial_db"] = req.InitialDB
upMap["timeout"] = req.Timeout
upMap["description"] = req.Description
upMap["ssl"] = req.SSL
+15 -1
View File
@@ -5,8 +5,10 @@ import (
"fmt"
"os"
"path"
"strings"
"github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/global"
@@ -51,7 +53,14 @@ func (u *DBCommonService) LoadDatabaseFile(req dto.OperationWithNameAndType) (st
case "mariadb-conf":
filePath = path.Join(global.Dir.DataDir, fmt.Sprintf("apps/mariadb/%s/conf/my.cnf", req.Name))
case "postgresql-conf":
database, err := databaseRepo.Get(repo.WithByName(req.Name))
if err != nil {
return "", err
}
filePath = path.Join(global.Dir.DataDir, fmt.Sprintf("apps/postgresql/%s/data/postgresql.conf", req.Name))
if strings.HasPrefix(database.Version, "18.") {
filePath = path.Join(global.Dir.DataDir, fmt.Sprintf("apps/postgresql/%s/data/18/docker/postgresql.conf", req.Name))
}
case "redis-conf":
filePath = path.Join(global.Dir.DataDir, fmt.Sprintf("apps/redis/%s/conf/redis.conf", req.Name))
case "redis-cluster-conf":
@@ -76,8 +85,13 @@ func (u *DBCommonService) UpdateConfByFile(req dto.DBConfUpdateByFile) error {
switch req.Type {
case constant.AppMariaDB, constant.AppMysql, constant.AppMysqlCluster:
path = fmt.Sprintf("%s/%s/%s/conf/my.cnf", global.Dir.AppInstallDir, req.Type, app.Name)
case constant.AppPostgresql, constant.AppPostgresqlCluster:
case constant.AppPostgresqlCluster:
path = fmt.Sprintf("%s/%s/%s/data/postgresql.conf", global.Dir.AppInstallDir, req.Type, app.Name)
case constant.AppPostgresql:
path = fmt.Sprintf("%s/%s/%s/data/postgresql.conf", global.Dir.AppInstallDir, req.Type, app.Name)
if strings.HasPrefix(app.Version, "18.") {
path = fmt.Sprintf("%s/%s/%s/data/18/docker/postgresql.conf", global.Dir.AppInstallDir, req.Type, app.Name)
}
case constant.AppRedis, constant.AppRedisCluster:
path = fmt.Sprintf("%s/%s/%s/conf/redis.conf", global.Dir.AppInstallDir, req.Type, app.Name)
}
+19 -4
View File
@@ -7,7 +7,6 @@ import (
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
@@ -25,6 +24,7 @@ import (
"github.com/1Panel-dev/1Panel/agent/utils/encrypt"
"github.com/1Panel-dev/1Panel/agent/utils/mysql"
"github.com/1Panel-dev/1Panel/agent/utils/mysql/client"
"github.com/1Panel-dev/1Panel/agent/utils/re"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
@@ -45,6 +45,7 @@ type IMysqlService interface {
DeleteCheck(req dto.MysqlDBDeleteCheck) ([]dto.DBResource, error)
Delete(ctx context.Context, req dto.MysqlDBDelete) error
LoadFormatOption(req dto.OperationWithName) []dto.MysqlFormatCollationOption
LoadStatus(req dto.OperationWithNameAndType) (*dto.MysqlStatus, error)
LoadVariables(req dto.OperationWithNameAndType) (*dto.MysqlVariables, error)
LoadRemoteAccess(req dto.OperationWithNameAndType) (bool, error)
@@ -99,7 +100,7 @@ func (u *MysqlService) ListDBOption() ([]dto.MysqlOption, error) {
}
func (u *MysqlService) Create(ctx context.Context, req dto.MysqlDBCreate) (*model.DatabaseMysql, error) {
if cmd.CheckIllegal(req.Name, req.Username, req.Password, req.Format, req.Permission) {
if cmd.CheckIllegal(req.Name, req.Username, req.Password, req.Format, req.Collation, req.Permission) {
return nil, buserr.New("ErrCmdIllegal")
}
@@ -114,7 +115,7 @@ func (u *MysqlService) Create(ctx context.Context, req dto.MysqlDBCreate) (*mode
}
if req.From == "local" && req.Username == "root" {
return nil, errors.New("Cannot set root as user name")
return nil, errors.New("cannot set root as user name")
}
cli, version, err := LoadMysqlClientByFrom(req.Database)
@@ -126,6 +127,7 @@ func (u *MysqlService) Create(ctx context.Context, req dto.MysqlDBCreate) (*mode
if err := cli.Create(client.CreateInfo{
Name: req.Name,
Format: req.Format,
Collation: req.Collation,
Username: req.Username,
Password: req.Password,
Permission: req.Permission,
@@ -584,6 +586,19 @@ func (u *MysqlService) LoadStatus(req dto.OperationWithNameAndType) (*dto.MysqlS
return &info, nil
}
func (u *MysqlService) LoadFormatOption(req dto.OperationWithName) []dto.MysqlFormatCollationOption {
defaultList := []dto.MysqlFormatCollationOption{{Format: "utf8mb4"}, {Format: "utf8mb3"}, {Format: "gbk"}, {Format: "big5"}}
client, _, err := LoadMysqlClientByFrom(req.Name)
if err != nil {
return defaultList
}
options, err := client.LoadFormatCollation(3)
if err != nil {
return defaultList
}
return options
}
func executeSqlForMaps(containerName, dbType, password, command string) (map[string]string, error) {
if dbType == "mysql-cluster" {
dbType = "mysql"
@@ -623,7 +638,7 @@ func updateMyCnf(oldFiles []string, group string, param string, value interface{
isOn := false
hasGroup := false
hasKey := false
regItem, _ := regexp.Compile(`\[*\]`)
regItem := re.GetRegex(re.MysqlGroupPattern)
var newFiles []string
i := 0
for _, line := range oldFiles {

Some files were not shown because too many files have changed in this diff Show More