すべてのプロダクト
Search
ドキュメントセンター

Function Compute:NASファイルシステムへのアクセス

最終更新日:Sep 09, 2024

Function ComputeでサービスのApsara File Storage NAS (NAS) マウントターゲットを設定した後、サービスの関数にコードを記述して、オンプレミスのファイルシステムと同じ方法でNASファイルシステムのファイルにアクセスできます。 このトピックでは、NASファイルシステムからデータを読み書きするために使用されるサンプル関数コードについて説明します。

前提条件

NASにデータを書き込む関数を作成する

  1. Function Computeコンソールにログインします。 左側のナビゲーションウィンドウで、[サービスと機能] をクリックします。

  2. 上部のナビゲーションバーで、リージョンを選択します。 [サービス] ページで、目的のサービスをクリックします。

  3. [関数] ページで、目的の関数の名前をクリックします。

  4. 関数の詳細ページで、[コード] タブをクリックして、コードエディターでコードを記述します。

    次のサンプルコードでは、Python 3を例として使用しています。

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import random
    import subprocess
    import string
    import os
    
    def handler(event, context):
      # report file system disk space usage and check NAS mount target
      out, err = subprocess.Popen(['df','-h'], stdout = subprocess.PIPE).communicate()
      print('disk: ' + str(out))
      lines = [ l.decode() for l in out.splitlines() if str(l).find(':') != -1 ]
      nas_dirs = [ x.split()[-1] for x in lines ]
      print('uid : ' + str(os.geteuid()))
      print('gid : ' + str(os.getgid()))
      for nas_dir in nas_dirs:
        sub_dir = randomString(16)
        file_name = randomString(6)+'.txt'
        new_dir = nas_dir + '/' + sub_dir + '/'
        print('test file: ' + new_dir + file_name)
        content = "NAS here I come"
        os.mkdir(new_dir)
        fw = open(new_dir + file_name, "w+")
        fw.write(content)
        fw.close()
        # Showing the folder tree in NAS
        for home, dirs, files in os.walk(nas_dir):
          level = home.replace(nas_dir, '').count(os.sep)
          indent = ' ' * 2 * (level)
          print('{}{}/'.format(indent, os.path.basename(home)))
          subindent = ' ' * 2 * (level + 1)
          for f in files:
            print('{}{}'.format(subindent, f))
      return 'success'
    
    def randomString(n):
      return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(n))                     

NASからデータを読み取る関数を作成する

  1. Function Computeコンソールにログインします。 左側のナビゲーションウィンドウで、[サービスと機能] をクリックします。

  2. 上部のナビゲーションバーで、リージョンを選択します。 [サービス] ページで、目的のサービスをクリックします。

  3. [関数] ページで、目的の関数の名前をクリックします。

  4. 関数の詳細ページで、[コード] タブをクリックして、コードエディターでコードを記述します。

    次のサンプルコードでは、Python 3を例として使用しています。

    # -*- coding: utf-8 -*-
    
    def handler(event, context):
    
        f = open("/mnt/test/test.txt", "r")
    
        print(f.readline())
        f.close()
        return 'ok'

    この関数の実行結果は、[NASにデータを書き込む関数を作成] で作成した関数によって書き込まれた内容です。