节点在线、应用在线、配置在线使用令牌查询
大石头 authored at 2021-12-16 19:49:30
9.65 KiB
Stardust
using System.ComponentModel;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using NewLife;
using NewLife.Cube;
using NewLife.Cube.Extensions;
using NewLife.Cube.ViewModels;
using NewLife.Log;
using NewLife.Web;
using Stardust.Data.Deployment;
using Stardust.Storages;
using Stardust.Web.Services;
using Stardust.Data.Platform;
using XCode.Membership;
using Attachment = NewLife.Cube.Entity.Attachment;

namespace Stardust.Web.Areas.Deployment.Controllers;

/// <summary>部署版本。每个部署集下的构建产物版本</summary>
[Menu(80, false)]
[DeploymentArea]
public class AppDeployVersionController : DeploymentEntityController<AppDeployVersion>
{
    static AppDeployVersionController()
    {
        ListFields.RemoveField("Hash", "CommitId", "CommitLog");
        ListFields.RemoveCreateField();
        ListFields.RemoveRemarkField();

        AddFormFields.RemoveCreateField();
        AddFormFields.RemoveField("Hash");
                ListFields.TraceUrl();

        LogOnChange = true;

        {
            var df = ListFields.GetField("DeployName") as ListField;
            df.Url = "/Deployment/AppDeploy?deployId={DeployId}";
        }
        {
            var df = ListFields.AddListField("UseVersion", null, "Enable");
            df.Header = "使用版本";
            df.DisplayName = "使用版本";
            df.Title = "应用部署集使用该版本";
            df.Url = "/Deployment/AppDeployVersion/UseVersion?Id={Id}";
            df.DataAction = "action";
        }
    }

    private readonly DeployService _deployService;
    private readonly IFileStorage _fileStorage;

    public AppDeployVersionController(DeployService deployService, IFileStorage fileStorage)
    {
        _deployService = deployService;
        _fileStorage = fileStorage;
    }

    /// <summary>高级搜索。按条件分页查询</summary>
    /// <param name="p">分页参数</param>
    /// <returns>实体列表</returns>
    protected override IEnumerable<AppDeployVersion> Search(Pager p)
    {
        var id = p["id"].ToInt(-1);
        if (id > 0)
        {
            var entity = ProjectScopeRules.FilterVisible(AppDeployVersion.FindByKey(id));
            if (entity != null) return [entity];
        }

        var deployId = p["deployId"].ToInt(-1);
        var start = p["dtStart"].ToDateTime();
        var end = p["dtEnd"].ToDateTime();

        PageSetting.EnableAdd = deployId > 0;
        PageSetting.EnableNavbar = false;

        return AppDeployVersion.Search(deployId, null, null, start, end, p["Q"], p);
    }

    /// <summary>上传新版本。multipart 提交 deployId+file(可选 remark),自动生成版本号并保存文件</summary>
    /// <remarks>
    /// 行为对齐 MVC 上传:包名须匹配部署集 PackageName;版本号自动取 yyyyMMdd-HHmmss;
    /// 文件保存为 cube 附件并回写 Hash/Size/Url;部署集开启自动发布时上传即发布。
    /// </remarks>
    /// <param name="deployId">部署集</param>
    /// <param name="file">应用包文件</param>
    /// <param name="remark">备注,可选</param>
    /// <returns>新版本信息</returns>
    [DisplayName("上传新版本")]
    [EntityAuthorize(PermissionFlags.Update)]
    public async Task<ActionResult> Upload([FromForm] Int32 deployId, IFormFile file, [FromForm] String remark = null)
    {
        if (deployId <= 0) throw new ArgumentNullException(nameof(deployId), L.T("Deployment is required."));
        if (file == null || file.Length <= 0) throw new ArgumentNullException(nameof(file), L.T("No file was uploaded."));

        var deploy = ProjectScopeRules.FilterVisible(AppDeploy.FindById(deployId));
        if (deploy == null) throw new InvalidOperationException(L.T("Deployment [{0}] does not exist.", deployId));

        // 包名校验,与表单上传一致:避免误传其它应用包
        var name = Path.GetFileName(file.FileName);
        if (!name.IsNullOrEmpty() && !deploy.PackageName.IsNullOrEmpty() && !deploy.PackageName.IsMatch(name, StringComparison.OrdinalIgnoreCase))
            throw new InvalidOperationException(L.T("File name [{0}] does not match the application package name [{1}].", name, deploy.PackageName));

        var entity = new AppDeployVersion
        {
            DeployId = deployId,
            Version = DateTime.Now.ToString("yyyyMMdd-HHmmss"),
            Enable = true,
            Remark = remark,
        };

        using (var stream = file.OpenReadStream())
            AppPackageHelper.ApplyStarPackage(entity, stream);

        // 与 MVC 表单上传一致:Valid(post) 显式写入当前追踪 ID(除实体 TraceInterceptor 兜底外再保证一次语义一致)
        entity.TraceId = DefaultSpan.Current?.TraceId;

        // 复刻标准新增流程:OnInsert(含部署集统计 Fix)后保存文件(override 已回写 Hash/Size/Url 并处理自动发布)
        OnInsert(entity);
        try
        {
            await SaveFile(entity, file, null, null);
        }
        catch
        {
            // 文件保存失败时回滚版本行,避免留下无包记录
            entity.Delete();
            throw;
        }

        return Json(0, null, new { id = entity.Id, version = entity.Version, size = entity.Size, hash = entity.Hash, url = entity.Url });
    }

