在《Kubernetes中分佈式存儲Rook-Ceph部署快速演練》文章中,我快速介紹了Kubernetes中分佈式存儲Rook-Ceph的部署過程,這裏介紹如何在部署於Kubernetes的ASP.NET Core MVC的應用程序中使用Rook-Ceph所建立的存儲對象。html
這個程序的基本功能就是用戶能夠經過主頁上傳一個文件並保存到由Rook-Ceph建立的S3對象存儲,同時將文件信息和上傳時間保存爲一個MongoDB的文檔。MongoDB使用Rook-Ceph建立的塊存儲(Block Storage)。
首先,新建一個基於.NET 5的ASP.NET Core MVC應用程序,添加AWSSDK.S3
和MongoDB.Driver
這兩個NuGet Package的引用。
而後,修改Startup.cs
的ConfigureServices
方法:git
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.Configure<FormOptions>(options => { options.MultipartBodyLengthLimit = 268435456; }); var s3Endpoint = Configuration["s3:endpoint"]; var s3AccessKey = Configuration["s3:accessKey"]; var s3SecretKey = Configuration["s3:secretKey"]; var s3Configuration = new AmazonS3Config { RegionEndpoint = RegionEndpoint.USEast1, ServiceURL = s3Endpoint, ForcePathStyle = true }; services.AddTransient<IAmazonS3>(sp => new AmazonS3Client(s3AccessKey, s3SecretKey, s3Configuration)); var mongoConnectionString = Configuration["mongo:connectionString"]; var mongoDatabase = Configuration["mongo:database"]; services.AddTransient<IDataAccessObject>(sp => new MongoDataAccessObject(new MongoUrl(mongoConnectionString), mongoDatabase)); }
這裏用到了配置信息,爲了調試方便,能夠修改appsettings.json
文件,添加對於S3和MongoDB的配置信息:github
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "s3": { "endpoint": "http://localhost:9000", "accessKey": "AKIAIOSFODNN7EXAMPLE", "secretKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" }, "mongo": { "connectionString": "mongodb://localhost:27017", "database": "form-file-upload" }, "AllowedHosts": "*" }
以後,修改Index.cshtml
文件,將界面元素準備好:mongodb
@{ ViewData["Title"] = "Home Page"; } @model FileUploadModel <div class="text-center"> <h1 class="display-4">Welcome</h1> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index"> <div class="form-group"> <div class="col-md-10"> <p>Upload one or more files using this form:</p> <input type="file" name="file" /> </div> </div> <div class="form-group"> <div class="col-md-10"> <input type="submit" value="Save" /> </div> </div> </form> </div>
修改HomeController:docker
public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly IDataAccessObject _dao; private readonly IAmazonS3 _s3; public HomeController(ILogger<HomeController> logger, IAmazonS3 s3, IDataAccessObject dao) => (_logger, _s3, _dao) = (logger, s3, dao); public IActionResult Index() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Index(FileUploadModel model) { if (model.File != null) { var fileName = Path.GetFileName(model.File.FileName); var fileTransUtility = new TransferUtility(_s3); using var stream = model.File.OpenReadStream(); await fileTransUtility.UploadAsync(stream, "data", $"FormFileUpload/{fileName}"); await _dao.AddAsync<SavedFile>(new SavedFile { Timestamp = DateTime.UtcNow, FileName = fileName }); return View(); } else { } return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } }
其它相關代碼這裏就不所有貼出來了,能夠直接參考本案例的源代碼。
在開發模式下,我使用運行於Docker的MongoDB以及MINIO分別做爲數據庫後端和S3服務後端。在按下F5進行Debug以前,請先確保MongoDB和MINIO已經運行。能夠參考https://github.com/daxnet/form-file-upload/blob/main/docker-compose.yml。shell
仍然使用上面提到的docker-compose.yml文件,而後使用下面的命令來生成HELM Chart:數據庫
kompose convert -f docker-compose.yml -c -o k8s
執行成功後會在k8s的目錄下產生用於部署到Kubernetes的HELM Chart。完整內容能夠參考:https://github.com/daxnet/form-file-upload/tree/main/k8s
須要注意幾個內容:json
要使用Ceph Object Store,只須要正確配置app中S3的Access Key、Secret Key以及Endpoint便可。對應的就是form-file-upload-service-deployment.yaml
中的s3__accessKey
、s3__endpoint
和s3__secretKey
環境變量設置。它們的取值在《Kubernetes中分佈式存儲Rook-Ceph部署快速演練》文章中已經介紹過了,只是在Endpoint的Host名稱上須要加上http://
。詳細能夠參考values.yaml文件。後端
部署到Kubernetes的MongoDB會須要使用Ceph Block Storage。在mongodb-deployment.yaml
中,會指定容器的volumeMount:api
volumeMounts: - mountPath: /data/db name: mongo-data
而後在Volume的定義部分,指定使用名爲{{ .Release.Name }}-form-file-upload-mongo-data
的PersistentVolumeClaim:
volumes: - name: mongo-data persistentVolumeClaim: claimName: {{ .Release.Name }}-form-file-upload-mongo-data
這裏的{{ .Release.Name }}
表示HELM的release的名字。接下來,在這個PersistentVolumeClaim中(mongo-data-persistentvolumeclaim.yaml),能夠指定所需使用的StorageClass:
spec: accessModes: - ReadWriteOnce resources: requests: storage: 20Gi storageClassName: {{ .Values.mongoStorageClassName }}
在這裏,storageClassName
在values.yaml
中設置:
mongoStorageClassName: "rook-ceph-block"
而rook-ceph-block
就是咱們在前文中建立的Block Storage的名字。
使用git將https://github.com/daxnet/form-file-upload.git克隆到本地,進入k8s目錄,而後:
helm install ffu .
安裝成功後,查看pods:
$ kubectl get po NAME READY STATUS RESTARTS AGE dnsutils 1/1 Running 2 160m ffu-form-file-upload-mongo-8c46f48fc-vm76k 1/1 Running 0 23m ffu-form-file-upload-service-7c5c679b96-rxl5s 1/1 Running 0 23m
查看PersistentVolumeClaims:
$ kubectl get pvc NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE ffu-form-file-upload-mongo-data Bound pvc-8e681be4-4378-11eb-8a9b-0ac973bf1e37 20Gi RWO rook-ceph-block 64m
能夠看到,ffu-form-file-upload-mongo-data
這個PVC使用的StorageClass就是rook-ceph-block。
查看Services:
$ kubectl get svc NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE ffu-form-file-upload-mongo ClusterIP 10.43.83.79 <none> 27017/TCP 65m ffu-form-file-upload-service ClusterIP 10.43.57.233 <none> 8080/TCP 65m kubernetes ClusterIP 10.43.0.1 <none> 443/TCP 3d10h
經過port-forward來訪問應用程序:
$ kubectl port-forward svc/ffu-form-file-upload-service 8081:8080 Forwarding from 127.0.0.1:8081 -> 80 Forwarding from [::1]:8081 -> 80
打開瀏覽器,訪問http://localhost:8081
:
點擊Choose File按鈕,選擇一個文件(測試方便儘可能選擇小一點的文件)點擊Save。成功後沒有任何信息提示,會返回到沒有上傳文件時的狀態。
使用下面的命令查看S3中已經保存的文件:
$ kubectl exec -it -n rook-ceph deploy/rook-ceph-tools -- s3cmd ls s3://data/FormFileUpload/ 2020-12-21 11:47 1260 s3://data/FormFileUpload/abc.sldimport
能夠看到,文件已經成功上傳到S3。
使用下面的命令查看MongoDB中的數據:
$ kubectl exec -it deploy/ffu-form-file-upload-mongo -- mongo --eval "db.SavedFile.find().pretty()" form-file-upload MongoDB shell version v3.6.21 connecting to: mongodb://127.0.0.1:27017/form-file-upload?gssapiServiceName=mongodb Implicit session: session { "id" : UUID("85f7d362-13d6-41b9-90f9-9de86f711eb0") } MongoDB server version: 3.6.21 { "_id" : BinData(3,"NyKi+5Q5N0O9B1bIddlk/g=="), "Timestamp" : ISODate("2020-12-21T11:47:01.853Z"), "FileName" : "abc.sldimport" }
能夠看到,數據記錄已經成功保存到MongoDB。
一切的一切,盡在https://github.com/daxnet/form-file-upload。 Enjoy!