run_iscsi_target.sh 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env bash
  2. # Copyright 2018 The Kubernetes Authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # This script does not run any daemon, it only configures iSCSI target (=server)
  16. # in kernel. It is possible to run this script multiple times on a single
  17. # node, each run will create its own IQN and LUN.
  18. # Kubernetes must provide unique name.
  19. IQN=$1
  20. # targetcli synchronizes over dbus, however it does not work in
  21. # containers. Use flock instead
  22. LOCK=/srv/iscsi/targetcli.lock
  23. function start()
  24. {
  25. # targetcli need dbus. It may not run on the host, so start a private one
  26. mkdir /run/dbus
  27. dbus-daemon --system
  28. # Create new IQN (iSCSI Qualified Name)
  29. flock $LOCK targetcli /iscsi create "$IQN"
  30. # Run it in demo mode, i.e. no authentication
  31. flock $LOCK targetcli /iscsi/"$IQN"/tpg1 set attribute authentication=0 demo_mode_write_protect=0 generate_node_acls=1 cache_dynamic_acls=1
  32. # Create unique "block volume" (i.e. flat file) on the *host*.
  33. # Having it in the container confuses kernel from some reason
  34. # and it's not able to server multiple LUNs from different
  35. # containers.
  36. # /srv/iscsi must be bind-mount from the host.
  37. cp /block /srv/iscsi/"$IQN"
  38. # Make the block volume available through our IQN as LUN 0
  39. flock $LOCK targetcli /backstores/fileio create block-"$IQN" /srv/iscsi/"$IQN"
  40. flock $LOCK targetcli /iscsi/"$IQN"/tpg1/luns create /backstores/fileio/block-"$IQN"
  41. echo "iscsi target started"
  42. }
  43. function stop()
  44. {
  45. echo "stopping iscsi target"
  46. # Remove IQN
  47. flock $LOCK targetcli /iscsi/"$IQN"/tpg1/luns/ delete 0
  48. flock $LOCK targetcli /iscsi delete "$IQN"
  49. # Remove block device mapping
  50. flock $LOCK targetcli /backstores/fileio delete block-"$IQN"
  51. /bin/rm -f /srv/iscsi/"$IQN"
  52. echo "iscsi target stopped"
  53. exit 0
  54. }
  55. trap stop TERM
  56. start
  57. while true; do
  58. sleep 1
  59. done