    protected override Boolean Valid(AppDeployVersion entity, DataObjectMethodType type, Boolean post)
    {
        if (type == DataObjectMethodType.Delete || type == DataObjectMethodType.Update) return base.Valid(entity, type, post);
        if (!post && type == DataObjectMethodType.Insert)
        {
            entity.Enable = true;
            entity.Version = DateTime.Now.ToString("yyyyMMdd-HHmmss");
        }

        if (post)
        {
            // 根据包名去查应用发布集,如果是不小心上传了其它包,则给出提醒
            foreach (var file in Request.Form.Files)
            {
                var deploy = entity.Deploy;
                var name = Path.GetFileName(file.FileName);
                if (!name.IsNullOrEmpty() && deploy != null)
                {
                    if (!deploy.PackageName.IsNullOrEmpty() && !deploy.PackageName.IsMatch(name, StringComparison.OrdinalIgnoreCase))
                        throw new InvalidOperationException(L.T("File name [{0}] does not match the application package name [{1}].", name, deploy.PackageName));

                    //var deploy = AppDeploy.FindByName(name);
                    //if (deploy != null && deploy.Id != entity.AppId)
                    //    throw new InvalidOperationException($"文件名[{name}]对应另一个应用[{deploy}],请确保是否上传错误!");
                }
            }

            var zip = Request.Form.Files.FirstOrDefault(e => e.FileName.EndsWithIgnoreCase(".zip"));
            if (zip != null)
            {
                using var stream = zip.OpenReadStream();
                AppPackageHelper.ApplyStarPackage(entity, stream);
            }

            entity.TraceId = DefaultSpan.Current?.TraceId;
        }

        return base.Valid(entity, type, post);
    }

    protected override async Task<Attachment> SaveFile(AppDeployVersion entity, IFormFile file, String uploadPath, String fileName)
    {
        var att = await base.SaveFile(entity, file, uploadPath, fileName);
        if (att != null)
        {
            var deploy = entity.Deploy;

            entity.Hash = att.Hash;
            entity.Size = att.Size;
            entity.Url = $"/cube/file?id={att.Id}{att.Extension}";

            entity.Update();

            // 上传完成即发布。即使新增,也是插入后保存文件,然后再来OnUpdate
            if (entity.Enable && !entity.Url.IsNullOrEmpty() && deploy != null && deploy.Enable && deploy.AutoPublish)
            {
                deploy.Version = entity.Version;
                deploy.Update();

                _ = _deployService.PublishEnabledNodes(entity.Deploy, UserHost);
            }
        }

        //// 广播指定附件在当前节点可用
        //await _fileStorage.PublishNewFileAsync(att.Id, att.FilePath, HttpContext.RequestAborted);

        // 不给上层拿到附件,避免Url字段被覆盖
        return null;
    }

    /// <summary>保存文件完成后、广播前执行识别与注入,确保广播携带最终哈希</summary>
    /// <param name="entity">实体对象</param>
    /// <param name="att">附件实体</param>
    /// <param name="uploadPath">上传目录</param>
    /// <param name="file">上传文件</param>
    /// <returns></returns>
    protected override async Task OnFileSaved(AppDeployVersion entity, Attachment att, String uploadPath, IFormFile file)
    {
        var deploy = entity.Deploy;

        // API 版 Cube 的 Attachment 为 NewLife.Cube.Entity.Attachment,
        // 而 DeployService 需要 Stardust.Data.Deployment.Attachment(同一张附件表,按 Id 重新查询桥接)
        var dAtt = ProjectScopeRules.FilterVisible(Stardust.Data.Deployment.Attachment.FindById(att.Id));
        if (dAtt != null)
        {
            _deployService.ReadDotNet(entity, dAtt, uploadPath);

            // 处理Nginx
            if (deploy.Port == 0 || deploy.Urls.IsNullOrEmpty())
                _deployService.ReadNginx(entity, dAtt, uploadPath);
            if (deploy.Port > 0 && !deploy.Urls.IsNullOrEmpty())
                _deployService.BuildNginx(entity, dAtt, uploadPath);
        }

        // 广播(此时附件哈希已更新为最终值,分布式拉取校验一致)
        await base.OnFileSaved(entity, att, uploadPath, file);
    }

    [EntityAuthorize(PermissionFlags.Update)]
    public async Task<ActionResult> UseVersion(Int32 id)
    {
        await _deployService.UseVersion(id, UserHost);
        return JsonRefresh($"成功!");
    }
}