F#로 Azure Files(파일 저장소) 시작하기
F#로 Azure Files(파일 저장소) 시작하기
Azure Files는 표준 SMB(Server Message Block) 프로토콜을 이용해 클라우드에서 파일 공유(File Share)를 제공하는 서비스예요. SMB 2.1과 SMB 3.0을 모두 지원해요. 파일 공유에 의존하던 기존(레거시) 애플리케이션을 비용이 많이 드는 재작성 없이 빠르게 Azure로 옮기고 싶다면, Azure Files가 좋은 선택이에요. Azure 가상 머신이나 클라우드 서비스에서 돌아가는 애플리케이션, 혹은 온프레미스(on-premises) 클라이언트까지 클라우드의 파일 공유를 마운트해서 쓸 수 있어요. 마치 데스크톱 애플리케이션이 평범한 SMB 공유를 마운트하듯 말이죠. 여러 애플리케이션 구성 요소가 동시에 파일 저장소 공유를 마운트하고 접근하는 것도 얼마든지 가능해요.
파일 저장소에 대한 개념적인 개요는 .NET용 파일 저장소 가이드를 참고하면 돼요. 이 튜토리얼들은 편의를 위해 연결 문자열(connection string)로 Azure에 인증해요. 다만 가장 안전한 방법은 관리 ID(managed identities)와 함께 Microsoft Entra ID를 쓰는 거예요.
출처: Get started with Azure Files using F#
본문
사전 준비(Prerequisites)
이 가이드를 따라 하려면 먼저 Azure Storage 계정을 만들어야 해요. 그리고 이 계정의 스토리지 액세스 키(storage access key)도 준비해야 해요.
F# 스크립트 만들고 F# Interactive 시작하기
이 문서의 예제 코드는 F# 애플리케이션에서 써도 되고 F# 스크립트에서 써도 돼요. F# 개발 환경에서 .fsx 확장자 파일(예: files.fsx)을 만들면 F# 스크립트가 돼요.
스크립트 실행하는 법
F# Interactive, 즉 dotnet fsi는 대화형(interactive)으로 실행할 수도 있고, 명령줄에서 스크립트를 돌리도록 실행할 수도 있어요. 명령줄 문법은 이렇게 생겼어요.
> dotnet fsi [options] [ script-file [arguments] ]
스크립트에서 패키지 추가하기
#r "nuget: <패키지 이름>" 문법으로 Azure.Storage.Blobs, Azure.Storage.Common, Azure.Storage.Files 패키지를 설치하고 네임스페이스를 open 하면 돼요. 예를 들면 이렇답니다.
> #r "nuget: Azure.Storage.Blobs"
> #r "nuget: Azure.Storage.Common"
> #r "nuget: Azure.Storage.Files"
open Azure.Storage.Blobs
open Azure.Storage.Sas
open Azure.Storage.Files
open Azure.Storage.Files.Shares
open Azure.Storage.Files.Shares.Models
네임스페이스 선언 추가하기
files.fsx 파일 맨 위에 다음 open 문들을 추가해 주세요.
open System
open System.IO
open Azure
open Azure.Storage // Namespace for StorageSharedKeyCredential
open Azure.Storage.Blobs // Namespace for BlobContainerClient
open Azure.Storage.Sas // Namespace for ShareSasBuilder
open Azure.Storage.Files.Shares // Namespace for File storage types
open Azure.Storage.Files.Shares.Models // Namespace for ShareServiceProperties
연결 문자열 가져오기
이 튜토리얼을 진행하려면 Azure Storage 연결 문자열이 필요해요. 연결 문자열에 대해 더 자세히 알고 싶다면 Configure Storage Connection Strings 문서를 봐 주세요.
튜토리얼에서는 이렇게 스크립트 안에 연결 문자열을 입력해서 쓸 거예요.
let storageConnString = "..." // fill this in from your storage account
파일 서비스 클라이언트 만들기
ShareClient 타입을 쓰면 파일 저장소에 저장된 파일을 코드로 제어할 수 있어요. 서비스 클라이언트를 만드는 방법 중 하나는 아래와 같아요.
let share = ShareClient(storageConnString, "shareName")
이제 파일 저장소에서 데이터를 읽고 쓰는 코드를 작성할 준비가 됐어요.
파일 공유 만들기
이 예제는 파일 공유가 아직 없을 때 새로 만드는 방법을 보여줘요.
share.CreateIfNotExistsAsync()
디렉터리 만들기
여기서는 디렉터리 핸들을 가져와요. 아직 디렉터리가 없다면 새로 만들어요.
// Get a reference to the directory
let directory = share.GetDirectoryClient("directoryName")
// Create the directory if it doesn't already exist
directory.CreateIfNotExistsAsync()
샘플 디렉터리에 파일 업로드하기
이 예제는 샘플 디렉터리에 파일을 업로드하는 방법을 보여줘요.
let file = directory.GetFileClient("fileName")
let writeToFile localFilePath =
use stream = File.OpenRead(localFilePath)
file.Create(stream.Length)
file.UploadRange(
HttpRange(0L, stream.Length),
stream)
writeToFile "localFilePath"
로컬 파일로 다운로드하기
여기서는 방금 만든 파일을 내려받아 그 내용을 로컬 파일에 이어 붙여요.
let download = file.Download()
let copyTo saveDownloadPath =
use downStream = File.OpenWrite(saveDownloadPath)
download.Value.Content.CopyTo(downStream)
copyTo "Save_Download_Path"
파일 공유 최대 크기 설정하기
아래 예제는 공유의 현재 사용량을 확인하고 공유에 대한 할당량(quota)을 설정하는 방법을 보여줘요.
// stats.Usage is current usage in GB
let ONE_GIBIBYTE = 10_737_420_000L // Number of bytes in 1 gibibyte
let stats = share.GetStatistics().Value
let currentGiB = int (stats.ShareUsageInBytes / ONE_GIBIBYTE)
// Set the quota to 10 GB plus current usage
share.SetQuotaAsync(currentGiB + 10)
// Remove the quota
share.SetQuotaAsync(0)
파일 또는 파일 공유용 공유 액세스 서명(SAS) 생성하기
파일 공유용 또는 개별 파일용으로 공유 액세스 서명(SAS, Shared Access Signature)을 생성할 수 있어요. 파일 공유에 공유 액세스 정책(shared access policy)을 만들어서 SAS를 관리할 수도 있어요. 공유 액세스 권한(shared access permissions)을 만들어 쓰는 편이 권장되는데, SAS가 노출됐을 때(compromised) 그 SAS를 취소할 수단이 생기거든요.
여기서 공유에 공유 액세스 권한을 만들고, 그 권한을 공유 안에 있는 파일에 대한 SAS 제약 조건으로 설정해 볼게요.
let accountName = "..." // Input your storage account name
let accountKey = "..." // Input your storage account key
// Create a 24-hour read/write policy.
let expiration = DateTimeOffset.UtcNow.AddHours(24.)
let fileSAS = ShareSasBuilder(
ShareName = "shareName",
FilePath = "filePath",
Resource = "f",
ExpiresOn = expiration)
// Set the permissions for the SAS
let permissions = ShareFileSasPermissions.All
fileSAS.SetPermissions(permissions)
// Create a SharedKeyCredential that we can use to sign the SAS token
let credential = StorageSharedKeyCredential(accountName, accountKey)
// Build a SAS URI
let fileSasUri = UriBuilder($"https://{accountName}.file.core.windows.net/{fileSAS.ShareName}/{fileSAS.FilePath}")
fileSasUri.Query = fileSAS.ToSasQueryParameters(credential).ToString()
공유 액세스 서명을 만들고 사용하는 방법에 대해 더 알고 싶다면 공유 액세스 서명(SAS) 사용하기와 Blob 저장소로 SAS 만들고 사용하기 문서를 참고해 주세요.
파일 복사하기
파일을 다른 파일이나 Blob으로, 또는 Blob을 파일로 복사할 수 있어요. Blob을 파일로, 혹은 파일을 Blob으로 복사할 때는 — 같은 스토리지 계정 안에서 복사하더라도 — 반드시 공유 액세스 서명(SAS)으로 원본 개체를 인증해야 해요.
파일을 다른 파일로 복사하기
여기서는 같은 공유 안의 다른 파일로 파일을 복사해요. 이 복사 연산은 같은 스토리지 계정 안의 파일끼리 복사하는 것이므로, 공유 키(Shared Key) 인증으로 복사를 수행할 수 있어요.
let sourceFile = ShareFileClient(storageConnString, "shareName", "sourceFilePath")
let destFile = ShareFileClient(storageConnString, "shareName", "destFilePath")
destFile.StartCopyAsync(sourceFile.Uri)
파일을 Blob으로 복사하기
여기서는 파일을 만들어 같은 스토리지 계정 안의 Blob으로 복사해요. 원본 파일용 SAS를 만들어 두는데, 복사 연산 중 서비스가 원본 파일에 대한 접근을 인증하는 데 그 SAS를 사용해요.
// Create a new file SAS
let fileSASCopyToBlob = ShareSasBuilder(
ShareName = "shareName",
FilePath = "sourceFilePath",
Resource = "f",
ExpiresOn = DateTimeOffset.UtcNow.AddHours(24.))
let permissionsCopyToBlob = ShareFileSasPermissions.Read
fileSASCopyToBlob.SetPermissions(permissionsCopyToBlob)
let fileSasUriCopyToBlob = UriBuilder($"https://{accountName}.file.core.windows.net/{fileSASCopyToBlob.ShareName}/{fileSASCopyToBlob.FilePath}")
// Get a reference to the file.
let sourceFileCopyToBlob = ShareFileClient(fileSasUriCopyToBlob.Uri)
// Get a reference to the blob to which the file will be copied.
let containerCopyToBlob = BlobContainerClient(storageConnString, "containerName");
containerCopyToBlob.CreateIfNotExists()
let destBlob = containerCopyToBlob.GetBlobClient("blobName")
destBlob.StartCopyFromUriAsync(sourceFileCopyToBlob.Uri)
Blob을 파일로 복사하는 방법도 똑같아요. 원본 개체가 Blob이라면, 복사 연산 중 그 Blob에 대한 접근을 인증하도록 SAS를 만들어 주면 돼요.
메트릭으로 파일 저장소 문제 해결하기
Azure Storage Analytics는 파일 저장소용 메트릭을 지원해요. 메트릭 데이터가 있으면 요청을 추적하고 문제를 진단할 수 있어요.
파일 저장소용 메트릭은 Azure Portal에서 켤 수도 있고, F#에서 이렇게 켤 수도 있어요.
// Instantiate a ShareServiceClient
let shareService = ShareServiceClient(storageConnString);
// Set metrics properties for File service
let props = ShareServiceProperties()
props.HourMetrics = ShareMetrics(
Enabled = true,
IncludeApis = true,
Version = "1.0",
RetentionPolicy = ShareRetentionPolicy(Enabled = true,Days = 14))
props.MinuteMetrics = ShareMetrics(
Enabled = true,
IncludeApis = true,
Version = "1.0",
RetentionPolicy = ShareRetentionPolicy(Enabled = true,Days = 7))
shareService.SetPropertiesAsync(props)
더 알아보기
Azure Files에 대해 더 알고 싶다면 아래 링크를 확인해 보세요.
개념 문서와 동영상
- How to use Azure Files with Linux
- Using Azure PowerShell with Azure Storage
- How to use AzCopy with Microsoft Azure Storage
- Create, download, and list blobs with Azure CLI
참고 자료
블로그 포스트